blob: 852d442ace0ec6cbdbd637a6c40ffd5e8d236f0c [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 Lattnerc8802d22003-03-11 00:12:48 +000080// isOnlyUse - Return true if this instruction will be deleted if we stop using
81// it.
82static bool isOnlyUse(Value *V) {
Chris Lattnerfd059242003-10-15 16:48:29 +000083 return V->hasOneUse() || isa<Constant>(V);
Chris Lattnerc8802d22003-03-11 00:12:48 +000084}
85
Chris Lattner4cb170c2004-02-23 06:38:22 +000086// getPromotedType - Return the specified type promoted as it would be to pass
87// though a va_arg area...
88static const Type *getPromotedType(const Type *Ty) {
Reid Spencera54b7cb2007-01-12 07:05:14 +000089 if (const IntegerType* ITy = dyn_cast<IntegerType>(Ty)) {
90 if (ITy->getBitWidth() < 32)
Owen Anderson1d0be152009-08-13 21:58:54 +000091 return Type::getInt32Ty(Ty->getContext());
Chris Lattner2b7e0ad2007-05-23 01:17:04 +000092 }
Reid Spencera54b7cb2007-01-12 07:05:14 +000093 return Ty;
Chris Lattner4cb170c2004-02-23 06:38:22 +000094}
95
Chris Lattnerc22d4d12009-11-10 07:23:37 +000096/// ShouldChangeType - Return true if it is desirable to convert a computation
97/// from 'From' to 'To'. We don't want to convert from a legal to an illegal
98/// type for example, or from a smaller to a larger illegal type.
Chris Lattner80f43d32010-01-04 07:53:58 +000099bool InstCombiner::ShouldChangeType(const Type *From, const Type *To) const {
Chris Lattnerc22d4d12009-11-10 07:23:37 +0000100 assert(isa<IntegerType>(From) && isa<IntegerType>(To));
101
102 // If we don't have TD, we don't know if the source/dest are legal.
103 if (!TD) return false;
104
105 unsigned FromWidth = From->getPrimitiveSizeInBits();
106 unsigned ToWidth = To->getPrimitiveSizeInBits();
107 bool FromLegal = TD->isLegalInteger(FromWidth);
108 bool ToLegal = TD->isLegalInteger(ToWidth);
109
110 // If this is a legal integer from type, and the result would be an illegal
111 // type, don't do the transformation.
112 if (FromLegal && !ToLegal)
113 return false;
114
115 // Otherwise, if both are illegal, do not increase the size of the result. We
116 // do allow things like i160 -> i64, but not i64 -> i160.
117 if (!FromLegal && !ToLegal && ToWidth > FromWidth)
118 return false;
119
120 return true;
121}
122
Matthijs Kooijman7e6d9b92008-10-13 15:17:01 +0000123/// getBitCastOperand - If the specified operand is a CastInst, a constant
124/// expression bitcast, or a GetElementPtrInst with all zero indices, return the
125/// operand value, otherwise return null.
Reid Spencer3da59db2006-11-27 01:05:10 +0000126static Value *getBitCastOperand(Value *V) {
Dan Gohman016de812009-07-17 23:55:56 +0000127 if (Operator *O = dyn_cast<Operator>(V)) {
128 if (O->getOpcode() == Instruction::BitCast)
129 return O->getOperand(0);
130 if (GEPOperator *GEP = dyn_cast<GEPOperator>(V))
131 if (GEP->hasAllZeroIndices())
132 return GEP->getPointerOperand();
Matthijs Kooijman7e6d9b92008-10-13 15:17:01 +0000133 }
Chris Lattnereed48272005-09-13 00:40:14 +0000134 return 0;
135}
136
Dan Gohmance9fe9f2009-07-21 23:21:54 +0000137
Chris Lattner33a61132006-05-06 09:00:16 +0000138
Chris Lattner4f98c562003-03-10 21:43:22 +0000139// SimplifyCommutative - This performs a few simplifications for commutative
140// operators:
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000141//
Chris Lattner4f98c562003-03-10 21:43:22 +0000142// 1. Order operands such that they are listed from right (least complex) to
143// left (most complex). This puts constants before unary operators before
144// binary operators.
145//
Chris Lattnerc8802d22003-03-11 00:12:48 +0000146// 2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
147// 3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattner4f98c562003-03-10 21:43:22 +0000148//
Chris Lattnerc8802d22003-03-11 00:12:48 +0000149bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +0000150 bool Changed = false;
Dan Gohman14ef4f02009-08-29 23:39:38 +0000151 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
Chris Lattner4f98c562003-03-10 21:43:22 +0000152 Changed = !I.swapOperands();
Misha Brukmanfd939082005-04-21 23:48:37 +0000153
Chris Lattner4f98c562003-03-10 21:43:22 +0000154 if (!I.isAssociative()) return Changed;
155 Instruction::BinaryOps Opcode = I.getOpcode();
Chris Lattnerc8802d22003-03-11 00:12:48 +0000156 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
157 if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
158 if (isa<Constant>(I.getOperand(1))) {
Owen Andersonbaf3c402009-07-29 18:55:55 +0000159 Constant *Folded = ConstantExpr::get(I.getOpcode(),
Chris Lattner2a9c8472003-05-27 16:40:51 +0000160 cast<Constant>(I.getOperand(1)),
161 cast<Constant>(Op->getOperand(1)));
Chris Lattnerc8802d22003-03-11 00:12:48 +0000162 I.setOperand(0, Op->getOperand(0));
163 I.setOperand(1, Folded);
164 return true;
165 } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
166 if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
167 isOnlyUse(Op) && isOnlyUse(Op1)) {
168 Constant *C1 = cast<Constant>(Op->getOperand(1));
169 Constant *C2 = cast<Constant>(Op1->getOperand(1));
170
171 // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Owen Andersonbaf3c402009-07-29 18:55:55 +0000172 Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000173 Instruction *New = BinaryOperator::Create(Opcode, Op->getOperand(0),
Chris Lattnerc8802d22003-03-11 00:12:48 +0000174 Op1->getOperand(0),
175 Op1->getName(), &I);
Chris Lattner7a1e9242009-08-30 06:13:40 +0000176 Worklist.Add(New);
Chris Lattnerc8802d22003-03-11 00:12:48 +0000177 I.setOperand(0, New);
178 I.setOperand(1, Folded);
179 return true;
Misha Brukmanfd939082005-04-21 23:48:37 +0000180 }
Chris Lattner4f98c562003-03-10 21:43:22 +0000181 }
Chris Lattner4f98c562003-03-10 21:43:22 +0000182 return Changed;
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000183}
Chris Lattner8a2a3112001-12-14 16:52:21 +0000184
Chris Lattner8d969642003-03-10 23:06:50 +0000185// dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
186// if the LHS is a constant zero (which is the 'negate' form).
Chris Lattnerb35dde12002-05-06 16:49:18 +0000187//
Chris Lattner02446fc2010-01-04 07:37:31 +0000188Value *InstCombiner::dyn_castNegVal(Value *V) const {
Owen Andersonfa82b6e2009-07-13 22:18:28 +0000189 if (BinaryOperator::isNeg(V))
Chris Lattnera1df33c2005-04-24 07:30:14 +0000190 return BinaryOperator::getNegArgument(V);
Chris Lattner8d969642003-03-10 23:06:50 +0000191
Chris Lattner0ce85802004-12-14 20:08:06 +0000192 // Constants can be considered to be negated values if they can be folded.
193 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
Owen Andersonbaf3c402009-07-29 18:55:55 +0000194 return ConstantExpr::getNeg(C);
Nick Lewycky18b3da62008-05-23 04:54:45 +0000195
196 if (ConstantVector *C = dyn_cast<ConstantVector>(V))
197 if (C->getType()->getElementType()->isInteger())
Owen Andersonbaf3c402009-07-29 18:55:55 +0000198 return ConstantExpr::getNeg(C);
Nick Lewycky18b3da62008-05-23 04:54:45 +0000199
Chris Lattner8d969642003-03-10 23:06:50 +0000200 return 0;
Chris Lattnerb35dde12002-05-06 16:49:18 +0000201}
202
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000203// dyn_castFNegVal - Given a 'fsub' instruction, return the RHS of the
204// instruction if the LHS is a constant negative zero (which is the 'negate'
205// form).
206//
Dan Gohman186a6362009-08-12 16:04:34 +0000207static inline Value *dyn_castFNegVal(Value *V) {
Owen Andersonfa82b6e2009-07-13 22:18:28 +0000208 if (BinaryOperator::isFNeg(V))
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000209 return BinaryOperator::getFNegArgument(V);
210
211 // Constants can be considered to be negated values if they can be folded.
212 if (ConstantFP *C = dyn_cast<ConstantFP>(V))
Owen Andersonbaf3c402009-07-29 18:55:55 +0000213 return ConstantExpr::getFNeg(C);
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000214
215 if (ConstantVector *C = dyn_cast<ConstantVector>(V))
216 if (C->getType()->getElementType()->isFloatingPoint())
Owen Andersonbaf3c402009-07-29 18:55:55 +0000217 return ConstantExpr::getFNeg(C);
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000218
219 return 0;
220}
221
Chris Lattnerb109b5c2009-12-21 06:03:05 +0000222/// MatchSelectPattern - Pattern match integer [SU]MIN, [SU]MAX, and ABS idioms,
223/// returning the kind and providing the out parameter results if we
224/// successfully match.
225static SelectPatternFlavor
226MatchSelectPattern(Value *V, Value *&LHS, Value *&RHS) {
227 SelectInst *SI = dyn_cast<SelectInst>(V);
228 if (SI == 0) return SPF_UNKNOWN;
229
230 ICmpInst *ICI = dyn_cast<ICmpInst>(SI->getCondition());
231 if (ICI == 0) return SPF_UNKNOWN;
232
233 LHS = ICI->getOperand(0);
234 RHS = ICI->getOperand(1);
235
236 // (icmp X, Y) ? X : Y
237 if (SI->getTrueValue() == ICI->getOperand(0) &&
238 SI->getFalseValue() == ICI->getOperand(1)) {
239 switch (ICI->getPredicate()) {
240 default: return SPF_UNKNOWN; // Equality.
241 case ICmpInst::ICMP_UGT:
242 case ICmpInst::ICMP_UGE: return SPF_UMAX;
243 case ICmpInst::ICMP_SGT:
244 case ICmpInst::ICMP_SGE: return SPF_SMAX;
245 case ICmpInst::ICMP_ULT:
246 case ICmpInst::ICMP_ULE: return SPF_UMIN;
247 case ICmpInst::ICMP_SLT:
248 case ICmpInst::ICMP_SLE: return SPF_SMIN;
249 }
250 }
251
252 // (icmp X, Y) ? Y : X
253 if (SI->getTrueValue() == ICI->getOperand(1) &&
254 SI->getFalseValue() == ICI->getOperand(0)) {
255 switch (ICI->getPredicate()) {
256 default: return SPF_UNKNOWN; // Equality.
257 case ICmpInst::ICMP_UGT:
258 case ICmpInst::ICMP_UGE: return SPF_UMIN;
259 case ICmpInst::ICMP_SGT:
260 case ICmpInst::ICMP_SGE: return SPF_SMIN;
261 case ICmpInst::ICMP_ULT:
262 case ICmpInst::ICMP_ULE: return SPF_UMAX;
263 case ICmpInst::ICMP_SLT:
264 case ICmpInst::ICMP_SLE: return SPF_SMAX;
265 }
266 }
267
268 // TODO: (X > 4) ? X : 5 --> (X >= 5) ? X : 5 --> MAX(X, 5)
269
270 return SPF_UNKNOWN;
271}
272
Chris Lattner48b59ec2009-10-26 15:40:07 +0000273/// isFreeToInvert - Return true if the specified value is free to invert (apply
274/// ~ to). This happens in cases where the ~ can be eliminated.
275static inline bool isFreeToInvert(Value *V) {
276 // ~(~(X)) -> X.
Evan Cheng85def162009-10-26 03:51:32 +0000277 if (BinaryOperator::isNot(V))
Chris Lattner48b59ec2009-10-26 15:40:07 +0000278 return true;
279
280 // Constants can be considered to be not'ed values.
281 if (isa<ConstantInt>(V))
282 return true;
283
284 // Compares can be inverted if they have a single use.
285 if (CmpInst *CI = dyn_cast<CmpInst>(V))
286 return CI->hasOneUse();
287
288 return false;
289}
290
291static inline Value *dyn_castNotVal(Value *V) {
292 // If this is not(not(x)) don't return that this is a not: we want the two
293 // not's to be folded first.
294 if (BinaryOperator::isNot(V)) {
295 Value *Operand = BinaryOperator::getNotArgument(V);
296 if (!isFreeToInvert(Operand))
297 return Operand;
298 }
Chris Lattner8d969642003-03-10 23:06:50 +0000299
300 // Constants can be considered to be not'ed values...
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000301 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
Dan Gohman186a6362009-08-12 16:04:34 +0000302 return ConstantInt::get(C->getType(), ~C->getValue());
Chris Lattner8d969642003-03-10 23:06:50 +0000303 return 0;
304}
305
Chris Lattner48b59ec2009-10-26 15:40:07 +0000306
307
Chris Lattnerc8802d22003-03-11 00:12:48 +0000308// dyn_castFoldableMul - If this value is a multiply that can be folded into
309// other computations (because it has a constant operand), return the
Chris Lattner50af16a2004-11-13 19:50:12 +0000310// non-constant operand of the multiply, and set CST to point to the multiplier.
311// Otherwise, return null.
Chris Lattnerc8802d22003-03-11 00:12:48 +0000312//
Dan Gohman186a6362009-08-12 16:04:34 +0000313static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST) {
Chris Lattner42a75512007-01-15 02:27:26 +0000314 if (V->hasOneUse() && V->getType()->isInteger())
Chris Lattner50af16a2004-11-13 19:50:12 +0000315 if (Instruction *I = dyn_cast<Instruction>(V)) {
Chris Lattnerc8802d22003-03-11 00:12:48 +0000316 if (I->getOpcode() == Instruction::Mul)
Chris Lattner50e60c72004-11-15 05:54:07 +0000317 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
Chris Lattnerc8802d22003-03-11 00:12:48 +0000318 return I->getOperand(0);
Chris Lattner50af16a2004-11-13 19:50:12 +0000319 if (I->getOpcode() == Instruction::Shl)
Chris Lattner50e60c72004-11-15 05:54:07 +0000320 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
Chris Lattner50af16a2004-11-13 19:50:12 +0000321 // The multiplier is really 1 << CST.
Zhou Sheng97b52c22007-03-29 01:57:21 +0000322 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +0000323 uint32_t CSTVal = CST->getLimitedValue(BitWidth);
Dan Gohman186a6362009-08-12 16:04:34 +0000324 CST = ConstantInt::get(V->getType()->getContext(),
325 APInt(BitWidth, 1).shl(CSTVal));
Chris Lattner50af16a2004-11-13 19:50:12 +0000326 return I->getOperand(0);
327 }
328 }
Chris Lattnerc8802d22003-03-11 00:12:48 +0000329 return 0;
Chris Lattnera2881962003-02-18 19:28:33 +0000330}
Chris Lattneraf2930e2002-08-14 17:51:49 +0000331
Reid Spencer7177c3a2007-03-25 05:33:51 +0000332/// AddOne - Add one to a ConstantInt
Dan Gohman186a6362009-08-12 16:04:34 +0000333static Constant *AddOne(Constant *C) {
Chris Lattner02446fc2010-01-04 07:37:31 +0000334 return ConstantExpr::getAdd(C, ConstantInt::get(C->getType(), 1));
Chris Lattner955f3312004-09-28 21:48:02 +0000335}
Reid Spencer7177c3a2007-03-25 05:33:51 +0000336/// SubOne - Subtract one from a ConstantInt
Dan Gohman186a6362009-08-12 16:04:34 +0000337static Constant *SubOne(ConstantInt *C) {
Chris Lattner02446fc2010-01-04 07:37:31 +0000338 return ConstantExpr::getSub(C, ConstantInt::get(C->getType(), 1));
Chris Lattner955f3312004-09-28 21:48:02 +0000339}
Nick Lewyckye0cfecf2008-02-18 22:48:05 +0000340/// MultiplyOverflows - True if the multiply can not be expressed in an int
341/// this size.
Dan Gohman186a6362009-08-12 16:04:34 +0000342static bool MultiplyOverflows(ConstantInt *C1, ConstantInt *C2, bool sign) {
Nick Lewyckye0cfecf2008-02-18 22:48:05 +0000343 uint32_t W = C1->getBitWidth();
344 APInt LHSExt = C1->getValue(), RHSExt = C2->getValue();
345 if (sign) {
346 LHSExt.sext(W * 2);
347 RHSExt.sext(W * 2);
348 } else {
349 LHSExt.zext(W * 2);
350 RHSExt.zext(W * 2);
351 }
352
353 APInt MulExt = LHSExt * RHSExt;
354
Chris Lattnerb109b5c2009-12-21 06:03:05 +0000355 if (!sign)
Nick Lewyckye0cfecf2008-02-18 22:48:05 +0000356 return MulExt.ugt(APInt::getLowBitsSet(W * 2, W));
Chris Lattnerb109b5c2009-12-21 06:03:05 +0000357
358 APInt Min = APInt::getSignedMinValue(W).sext(W * 2);
359 APInt Max = APInt::getSignedMaxValue(W).sext(W * 2);
360 return MulExt.slt(Min) || MulExt.sgt(Max);
Nick Lewyckye0cfecf2008-02-18 22:48:05 +0000361}
Chris Lattner955f3312004-09-28 21:48:02 +0000362
Reid Spencere7816b52007-03-08 01:52:58 +0000363
Dan Gohman45b4e482008-05-19 22:14:15 +0000364
Chris Lattner564a7272003-08-13 19:01:45 +0000365/// AssociativeOpt - Perform an optimization on an associative operator. This
366/// function is designed to check a chain of associative operators for a
367/// potential to apply a certain optimization. Since the optimization may be
368/// applicable if the expression was reassociated, this checks the chain, then
369/// reassociates the expression as necessary to expose the optimization
370/// opportunity. This makes use of a special Functor, which must define
371/// 'shouldApply' and 'apply' methods.
372///
373template<typename Functor>
Dan Gohman186a6362009-08-12 16:04:34 +0000374static Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
Chris Lattner564a7272003-08-13 19:01:45 +0000375 unsigned Opcode = Root.getOpcode();
376 Value *LHS = Root.getOperand(0);
377
378 // Quick check, see if the immediate LHS matches...
379 if (F.shouldApply(LHS))
380 return F.apply(Root);
381
382 // Otherwise, if the LHS is not of the same opcode as the root, return.
383 Instruction *LHSI = dyn_cast<Instruction>(LHS);
Chris Lattnerfd059242003-10-15 16:48:29 +0000384 while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
Chris Lattner564a7272003-08-13 19:01:45 +0000385 // Should we apply this transform to the RHS?
386 bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
387
388 // If not to the RHS, check to see if we should apply to the LHS...
389 if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
390 cast<BinaryOperator>(LHSI)->swapOperands(); // Make the LHS the RHS
391 ShouldApply = true;
392 }
393
394 // If the functor wants to apply the optimization to the RHS of LHSI,
395 // reassociate the expression from ((? op A) op B) to (? op (A op B))
396 if (ShouldApply) {
Chris Lattner564a7272003-08-13 19:01:45 +0000397 // Now all of the instructions are in the current basic block, go ahead
398 // and perform the reassociation.
399 Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
400
401 // First move the selected RHS to the LHS of the root...
402 Root.setOperand(0, LHSI->getOperand(1));
403
404 // Make what used to be the LHS of the root be the user of the root...
405 Value *ExtraOperand = TmpLHSI->getOperand(1);
Chris Lattner65725312004-04-16 18:08:07 +0000406 if (&Root == TmpLHSI) {
Owen Andersona7235ea2009-07-31 20:28:14 +0000407 Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
Chris Lattner15a76c02004-04-05 02:10:19 +0000408 return 0;
409 }
Chris Lattner65725312004-04-16 18:08:07 +0000410 Root.replaceAllUsesWith(TmpLHSI); // Users now use TmpLHSI
Chris Lattner564a7272003-08-13 19:01:45 +0000411 TmpLHSI->setOperand(1, &Root); // TmpLHSI now uses the root
Chris Lattner65725312004-04-16 18:08:07 +0000412 BasicBlock::iterator ARI = &Root; ++ARI;
Dan Gohmand02d9172008-06-19 17:47:47 +0000413 TmpLHSI->moveBefore(ARI); // Move TmpLHSI to after Root
Chris Lattner65725312004-04-16 18:08:07 +0000414 ARI = Root;
Chris Lattner564a7272003-08-13 19:01:45 +0000415
416 // Now propagate the ExtraOperand down the chain of instructions until we
417 // get to LHSI.
418 while (TmpLHSI != LHSI) {
419 Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
Chris Lattner65725312004-04-16 18:08:07 +0000420 // Move the instruction to immediately before the chain we are
421 // constructing to avoid breaking dominance properties.
Dan Gohmand02d9172008-06-19 17:47:47 +0000422 NextLHSI->moveBefore(ARI);
Chris Lattner65725312004-04-16 18:08:07 +0000423 ARI = NextLHSI;
424
Chris Lattner564a7272003-08-13 19:01:45 +0000425 Value *NextOp = NextLHSI->getOperand(1);
426 NextLHSI->setOperand(1, ExtraOperand);
427 TmpLHSI = NextLHSI;
428 ExtraOperand = NextOp;
429 }
Misha Brukmanfd939082005-04-21 23:48:37 +0000430
Chris Lattner564a7272003-08-13 19:01:45 +0000431 // Now that the instructions are reassociated, have the functor perform
432 // the transformation...
433 return F.apply(Root);
434 }
Misha Brukmanfd939082005-04-21 23:48:37 +0000435
Chris Lattner564a7272003-08-13 19:01:45 +0000436 LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
437 }
438 return 0;
439}
440
Dan Gohman844731a2008-05-13 00:00:25 +0000441namespace {
Chris Lattner564a7272003-08-13 19:01:45 +0000442
Nick Lewycky02d639f2008-05-23 04:34:58 +0000443// AddRHS - Implements: X + X --> X << 1
Chris Lattner564a7272003-08-13 19:01:45 +0000444struct AddRHS {
445 Value *RHS;
Dan Gohman4ae51262009-08-12 16:23:25 +0000446 explicit AddRHS(Value *rhs) : RHS(rhs) {}
Chris Lattner564a7272003-08-13 19:01:45 +0000447 bool shouldApply(Value *LHS) const { return LHS == RHS; }
448 Instruction *apply(BinaryOperator &Add) const {
Nick Lewycky02d639f2008-05-23 04:34:58 +0000449 return BinaryOperator::CreateShl(Add.getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +0000450 ConstantInt::get(Add.getType(), 1));
Chris Lattner564a7272003-08-13 19:01:45 +0000451 }
452};
453
454// AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
455// iff C1&C2 == 0
456struct AddMaskingAnd {
457 Constant *C2;
Dan Gohman4ae51262009-08-12 16:23:25 +0000458 explicit AddMaskingAnd(Constant *c) : C2(c) {}
Chris Lattner564a7272003-08-13 19:01:45 +0000459 bool shouldApply(Value *LHS) const {
Chris Lattneracd1f0f2004-07-30 07:50:03 +0000460 ConstantInt *C1;
Dan Gohman4ae51262009-08-12 16:23:25 +0000461 return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
Owen Andersonbaf3c402009-07-29 18:55:55 +0000462 ConstantExpr::getAnd(C1, C2)->isNullValue();
Chris Lattner564a7272003-08-13 19:01:45 +0000463 }
464 Instruction *apply(BinaryOperator &Add) const {
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000465 return BinaryOperator::CreateOr(Add.getOperand(0), Add.getOperand(1));
Chris Lattner564a7272003-08-13 19:01:45 +0000466 }
467};
468
Dan Gohman844731a2008-05-13 00:00:25 +0000469}
470
Chris Lattner6e7ba452005-01-01 16:22:27 +0000471static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
Chris Lattner2eefe512004-04-09 19:05:30 +0000472 InstCombiner *IC) {
Chris Lattner08142f22009-08-30 19:47:22 +0000473 if (CastInst *CI = dyn_cast<CastInst>(&I))
Chris Lattner2345d1d2009-08-30 20:01:10 +0000474 return IC->Builder->CreateCast(CI->getOpcode(), SO, I.getType());
Chris Lattner6e7ba452005-01-01 16:22:27 +0000475
Chris Lattner2eefe512004-04-09 19:05:30 +0000476 // Figure out if the constant is the left or the right argument.
Chris Lattner6e7ba452005-01-01 16:22:27 +0000477 bool ConstIsRHS = isa<Constant>(I.getOperand(1));
478 Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
Chris Lattner564a7272003-08-13 19:01:45 +0000479
Chris Lattner2eefe512004-04-09 19:05:30 +0000480 if (Constant *SOC = dyn_cast<Constant>(SO)) {
481 if (ConstIsRHS)
Owen Andersonbaf3c402009-07-29 18:55:55 +0000482 return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
483 return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
Chris Lattner2eefe512004-04-09 19:05:30 +0000484 }
485
486 Value *Op0 = SO, *Op1 = ConstOperand;
487 if (!ConstIsRHS)
488 std::swap(Op0, Op1);
Chris Lattner74381062009-08-30 07:44:24 +0000489
Chris Lattner6e7ba452005-01-01 16:22:27 +0000490 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
Chris Lattner74381062009-08-30 07:44:24 +0000491 return IC->Builder->CreateBinOp(BO->getOpcode(), Op0, Op1,
492 SO->getName()+".op");
493 if (ICmpInst *CI = dyn_cast<ICmpInst>(&I))
494 return IC->Builder->CreateICmp(CI->getPredicate(), Op0, Op1,
495 SO->getName()+".cmp");
496 if (FCmpInst *CI = dyn_cast<FCmpInst>(&I))
497 return IC->Builder->CreateICmp(CI->getPredicate(), Op0, Op1,
498 SO->getName()+".cmp");
499 llvm_unreachable("Unknown binary instruction type!");
Chris Lattner6e7ba452005-01-01 16:22:27 +0000500}
501
502// FoldOpIntoSelect - Given an instruction with a select as one operand and a
503// constant as the other operand, try to fold the binary operator into the
504// select arguments. This also works for Cast instructions, which obviously do
505// not have a second operand.
Chris Lattner80f43d32010-01-04 07:53:58 +0000506Instruction *InstCombiner::FoldOpIntoSelect(Instruction &Op, SelectInst *SI) {
Chris Lattner6e7ba452005-01-01 16:22:27 +0000507 // Don't modify shared select instructions
508 if (!SI->hasOneUse()) return 0;
509 Value *TV = SI->getOperand(1);
510 Value *FV = SI->getOperand(2);
511
512 if (isa<Constant>(TV) || isa<Constant>(FV)) {
Chris Lattner956db272005-04-21 05:43:13 +0000513 // Bool selects with constant operands can be folded to logical ops.
Chris Lattner4de84762010-01-04 07:02:48 +0000514 if (SI->getType() == Type::getInt1Ty(SI->getContext())) return 0;
Chris Lattner956db272005-04-21 05:43:13 +0000515
Chris Lattner80f43d32010-01-04 07:53:58 +0000516 Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, this);
517 Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, this);
Chris Lattner6e7ba452005-01-01 16:22:27 +0000518
Gabor Greif051a9502008-04-06 20:25:17 +0000519 return SelectInst::Create(SI->getCondition(), SelectTrueVal,
520 SelectFalseVal);
Chris Lattner6e7ba452005-01-01 16:22:27 +0000521 }
522 return 0;
Chris Lattner2eefe512004-04-09 19:05:30 +0000523}
524
Chris Lattner4e998b22004-09-29 05:07:12 +0000525
Chris Lattner5d1704d2009-09-27 19:57:57 +0000526/// FoldOpIntoPhi - Given a binary operator, cast instruction, or select which
527/// has a PHI node as operand #0, see if we can fold the instruction into the
528/// PHI (which is only possible if all operands to the PHI are constants).
Chris Lattner213cd612009-09-27 20:46:36 +0000529///
530/// If AllowAggressive is true, FoldOpIntoPhi will allow certain transforms
531/// that would normally be unprofitable because they strongly encourage jump
532/// threading.
533Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I,
534 bool AllowAggressive) {
535 AllowAggressive = false;
Chris Lattner4e998b22004-09-29 05:07:12 +0000536 PHINode *PN = cast<PHINode>(I.getOperand(0));
Chris Lattnerbac32862004-11-14 19:13:23 +0000537 unsigned NumPHIValues = PN->getNumIncomingValues();
Chris Lattner213cd612009-09-27 20:46:36 +0000538 if (NumPHIValues == 0 ||
539 // We normally only transform phis with a single use, unless we're trying
540 // hard to make jump threading happen.
541 (!PN->hasOneUse() && !AllowAggressive))
542 return 0;
543
544
Chris Lattner5d1704d2009-09-27 19:57:57 +0000545 // Check to see if all of the operands of the PHI are simple constants
546 // (constantint/constantfp/undef). If there is one non-constant value,
Chris Lattnerc6df8f42009-09-27 20:18:49 +0000547 // remember the BB it is in. If there is more than one or if *it* is a PHI,
548 // bail out. We don't do arbitrary constant expressions here because moving
549 // their computation can be expensive without a cost model.
Chris Lattner2a86f3b2006-09-09 22:02:56 +0000550 BasicBlock *NonConstBB = 0;
551 for (unsigned i = 0; i != NumPHIValues; ++i)
Chris Lattner5d1704d2009-09-27 19:57:57 +0000552 if (!isa<Constant>(PN->getIncomingValue(i)) ||
553 isa<ConstantExpr>(PN->getIncomingValue(i))) {
Chris Lattner2a86f3b2006-09-09 22:02:56 +0000554 if (NonConstBB) return 0; // More than one non-const value.
Chris Lattnerb3036682007-02-24 01:03:45 +0000555 if (isa<PHINode>(PN->getIncomingValue(i))) return 0; // Itself a phi.
Chris Lattner2a86f3b2006-09-09 22:02:56 +0000556 NonConstBB = PN->getIncomingBlock(i);
557
558 // If the incoming non-constant value is in I's block, we have an infinite
559 // loop.
560 if (NonConstBB == I.getParent())
561 return 0;
562 }
563
564 // If there is exactly one non-constant value, we can insert a copy of the
565 // operation in that block. However, if this is a critical edge, we would be
566 // inserting the computation one some other paths (e.g. inside a loop). Only
567 // do this if the pred block is unconditionally branching into the phi block.
Chris Lattner213cd612009-09-27 20:46:36 +0000568 if (NonConstBB != 0 && !AllowAggressive) {
Chris Lattner2a86f3b2006-09-09 22:02:56 +0000569 BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
570 if (!BI || !BI->isUnconditional()) return 0;
571 }
Chris Lattner4e998b22004-09-29 05:07:12 +0000572
573 // Okay, we can do the transformation: create the new PHI node.
Gabor Greif051a9502008-04-06 20:25:17 +0000574 PHINode *NewPN = PHINode::Create(I.getType(), "");
Chris Lattner55517062005-01-29 00:39:08 +0000575 NewPN->reserveOperandSpace(PN->getNumOperands()/2);
Chris Lattner857eb572009-10-21 23:41:58 +0000576 InsertNewInstBefore(NewPN, *PN);
577 NewPN->takeName(PN);
Chris Lattner4e998b22004-09-29 05:07:12 +0000578
579 // Next, add all of the operands to the PHI.
Chris Lattner5d1704d2009-09-27 19:57:57 +0000580 if (SelectInst *SI = dyn_cast<SelectInst>(&I)) {
581 // We only currently try to fold the condition of a select when it is a phi,
582 // not the true/false values.
Chris Lattnerc6df8f42009-09-27 20:18:49 +0000583 Value *TrueV = SI->getTrueValue();
584 Value *FalseV = SI->getFalseValue();
Chris Lattner3ddfb212009-09-28 06:49:44 +0000585 BasicBlock *PhiTransBB = PN->getParent();
Chris Lattner5d1704d2009-09-27 19:57:57 +0000586 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattnerc6df8f42009-09-27 20:18:49 +0000587 BasicBlock *ThisBB = PN->getIncomingBlock(i);
Chris Lattner3ddfb212009-09-28 06:49:44 +0000588 Value *TrueVInPred = TrueV->DoPHITranslation(PhiTransBB, ThisBB);
589 Value *FalseVInPred = FalseV->DoPHITranslation(PhiTransBB, ThisBB);
Chris Lattner5d1704d2009-09-27 19:57:57 +0000590 Value *InV = 0;
591 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Chris Lattnerc6df8f42009-09-27 20:18:49 +0000592 InV = InC->isNullValue() ? FalseVInPred : TrueVInPred;
Chris Lattner5d1704d2009-09-27 19:57:57 +0000593 } else {
594 assert(PN->getIncomingBlock(i) == NonConstBB);
Chris Lattnerc6df8f42009-09-27 20:18:49 +0000595 InV = SelectInst::Create(PN->getIncomingValue(i), TrueVInPred,
596 FalseVInPred,
Chris Lattner5d1704d2009-09-27 19:57:57 +0000597 "phitmp", NonConstBB->getTerminator());
Chris Lattner857eb572009-10-21 23:41:58 +0000598 Worklist.Add(cast<Instruction>(InV));
Chris Lattner5d1704d2009-09-27 19:57:57 +0000599 }
Chris Lattnerc6df8f42009-09-27 20:18:49 +0000600 NewPN->addIncoming(InV, ThisBB);
Chris Lattner5d1704d2009-09-27 19:57:57 +0000601 }
602 } else if (I.getNumOperands() == 2) {
Chris Lattner4e998b22004-09-29 05:07:12 +0000603 Constant *C = cast<Constant>(I.getOperand(1));
Chris Lattnerbac32862004-11-14 19:13:23 +0000604 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattnera9ff5eb2007-08-05 08:47:58 +0000605 Value *InV = 0;
Chris Lattner2a86f3b2006-09-09 22:02:56 +0000606 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Reid Spencere4d87aa2006-12-23 06:05:41 +0000607 if (CmpInst *CI = dyn_cast<CmpInst>(&I))
Owen Andersonbaf3c402009-07-29 18:55:55 +0000608 InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C);
Reid Spencere4d87aa2006-12-23 06:05:41 +0000609 else
Owen Andersonbaf3c402009-07-29 18:55:55 +0000610 InV = ConstantExpr::get(I.getOpcode(), InC, C);
Chris Lattner2a86f3b2006-09-09 22:02:56 +0000611 } else {
612 assert(PN->getIncomingBlock(i) == NonConstBB);
613 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000614 InV = BinaryOperator::Create(BO->getOpcode(),
Chris Lattner2a86f3b2006-09-09 22:02:56 +0000615 PN->getIncomingValue(i), C, "phitmp",
616 NonConstBB->getTerminator());
Reid Spencere4d87aa2006-12-23 06:05:41 +0000617 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
Dan Gohman1c8a23c2009-08-25 23:17:54 +0000618 InV = CmpInst::Create(CI->getOpcode(),
Reid Spencere4d87aa2006-12-23 06:05:41 +0000619 CI->getPredicate(),
620 PN->getIncomingValue(i), C, "phitmp",
621 NonConstBB->getTerminator());
Chris Lattner2a86f3b2006-09-09 22:02:56 +0000622 else
Torok Edwinc23197a2009-07-14 16:55:14 +0000623 llvm_unreachable("Unknown binop!");
Chris Lattner857eb572009-10-21 23:41:58 +0000624
625 Worklist.Add(cast<Instruction>(InV));
Chris Lattner2a86f3b2006-09-09 22:02:56 +0000626 }
627 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner4e998b22004-09-29 05:07:12 +0000628 }
Reid Spencer3da59db2006-11-27 01:05:10 +0000629 } else {
630 CastInst *CI = cast<CastInst>(&I);
631 const Type *RetTy = CI->getType();
Chris Lattnerbac32862004-11-14 19:13:23 +0000632 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattner2a86f3b2006-09-09 22:02:56 +0000633 Value *InV;
634 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Owen Andersonbaf3c402009-07-29 18:55:55 +0000635 InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
Chris Lattner2a86f3b2006-09-09 22:02:56 +0000636 } else {
637 assert(PN->getIncomingBlock(i) == NonConstBB);
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000638 InV = CastInst::Create(CI->getOpcode(), PN->getIncomingValue(i),
Reid Spencer3da59db2006-11-27 01:05:10 +0000639 I.getType(), "phitmp",
640 NonConstBB->getTerminator());
Chris Lattner857eb572009-10-21 23:41:58 +0000641 Worklist.Add(cast<Instruction>(InV));
Chris Lattner2a86f3b2006-09-09 22:02:56 +0000642 }
643 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner4e998b22004-09-29 05:07:12 +0000644 }
645 }
646 return ReplaceInstUsesWith(I, NewPN);
647}
648
Chris Lattner2454a2e2008-01-29 06:52:45 +0000649
Chris Lattner3d28b1b2008-05-20 05:46:13 +0000650/// WillNotOverflowSignedAdd - Return true if we can prove that:
651/// (sext (add LHS, RHS)) === (add (sext LHS), (sext RHS))
652/// This basically requires proving that the add in the original type would not
653/// overflow to change the sign bit or have a carry out.
654bool InstCombiner::WillNotOverflowSignedAdd(Value *LHS, Value *RHS) {
655 // There are different heuristics we can use for this. Here are some simple
656 // ones.
657
658 // Add has the property that adding any two 2's complement numbers can only
659 // have one carry bit which can change a sign. As such, if LHS and RHS each
Chris Lattner8aee8ef2009-11-27 17:42:22 +0000660 // have at least two sign bits, we know that the addition of the two values
661 // will sign extend fine.
Chris Lattner3d28b1b2008-05-20 05:46:13 +0000662 if (ComputeNumSignBits(LHS) > 1 && ComputeNumSignBits(RHS) > 1)
663 return true;
664
665
666 // If one of the operands only has one non-zero bit, and if the other operand
667 // has a known-zero bit in a more significant place than it (not including the
668 // sign bit) the ripple may go up to and fill the zero, but won't change the
669 // sign. For example, (X & ~4) + 1.
670
671 // TODO: Implement.
672
673 return false;
674}
675
Chris Lattner2454a2e2008-01-29 06:52:45 +0000676
Chris Lattner7e708292002-06-25 16:13:24 +0000677Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +0000678 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +0000679 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
Chris Lattnerb35dde12002-05-06 16:49:18 +0000680
Chris Lattner8aee8ef2009-11-27 17:42:22 +0000681 if (Value *V = SimplifyAddInst(LHS, RHS, I.hasNoSignedWrap(),
682 I.hasNoUnsignedWrap(), TD))
683 return ReplaceInstUsesWith(I, V);
684
685
Chris Lattner66331a42004-04-10 22:01:55 +0000686 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
Chris Lattner66331a42004-04-10 22:01:55 +0000687 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
Chris Lattnerb4a2f052006-11-09 05:12:27 +0000688 // X + (signbit) --> X ^ signbit
Zhou Sheng3a507fd2007-04-01 17:13:37 +0000689 const APInt& Val = CI->getValue();
Zhou Sheng4351c642007-04-02 08:20:41 +0000690 uint32_t BitWidth = Val.getBitWidth();
Reid Spencer2ec619a2007-03-23 21:24:59 +0000691 if (Val == APInt::getSignBit(BitWidth))
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000692 return BinaryOperator::CreateXor(LHS, RHS);
Chris Lattnerb4a2f052006-11-09 05:12:27 +0000693
694 // See if SimplifyDemandedBits can simplify this. This handles stuff like
695 // (X & 254)+1 -> (X&254)|1
Dan Gohman6de29f82009-06-15 22:12:54 +0000696 if (SimplifyDemandedInstructionBits(I))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000697 return &I;
Dan Gohman1975d032008-10-30 20:40:10 +0000698
Eli Friedman709b33d2009-07-13 22:27:52 +0000699 // zext(bool) + C -> bool ? C + 1 : C
Dan Gohman1975d032008-10-30 20:40:10 +0000700 if (ZExtInst *ZI = dyn_cast<ZExtInst>(LHS))
Chris Lattner4de84762010-01-04 07:02:48 +0000701 if (ZI->getSrcTy() == Type::getInt1Ty(I.getContext()))
Dan Gohman186a6362009-08-12 16:04:34 +0000702 return SelectInst::Create(ZI->getOperand(0), AddOne(CI), CI);
Chris Lattner66331a42004-04-10 22:01:55 +0000703 }
Chris Lattner4e998b22004-09-29 05:07:12 +0000704
705 if (isa<PHINode>(LHS))
706 if (Instruction *NV = FoldOpIntoPhi(I))
707 return NV;
Chris Lattner5931c542005-09-24 23:43:33 +0000708
Chris Lattner4f637d42006-01-06 17:59:59 +0000709 ConstantInt *XorRHS = 0;
710 Value *XorLHS = 0;
Chris Lattnerc5eff442007-01-30 22:32:46 +0000711 if (isa<ConstantInt>(RHSC) &&
Dan Gohman4ae51262009-08-12 16:23:25 +0000712 match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
Dan Gohman6de29f82009-06-15 22:12:54 +0000713 uint32_t TySizeBits = I.getType()->getScalarSizeInBits();
Zhou Sheng3a507fd2007-04-01 17:13:37 +0000714 const APInt& RHSVal = cast<ConstantInt>(RHSC)->getValue();
Chris Lattner5931c542005-09-24 23:43:33 +0000715
Zhou Sheng4351c642007-04-02 08:20:41 +0000716 uint32_t Size = TySizeBits / 2;
Reid Spencer2ec619a2007-03-23 21:24:59 +0000717 APInt C0080Val(APInt(TySizeBits, 1ULL).shl(Size - 1));
718 APInt CFF80Val(-C0080Val);
Chris Lattner5931c542005-09-24 23:43:33 +0000719 do {
720 if (TySizeBits > Size) {
Chris Lattner5931c542005-09-24 23:43:33 +0000721 // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
722 // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
Reid Spencer2ec619a2007-03-23 21:24:59 +0000723 if ((RHSVal == CFF80Val && XorRHS->getValue() == C0080Val) ||
724 (RHSVal == C0080Val && XorRHS->getValue() == CFF80Val)) {
Chris Lattner5931c542005-09-24 23:43:33 +0000725 // This is a sign extend if the top bits are known zero.
Zhou Sheng290bec52007-03-29 08:15:12 +0000726 if (!MaskedValueIsZero(XorLHS,
727 APInt::getHighBitsSet(TySizeBits, TySizeBits - Size)))
Chris Lattner5931c542005-09-24 23:43:33 +0000728 Size = 0; // Not a sign ext, but can't be any others either.
Reid Spencer2ec619a2007-03-23 21:24:59 +0000729 break;
Chris Lattner5931c542005-09-24 23:43:33 +0000730 }
731 }
732 Size >>= 1;
Reid Spencer2ec619a2007-03-23 21:24:59 +0000733 C0080Val = APIntOps::lshr(C0080Val, Size);
734 CFF80Val = APIntOps::ashr(CFF80Val, Size);
735 } while (Size >= 1);
Chris Lattner5931c542005-09-24 23:43:33 +0000736
Reid Spencer35c38852007-03-28 01:36:16 +0000737 // FIXME: This shouldn't be necessary. When the backends can handle types
Chris Lattner0c7a9a02008-05-19 20:25:04 +0000738 // with funny bit widths then this switch statement should be removed. It
739 // is just here to get the size of the "middle" type back up to something
740 // that the back ends can handle.
Reid Spencer35c38852007-03-28 01:36:16 +0000741 const Type *MiddleType = 0;
742 switch (Size) {
743 default: break;
Chris Lattner4de84762010-01-04 07:02:48 +0000744 case 32:
745 case 16:
746 case 8: MiddleType = IntegerType::get(I.getContext(), Size); break;
Reid Spencer35c38852007-03-28 01:36:16 +0000747 }
748 if (MiddleType) {
Chris Lattner74381062009-08-30 07:44:24 +0000749 Value *NewTrunc = Builder->CreateTrunc(XorLHS, MiddleType, "sext");
Reid Spencer35c38852007-03-28 01:36:16 +0000750 return new SExtInst(NewTrunc, I.getType(), I.getName());
Chris Lattner5931c542005-09-24 23:43:33 +0000751 }
752 }
Chris Lattner66331a42004-04-10 22:01:55 +0000753 }
Chris Lattnerb35dde12002-05-06 16:49:18 +0000754
Chris Lattner4de84762010-01-04 07:02:48 +0000755 if (I.getType() == Type::getInt1Ty(I.getContext()))
Nick Lewycky9419ddb2008-05-31 17:59:52 +0000756 return BinaryOperator::CreateXor(LHS, RHS);
757
Nick Lewycky7d26bd82008-05-23 04:39:38 +0000758 // X + X --> X << 1
Nick Lewycky9419ddb2008-05-31 17:59:52 +0000759 if (I.getType()->isInteger()) {
Dan Gohman4ae51262009-08-12 16:23:25 +0000760 if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS)))
Owen Andersond672ecb2009-07-03 00:17:18 +0000761 return Result;
Chris Lattner7edc8c22005-04-07 17:14:51 +0000762
763 if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
764 if (RHSI->getOpcode() == Instruction::Sub)
765 if (LHS == RHSI->getOperand(1)) // A + (B - A) --> B
766 return ReplaceInstUsesWith(I, RHSI->getOperand(0));
767 }
768 if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
769 if (LHSI->getOpcode() == Instruction::Sub)
770 if (RHS == LHSI->getOperand(1)) // (B - A) + A --> B
771 return ReplaceInstUsesWith(I, LHSI->getOperand(0));
772 }
Robert Bocchino71698282004-07-27 21:02:21 +0000773 }
Chris Lattnere92d2f42003-08-13 04:18:28 +0000774
Chris Lattner5c4afb92002-05-08 22:46:53 +0000775 // -A + B --> B - A
Chris Lattnerdd12f962008-02-17 21:03:36 +0000776 // -A + -B --> -(A + B)
Dan Gohman186a6362009-08-12 16:04:34 +0000777 if (Value *LHSV = dyn_castNegVal(LHS)) {
Chris Lattnere10c0b92008-02-18 17:50:16 +0000778 if (LHS->getType()->isIntOrIntVector()) {
Dan Gohman186a6362009-08-12 16:04:34 +0000779 if (Value *RHSV = dyn_castNegVal(RHS)) {
Chris Lattner74381062009-08-30 07:44:24 +0000780 Value *NewAdd = Builder->CreateAdd(LHSV, RHSV, "sum");
Dan Gohman4ae51262009-08-12 16:23:25 +0000781 return BinaryOperator::CreateNeg(NewAdd);
Chris Lattnere10c0b92008-02-18 17:50:16 +0000782 }
Chris Lattnerdd12f962008-02-17 21:03:36 +0000783 }
784
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000785 return BinaryOperator::CreateSub(RHS, LHSV);
Chris Lattnerdd12f962008-02-17 21:03:36 +0000786 }
Chris Lattnerb35dde12002-05-06 16:49:18 +0000787
788 // A + -B --> A - B
Chris Lattner8d969642003-03-10 23:06:50 +0000789 if (!isa<Constant>(RHS))
Dan Gohman186a6362009-08-12 16:04:34 +0000790 if (Value *V = dyn_castNegVal(RHS))
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000791 return BinaryOperator::CreateSub(LHS, V);
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000792
Misha Brukmanfd939082005-04-21 23:48:37 +0000793
Chris Lattner50af16a2004-11-13 19:50:12 +0000794 ConstantInt *C2;
Dan Gohman186a6362009-08-12 16:04:34 +0000795 if (Value *X = dyn_castFoldableMul(LHS, C2)) {
Chris Lattner50af16a2004-11-13 19:50:12 +0000796 if (X == RHS) // X*C + X --> X * (C+1)
Dan Gohman186a6362009-08-12 16:04:34 +0000797 return BinaryOperator::CreateMul(RHS, AddOne(C2));
Chris Lattner50af16a2004-11-13 19:50:12 +0000798
799 // X*C1 + X*C2 --> X * (C1+C2)
800 ConstantInt *C1;
Dan Gohman186a6362009-08-12 16:04:34 +0000801 if (X == dyn_castFoldableMul(RHS, C1))
Owen Andersonbaf3c402009-07-29 18:55:55 +0000802 return BinaryOperator::CreateMul(X, ConstantExpr::getAdd(C1, C2));
Chris Lattnerad3448c2003-02-18 19:57:07 +0000803 }
804
805 // X + X*C --> X * (C+1)
Dan Gohman186a6362009-08-12 16:04:34 +0000806 if (dyn_castFoldableMul(RHS, C2) == LHS)
807 return BinaryOperator::CreateMul(LHS, AddOne(C2));
Chris Lattner50af16a2004-11-13 19:50:12 +0000808
Chris Lattnere617c9e2007-01-05 02:17:46 +0000809 // X + ~X --> -1 since ~X = -X-1
Dan Gohman186a6362009-08-12 16:04:34 +0000810 if (dyn_castNotVal(LHS) == RHS ||
811 dyn_castNotVal(RHS) == LHS)
Owen Andersona7235ea2009-07-31 20:28:14 +0000812 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnere617c9e2007-01-05 02:17:46 +0000813
Chris Lattnerad3448c2003-02-18 19:57:07 +0000814
Chris Lattner564a7272003-08-13 19:01:45 +0000815 // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
Dan Gohman4ae51262009-08-12 16:23:25 +0000816 if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
817 if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2)))
Chris Lattnere617c9e2007-01-05 02:17:46 +0000818 return R;
Chris Lattner5e0d7182008-05-19 20:01:56 +0000819
820 // A+B --> A|B iff A and B have no bits set in common.
821 if (const IntegerType *IT = dyn_cast<IntegerType>(I.getType())) {
822 APInt Mask = APInt::getAllOnesValue(IT->getBitWidth());
823 APInt LHSKnownOne(IT->getBitWidth(), 0);
824 APInt LHSKnownZero(IT->getBitWidth(), 0);
825 ComputeMaskedBits(LHS, Mask, LHSKnownZero, LHSKnownOne);
826 if (LHSKnownZero != 0) {
827 APInt RHSKnownOne(IT->getBitWidth(), 0);
828 APInt RHSKnownZero(IT->getBitWidth(), 0);
829 ComputeMaskedBits(RHS, Mask, RHSKnownZero, RHSKnownOne);
830
831 // No bits in common -> bitwise or.
Chris Lattner9d60ba92008-05-19 20:03:53 +0000832 if ((LHSKnownZero|RHSKnownZero).isAllOnesValue())
Chris Lattner5e0d7182008-05-19 20:01:56 +0000833 return BinaryOperator::CreateOr(LHS, RHS);
Chris Lattner5e0d7182008-05-19 20:01:56 +0000834 }
835 }
Chris Lattnerc8802d22003-03-11 00:12:48 +0000836
Nick Lewyckyb6eabff2008-02-03 07:42:09 +0000837 // W*X + Y*Z --> W * (X+Z) iff W == Y
Nick Lewycky0c2c3f62008-02-03 08:19:11 +0000838 if (I.getType()->isIntOrIntVector()) {
Nick Lewyckyb6eabff2008-02-03 07:42:09 +0000839 Value *W, *X, *Y, *Z;
Dan Gohman4ae51262009-08-12 16:23:25 +0000840 if (match(LHS, m_Mul(m_Value(W), m_Value(X))) &&
841 match(RHS, m_Mul(m_Value(Y), m_Value(Z)))) {
Nick Lewyckyb6eabff2008-02-03 07:42:09 +0000842 if (W != Y) {
843 if (W == Z) {
Bill Wendling587c01d2008-02-26 10:53:30 +0000844 std::swap(Y, Z);
Nick Lewyckyb6eabff2008-02-03 07:42:09 +0000845 } else if (Y == X) {
Bill Wendling587c01d2008-02-26 10:53:30 +0000846 std::swap(W, X);
847 } else if (X == Z) {
Nick Lewyckyb6eabff2008-02-03 07:42:09 +0000848 std::swap(Y, Z);
849 std::swap(W, X);
850 }
851 }
852
853 if (W == Y) {
Chris Lattner74381062009-08-30 07:44:24 +0000854 Value *NewAdd = Builder->CreateAdd(X, Z, LHS->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000855 return BinaryOperator::CreateMul(W, NewAdd);
Nick Lewyckyb6eabff2008-02-03 07:42:09 +0000856 }
857 }
858 }
859
Chris Lattner6b032052003-10-02 15:11:26 +0000860 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
Chris Lattner4f637d42006-01-06 17:59:59 +0000861 Value *X = 0;
Dan Gohman4ae51262009-08-12 16:23:25 +0000862 if (match(LHS, m_Not(m_Value(X)))) // ~X + C --> (C-1) - X
Dan Gohman186a6362009-08-12 16:04:34 +0000863 return BinaryOperator::CreateSub(SubOne(CRHS), X);
Chris Lattneracd1f0f2004-07-30 07:50:03 +0000864
Chris Lattnerb99d6b12004-10-08 05:07:56 +0000865 // (X & FF00) + xx00 -> (X+xx00) & FF00
Owen Andersonc7d2ce72009-07-10 17:35:01 +0000866 if (LHS->hasOneUse() &&
Dan Gohman4ae51262009-08-12 16:23:25 +0000867 match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
Owen Andersonbaf3c402009-07-29 18:55:55 +0000868 Constant *Anded = ConstantExpr::getAnd(CRHS, C2);
Chris Lattnerb99d6b12004-10-08 05:07:56 +0000869 if (Anded == CRHS) {
870 // See if all bits from the first bit set in the Add RHS up are included
871 // in the mask. First, get the rightmost bit.
Zhou Sheng3a507fd2007-04-01 17:13:37 +0000872 const APInt& AddRHSV = CRHS->getValue();
Chris Lattnerb99d6b12004-10-08 05:07:56 +0000873
874 // Form a mask of all bits from the lowest bit added through the top.
Zhou Sheng3a507fd2007-04-01 17:13:37 +0000875 APInt AddRHSHighBits(~((AddRHSV & -AddRHSV)-1));
Chris Lattnerb99d6b12004-10-08 05:07:56 +0000876
877 // See if the and mask includes all of these bits.
Zhou Sheng3a507fd2007-04-01 17:13:37 +0000878 APInt AddRHSHighBitsAnd(AddRHSHighBits & C2->getValue());
Misha Brukmanfd939082005-04-21 23:48:37 +0000879
Chris Lattnerb99d6b12004-10-08 05:07:56 +0000880 if (AddRHSHighBits == AddRHSHighBitsAnd) {
881 // Okay, the xform is safe. Insert the new add pronto.
Chris Lattner74381062009-08-30 07:44:24 +0000882 Value *NewAdd = Builder->CreateAdd(X, CRHS, LHS->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000883 return BinaryOperator::CreateAnd(NewAdd, C2);
Chris Lattnerb99d6b12004-10-08 05:07:56 +0000884 }
885 }
886 }
887
Chris Lattneracd1f0f2004-07-30 07:50:03 +0000888 // Try to fold constant add into select arguments.
889 if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
Chris Lattner80f43d32010-01-04 07:53:58 +0000890 if (Instruction *R = FoldOpIntoSelect(I, SI))
Chris Lattneracd1f0f2004-07-30 07:50:03 +0000891 return R;
Chris Lattner6b032052003-10-02 15:11:26 +0000892 }
893
Chris Lattner42790482007-12-20 01:56:58 +0000894 // add (select X 0 (sub n A)) A --> select X A n
Christopher Lamb30f017a2007-12-18 09:34:41 +0000895 {
896 SelectInst *SI = dyn_cast<SelectInst>(LHS);
Chris Lattner6046fb72008-11-16 04:46:19 +0000897 Value *A = RHS;
Christopher Lamb30f017a2007-12-18 09:34:41 +0000898 if (!SI) {
899 SI = dyn_cast<SelectInst>(RHS);
Chris Lattner6046fb72008-11-16 04:46:19 +0000900 A = LHS;
Christopher Lamb30f017a2007-12-18 09:34:41 +0000901 }
Chris Lattner42790482007-12-20 01:56:58 +0000902 if (SI && SI->hasOneUse()) {
Christopher Lamb30f017a2007-12-18 09:34:41 +0000903 Value *TV = SI->getTrueValue();
904 Value *FV = SI->getFalseValue();
Chris Lattner6046fb72008-11-16 04:46:19 +0000905 Value *N;
Christopher Lamb30f017a2007-12-18 09:34:41 +0000906
907 // Can we fold the add into the argument of the select?
908 // We check both true and false select arguments for a matching subtract.
Dan Gohman4ae51262009-08-12 16:23:25 +0000909 if (match(FV, m_Zero()) &&
910 match(TV, m_Sub(m_Value(N), m_Specific(A))))
Chris Lattner6046fb72008-11-16 04:46:19 +0000911 // Fold the add into the true select value.
Gabor Greif051a9502008-04-06 20:25:17 +0000912 return SelectInst::Create(SI->getCondition(), N, A);
Dan Gohman4ae51262009-08-12 16:23:25 +0000913 if (match(TV, m_Zero()) &&
914 match(FV, m_Sub(m_Value(N), m_Specific(A))))
Chris Lattner6046fb72008-11-16 04:46:19 +0000915 // Fold the add into the false select value.
Gabor Greif051a9502008-04-06 20:25:17 +0000916 return SelectInst::Create(SI->getCondition(), A, N);
Christopher Lamb30f017a2007-12-18 09:34:41 +0000917 }
918 }
Andrew Lenharth16d79552006-09-19 18:24:51 +0000919
Chris Lattner3d28b1b2008-05-20 05:46:13 +0000920 // Check for (add (sext x), y), see if we can merge this into an
921 // integer add followed by a sext.
922 if (SExtInst *LHSConv = dyn_cast<SExtInst>(LHS)) {
923 // (add (sext x), cst) --> (sext (add x, cst'))
924 if (ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS)) {
925 Constant *CI =
Owen Andersonbaf3c402009-07-29 18:55:55 +0000926 ConstantExpr::getTrunc(RHSC, LHSConv->getOperand(0)->getType());
Chris Lattner3d28b1b2008-05-20 05:46:13 +0000927 if (LHSConv->hasOneUse() &&
Owen Andersonbaf3c402009-07-29 18:55:55 +0000928 ConstantExpr::getSExt(CI, I.getType()) == RHSC &&
Chris Lattner3d28b1b2008-05-20 05:46:13 +0000929 WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
930 // Insert the new, smaller add.
Dan Gohmanfe359552009-10-26 22:14:22 +0000931 Value *NewAdd = Builder->CreateNSWAdd(LHSConv->getOperand(0),
932 CI, "addconv");
Chris Lattner3d28b1b2008-05-20 05:46:13 +0000933 return new SExtInst(NewAdd, I.getType());
934 }
935 }
936
937 // (add (sext x), (sext y)) --> (sext (add int x, y))
938 if (SExtInst *RHSConv = dyn_cast<SExtInst>(RHS)) {
939 // Only do this if x/y have the same type, if at last one of them has a
940 // single use (so we don't increase the number of sexts), and if the
941 // integer add will not overflow.
942 if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
943 (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
944 WillNotOverflowSignedAdd(LHSConv->getOperand(0),
945 RHSConv->getOperand(0))) {
946 // Insert the new integer add.
Dan Gohmanfe359552009-10-26 22:14:22 +0000947 Value *NewAdd = Builder->CreateNSWAdd(LHSConv->getOperand(0),
948 RHSConv->getOperand(0), "addconv");
Chris Lattner3d28b1b2008-05-20 05:46:13 +0000949 return new SExtInst(NewAdd, I.getType());
950 }
951 }
952 }
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000953
954 return Changed ? &I : 0;
955}
956
957Instruction *InstCombiner::visitFAdd(BinaryOperator &I) {
958 bool Changed = SimplifyCommutative(I);
959 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
960
961 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
962 // X + 0 --> X
963 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
Owen Anderson6f83c9c2009-07-27 20:59:43 +0000964 if (CFP->isExactlyValue(ConstantFP::getNegativeZero
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000965 (I.getType())->getValueAPF()))
966 return ReplaceInstUsesWith(I, LHS);
967 }
968
969 if (isa<PHINode>(LHS))
970 if (Instruction *NV = FoldOpIntoPhi(I))
971 return NV;
972 }
973
974 // -A + B --> B - A
975 // -A + -B --> -(A + B)
Dan Gohman186a6362009-08-12 16:04:34 +0000976 if (Value *LHSV = dyn_castFNegVal(LHS))
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000977 return BinaryOperator::CreateFSub(RHS, LHSV);
978
979 // A + -B --> A - B
980 if (!isa<Constant>(RHS))
Dan Gohman186a6362009-08-12 16:04:34 +0000981 if (Value *V = dyn_castFNegVal(RHS))
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000982 return BinaryOperator::CreateFSub(LHS, V);
983
984 // Check for X+0.0. Simplify it to X if we know X is not -0.0.
985 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS))
986 if (CFP->getValueAPF().isPosZero() && CannotBeNegativeZero(LHS))
987 return ReplaceInstUsesWith(I, LHS);
988
Chris Lattner3d28b1b2008-05-20 05:46:13 +0000989 // Check for (add double (sitofp x), y), see if we can merge this into an
990 // integer add followed by a promotion.
991 if (SIToFPInst *LHSConv = dyn_cast<SIToFPInst>(LHS)) {
992 // (add double (sitofp x), fpcst) --> (sitofp (add int x, intcst))
993 // ... if the constant fits in the integer value. This is useful for things
994 // like (double)(x & 1234) + 4.0 -> (double)((X & 1234)+4) which no longer
995 // requires a constant pool load, and generally allows the add to be better
996 // instcombined.
997 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS)) {
998 Constant *CI =
Owen Andersonbaf3c402009-07-29 18:55:55 +0000999 ConstantExpr::getFPToSI(CFP, LHSConv->getOperand(0)->getType());
Chris Lattner3d28b1b2008-05-20 05:46:13 +00001000 if (LHSConv->hasOneUse() &&
Owen Andersonbaf3c402009-07-29 18:55:55 +00001001 ConstantExpr::getSIToFP(CI, I.getType()) == CFP &&
Chris Lattner3d28b1b2008-05-20 05:46:13 +00001002 WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
1003 // Insert the new integer add.
Dan Gohmanfe359552009-10-26 22:14:22 +00001004 Value *NewAdd = Builder->CreateNSWAdd(LHSConv->getOperand(0),
1005 CI, "addconv");
Chris Lattner3d28b1b2008-05-20 05:46:13 +00001006 return new SIToFPInst(NewAdd, I.getType());
1007 }
1008 }
1009
1010 // (add double (sitofp x), (sitofp y)) --> (sitofp (add int x, y))
1011 if (SIToFPInst *RHSConv = dyn_cast<SIToFPInst>(RHS)) {
1012 // Only do this if x/y have the same type, if at last one of them has a
1013 // single use (so we don't increase the number of int->fp conversions),
1014 // and if the integer add will not overflow.
1015 if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
1016 (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
1017 WillNotOverflowSignedAdd(LHSConv->getOperand(0),
1018 RHSConv->getOperand(0))) {
1019 // Insert the new integer add.
Dan Gohmanfe359552009-10-26 22:14:22 +00001020 Value *NewAdd = Builder->CreateNSWAdd(LHSConv->getOperand(0),
Chris Lattner092543c2009-11-04 08:05:20 +00001021 RHSConv->getOperand(0),"addconv");
Chris Lattner3d28b1b2008-05-20 05:46:13 +00001022 return new SIToFPInst(NewAdd, I.getType());
1023 }
1024 }
1025 }
1026
Chris Lattner7e708292002-06-25 16:13:24 +00001027 return Changed ? &I : 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00001028}
1029
Chris Lattner092543c2009-11-04 08:05:20 +00001030
1031/// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
1032/// code necessary to compute the offset from the base pointer (without adding
1033/// in the base pointer). Return the result as a signed integer of intptr size.
Chris Lattner02446fc2010-01-04 07:37:31 +00001034Value *InstCombiner::EmitGEPOffset(User *GEP) {
1035 TargetData &TD = *getTargetData();
Chris Lattner092543c2009-11-04 08:05:20 +00001036 gep_type_iterator GTI = gep_type_begin(GEP);
1037 const Type *IntPtrTy = TD.getIntPtrType(GEP->getContext());
1038 Value *Result = Constant::getNullValue(IntPtrTy);
1039
1040 // Build a mask for high order bits.
1041 unsigned IntPtrWidth = TD.getPointerSizeInBits();
1042 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
1043
1044 for (User::op_iterator i = GEP->op_begin() + 1, e = GEP->op_end(); i != e;
1045 ++i, ++GTI) {
1046 Value *Op = *i;
1047 uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType()) & PtrSizeMask;
1048 if (ConstantInt *OpC = dyn_cast<ConstantInt>(Op)) {
1049 if (OpC->isZero()) continue;
1050
1051 // Handle a struct index, which adds its field offset to the pointer.
1052 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
1053 Size = TD.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
1054
Chris Lattner02446fc2010-01-04 07:37:31 +00001055 Result = Builder->CreateAdd(Result,
1056 ConstantInt::get(IntPtrTy, Size),
1057 GEP->getName()+".offs");
Chris Lattner092543c2009-11-04 08:05:20 +00001058 continue;
1059 }
1060
1061 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
1062 Constant *OC =
1063 ConstantExpr::getIntegerCast(OpC, IntPtrTy, true /*SExt*/);
1064 Scale = ConstantExpr::getMul(OC, Scale);
1065 // Emit an add instruction.
Chris Lattner02446fc2010-01-04 07:37:31 +00001066 Result = Builder->CreateAdd(Result, Scale, GEP->getName()+".offs");
Chris Lattner092543c2009-11-04 08:05:20 +00001067 continue;
1068 }
1069 // Convert to correct type.
1070 if (Op->getType() != IntPtrTy)
Chris Lattner02446fc2010-01-04 07:37:31 +00001071 Op = Builder->CreateIntCast(Op, IntPtrTy, true, Op->getName()+".c");
Chris Lattner092543c2009-11-04 08:05:20 +00001072 if (Size != 1) {
1073 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
1074 // We'll let instcombine(mul) convert this to a shl if possible.
Chris Lattner02446fc2010-01-04 07:37:31 +00001075 Op = Builder->CreateMul(Op, Scale, GEP->getName()+".idx");
Chris Lattner092543c2009-11-04 08:05:20 +00001076 }
1077
1078 // Emit an add instruction.
Chris Lattner02446fc2010-01-04 07:37:31 +00001079 Result = Builder->CreateAdd(Op, Result, GEP->getName()+".offs");
Chris Lattner092543c2009-11-04 08:05:20 +00001080 }
1081 return Result;
1082}
1083
1084
Chris Lattner092543c2009-11-04 08:05:20 +00001085
1086
1087/// Optimize pointer differences into the same array into a size. Consider:
1088/// &A[10] - &A[0]: we should compile this to "10". LHS/RHS are the pointer
1089/// operands to the ptrtoint instructions for the LHS/RHS of the subtract.
1090///
1091Value *InstCombiner::OptimizePointerDifference(Value *LHS, Value *RHS,
1092 const Type *Ty) {
1093 assert(TD && "Must have target data info for this");
1094
1095 // If LHS is a gep based on RHS or RHS is a gep based on LHS, we can optimize
1096 // this.
Chris Lattner0cb1e9e2010-01-04 18:48:26 +00001097 bool Swapped = false;
Chris Lattner85c1c962010-01-01 22:42:29 +00001098 GetElementPtrInst *GEP = 0;
1099 ConstantExpr *CstGEP = 0;
Chris Lattner092543c2009-11-04 08:05:20 +00001100
Chris Lattner85c1c962010-01-01 22:42:29 +00001101 // TODO: Could also optimize &A[i] - &A[j] -> "i-j", and "&A.foo[i] - &A.foo".
1102 // For now we require one side to be the base pointer "A" or a constant
1103 // expression derived from it.
1104 if (GetElementPtrInst *LHSGEP = dyn_cast<GetElementPtrInst>(LHS)) {
1105 // (gep X, ...) - X
1106 if (LHSGEP->getOperand(0) == RHS) {
1107 GEP = LHSGEP;
1108 Swapped = false;
1109 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(RHS)) {
1110 // (gep X, ...) - (ce_gep X, ...)
1111 if (CE->getOpcode() == Instruction::GetElementPtr &&
1112 LHSGEP->getOperand(0) == CE->getOperand(0)) {
1113 CstGEP = CE;
1114 GEP = LHSGEP;
1115 Swapped = false;
1116 }
1117 }
1118 }
1119
1120 if (GetElementPtrInst *RHSGEP = dyn_cast<GetElementPtrInst>(RHS)) {
1121 // X - (gep X, ...)
1122 if (RHSGEP->getOperand(0) == LHS) {
1123 GEP = RHSGEP;
1124 Swapped = true;
1125 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(LHS)) {
1126 // (ce_gep X, ...) - (gep X, ...)
1127 if (CE->getOpcode() == Instruction::GetElementPtr &&
1128 RHSGEP->getOperand(0) == CE->getOperand(0)) {
1129 CstGEP = CE;
1130 GEP = RHSGEP;
1131 Swapped = true;
1132 }
1133 }
1134 }
1135
1136 if (GEP == 0)
Chris Lattner092543c2009-11-04 08:05:20 +00001137 return 0;
1138
Chris Lattner092543c2009-11-04 08:05:20 +00001139 // Emit the offset of the GEP and an intptr_t.
Chris Lattner02446fc2010-01-04 07:37:31 +00001140 Value *Result = EmitGEPOffset(GEP);
Chris Lattner85c1c962010-01-01 22:42:29 +00001141
1142 // If we had a constant expression GEP on the other side offsetting the
1143 // pointer, subtract it from the offset we have.
1144 if (CstGEP) {
Chris Lattner02446fc2010-01-04 07:37:31 +00001145 Value *CstOffset = EmitGEPOffset(CstGEP);
Chris Lattner85c1c962010-01-01 22:42:29 +00001146 Result = Builder->CreateSub(Result, CstOffset);
1147 }
1148
Chris Lattner092543c2009-11-04 08:05:20 +00001149
1150 // If we have p - gep(p, ...) then we have to negate the result.
1151 if (Swapped)
1152 Result = Builder->CreateNeg(Result, "diff.neg");
1153
1154 return Builder->CreateIntCast(Result, Ty, true);
1155}
1156
1157
Chris Lattner7e708292002-06-25 16:13:24 +00001158Instruction *InstCombiner::visitSub(BinaryOperator &I) {
Chris Lattner7e708292002-06-25 16:13:24 +00001159 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00001160
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001161 if (Op0 == Op1) // sub X, X -> 0
Owen Andersona7235ea2009-07-31 20:28:14 +00001162 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerdd841ae2002-04-18 17:39:14 +00001163
Chris Lattner3bf68152009-12-21 04:04:05 +00001164 // If this is a 'B = x-(-A)', change to B = x+A. This preserves NSW/NUW.
1165 if (Value *V = dyn_castNegVal(Op1)) {
1166 BinaryOperator *Res = BinaryOperator::CreateAdd(Op0, V);
1167 Res->setHasNoSignedWrap(I.hasNoSignedWrap());
1168 Res->setHasNoUnsignedWrap(I.hasNoUnsignedWrap());
1169 return Res;
1170 }
Chris Lattnerb35dde12002-05-06 16:49:18 +00001171
Chris Lattnere87597f2004-10-16 18:11:37 +00001172 if (isa<UndefValue>(Op0))
1173 return ReplaceInstUsesWith(I, Op0); // undef - X -> undef
1174 if (isa<UndefValue>(Op1))
1175 return ReplaceInstUsesWith(I, Op1); // X - undef -> undef
Chris Lattner4de84762010-01-04 07:02:48 +00001176 if (I.getType() == Type::getInt1Ty(I.getContext()))
Chris Lattner092543c2009-11-04 08:05:20 +00001177 return BinaryOperator::CreateXor(Op0, Op1);
1178
Chris Lattnerd65460f2003-11-05 01:06:05 +00001179 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
Chris Lattner092543c2009-11-04 08:05:20 +00001180 // Replace (-1 - A) with (~A).
Chris Lattnera2881962003-02-18 19:28:33 +00001181 if (C->isAllOnesValue())
Dan Gohman4ae51262009-08-12 16:23:25 +00001182 return BinaryOperator::CreateNot(Op1);
Chris Lattner40371712002-05-09 01:29:19 +00001183
Chris Lattnerd65460f2003-11-05 01:06:05 +00001184 // C - ~X == X + (1+C)
Reid Spencer4b828e62005-06-18 17:37:34 +00001185 Value *X = 0;
Dan Gohman4ae51262009-08-12 16:23:25 +00001186 if (match(Op1, m_Not(m_Value(X))))
Dan Gohman186a6362009-08-12 16:04:34 +00001187 return BinaryOperator::CreateAdd(X, AddOne(C));
Reid Spencer7177c3a2007-03-25 05:33:51 +00001188
Chris Lattner76b7a062007-01-15 07:02:54 +00001189 // -(X >>u 31) -> (X >>s 31)
1190 // -(X >>s 31) -> (X >>u 31)
Zhou Sheng302748d2007-03-30 17:20:39 +00001191 if (C->isZero()) {
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00001192 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op1)) {
Reid Spencer3822ff52006-11-08 06:47:33 +00001193 if (SI->getOpcode() == Instruction::LShr) {
Reid Spencerb83eb642006-10-20 07:07:24 +00001194 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
Chris Lattner9c290672004-03-12 23:53:13 +00001195 // Check to see if we are shifting out everything but the sign bit.
Zhou Sheng302748d2007-03-30 17:20:39 +00001196 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
Reid Spencerb83eb642006-10-20 07:07:24 +00001197 SI->getType()->getPrimitiveSizeInBits()-1) {
Reid Spencer3822ff52006-11-08 06:47:33 +00001198 // Ok, the transformation is safe. Insert AShr.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001199 return BinaryOperator::Create(Instruction::AShr,
Reid Spencer832254e2007-02-02 02:16:23 +00001200 SI->getOperand(0), CU, SI->getName());
Chris Lattner9c290672004-03-12 23:53:13 +00001201 }
1202 }
Chris Lattner092543c2009-11-04 08:05:20 +00001203 } else if (SI->getOpcode() == Instruction::AShr) {
Reid Spencer3822ff52006-11-08 06:47:33 +00001204 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
1205 // Check to see if we are shifting out everything but the sign bit.
Zhou Sheng302748d2007-03-30 17:20:39 +00001206 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
Reid Spencer3822ff52006-11-08 06:47:33 +00001207 SI->getType()->getPrimitiveSizeInBits()-1) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00001208 // Ok, the transformation is safe. Insert LShr.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001209 return BinaryOperator::CreateLShr(
Reid Spencer832254e2007-02-02 02:16:23 +00001210 SI->getOperand(0), CU, SI->getName());
Reid Spencer3822ff52006-11-08 06:47:33 +00001211 }
1212 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00001213 }
1214 }
Chris Lattnerbfe492b2004-03-13 00:11:49 +00001215 }
Chris Lattner2eefe512004-04-09 19:05:30 +00001216
1217 // Try to fold constant sub into select arguments.
1218 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner80f43d32010-01-04 07:53:58 +00001219 if (Instruction *R = FoldOpIntoSelect(I, SI))
Chris Lattner2eefe512004-04-09 19:05:30 +00001220 return R;
Eli Friedman709b33d2009-07-13 22:27:52 +00001221
1222 // C - zext(bool) -> bool ? C - 1 : C
1223 if (ZExtInst *ZI = dyn_cast<ZExtInst>(Op1))
Chris Lattner4de84762010-01-04 07:02:48 +00001224 if (ZI->getSrcTy() == Type::getInt1Ty(I.getContext()))
Dan Gohman186a6362009-08-12 16:04:34 +00001225 return SelectInst::Create(ZI->getOperand(0), SubOne(C), C);
Chris Lattnerd65460f2003-11-05 01:06:05 +00001226 }
1227
Chris Lattner43d84d62005-04-07 16:15:25 +00001228 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001229 if (Op1I->getOpcode() == Instruction::Add) {
Chris Lattner08954a22005-04-07 16:28:01 +00001230 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
Dan Gohman4ae51262009-08-12 16:23:25 +00001231 return BinaryOperator::CreateNeg(Op1I->getOperand(1),
Owen Anderson0a5372e2009-07-13 04:09:18 +00001232 I.getName());
Chris Lattner08954a22005-04-07 16:28:01 +00001233 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
Dan Gohman4ae51262009-08-12 16:23:25 +00001234 return BinaryOperator::CreateNeg(Op1I->getOperand(0),
Owen Anderson0a5372e2009-07-13 04:09:18 +00001235 I.getName());
Chris Lattner08954a22005-04-07 16:28:01 +00001236 else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
1237 if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
1238 // C1-(X+C2) --> (C1-C2)-X
Owen Andersond672ecb2009-07-03 00:17:18 +00001239 return BinaryOperator::CreateSub(
Owen Andersonbaf3c402009-07-29 18:55:55 +00001240 ConstantExpr::getSub(CI1, CI2), Op1I->getOperand(0));
Chris Lattner08954a22005-04-07 16:28:01 +00001241 }
Chris Lattner43d84d62005-04-07 16:15:25 +00001242 }
1243
Chris Lattnerfd059242003-10-15 16:48:29 +00001244 if (Op1I->hasOneUse()) {
Chris Lattnera2881962003-02-18 19:28:33 +00001245 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
1246 // is not used by anyone else...
1247 //
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001248 if (Op1I->getOpcode() == Instruction::Sub) {
Chris Lattnera2881962003-02-18 19:28:33 +00001249 // Swap the two operands of the subexpr...
1250 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
1251 Op1I->setOperand(0, IIOp1);
1252 Op1I->setOperand(1, IIOp0);
Misha Brukmanfd939082005-04-21 23:48:37 +00001253
Chris Lattnera2881962003-02-18 19:28:33 +00001254 // Create the new top level add instruction...
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001255 return BinaryOperator::CreateAdd(Op0, Op1);
Chris Lattnera2881962003-02-18 19:28:33 +00001256 }
1257
1258 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
1259 //
1260 if (Op1I->getOpcode() == Instruction::And &&
1261 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
1262 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
1263
Chris Lattner74381062009-08-30 07:44:24 +00001264 Value *NewNot = Builder->CreateNot(OtherOp, "B.not");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001265 return BinaryOperator::CreateAnd(Op0, NewNot);
Chris Lattnera2881962003-02-18 19:28:33 +00001266 }
Chris Lattnerad3448c2003-02-18 19:57:07 +00001267
Reid Spencerac5209e2006-10-16 23:08:08 +00001268 // 0 - (X sdiv C) -> (X sdiv -C)
Reid Spencer1628cec2006-10-26 06:15:43 +00001269 if (Op1I->getOpcode() == Instruction::SDiv)
Reid Spencerb83eb642006-10-20 07:07:24 +00001270 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
Zhou Sheng843f07672007-04-19 05:39:12 +00001271 if (CSI->isZero())
Chris Lattner91ccc152004-10-06 15:08:25 +00001272 if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001273 return BinaryOperator::CreateSDiv(Op1I->getOperand(0),
Owen Andersonbaf3c402009-07-29 18:55:55 +00001274 ConstantExpr::getNeg(DivRHS));
Chris Lattner91ccc152004-10-06 15:08:25 +00001275
Chris Lattnerad3448c2003-02-18 19:57:07 +00001276 // X - X*C --> X * (1-C)
Reid Spencer4b828e62005-06-18 17:37:34 +00001277 ConstantInt *C2 = 0;
Dan Gohman186a6362009-08-12 16:04:34 +00001278 if (dyn_castFoldableMul(Op1I, C2) == Op0) {
Owen Andersond672ecb2009-07-03 00:17:18 +00001279 Constant *CP1 =
Owen Andersonbaf3c402009-07-29 18:55:55 +00001280 ConstantExpr::getSub(ConstantInt::get(I.getType(), 1),
Dan Gohman6de29f82009-06-15 22:12:54 +00001281 C2);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001282 return BinaryOperator::CreateMul(Op0, CP1);
Chris Lattnerad3448c2003-02-18 19:57:07 +00001283 }
Chris Lattner40371712002-05-09 01:29:19 +00001284 }
Chris Lattner43d84d62005-04-07 16:15:25 +00001285 }
Chris Lattnera2881962003-02-18 19:28:33 +00001286
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001287 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
1288 if (Op0I->getOpcode() == Instruction::Add) {
1289 if (Op0I->getOperand(0) == Op1) // (Y+X)-Y == X
1290 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
1291 else if (Op0I->getOperand(1) == Op1) // (X+Y)-Y == X
1292 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
1293 } else if (Op0I->getOpcode() == Instruction::Sub) {
1294 if (Op0I->getOperand(0) == Op1) // (X-Y)-X == -Y
Dan Gohman4ae51262009-08-12 16:23:25 +00001295 return BinaryOperator::CreateNeg(Op0I->getOperand(1),
Owen Anderson0a5372e2009-07-13 04:09:18 +00001296 I.getName());
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00001297 }
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001298 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001299
Chris Lattner50af16a2004-11-13 19:50:12 +00001300 ConstantInt *C1;
Dan Gohman186a6362009-08-12 16:04:34 +00001301 if (Value *X = dyn_castFoldableMul(Op0, C1)) {
Reid Spencer7177c3a2007-03-25 05:33:51 +00001302 if (X == Op1) // X*C - X --> X * (C-1)
Dan Gohman186a6362009-08-12 16:04:34 +00001303 return BinaryOperator::CreateMul(Op1, SubOne(C1));
Chris Lattnerad3448c2003-02-18 19:57:07 +00001304
Chris Lattner50af16a2004-11-13 19:50:12 +00001305 ConstantInt *C2; // X*C1 - X*C2 -> X * (C1-C2)
Dan Gohman186a6362009-08-12 16:04:34 +00001306 if (X == dyn_castFoldableMul(Op1, C2))
Owen Andersonbaf3c402009-07-29 18:55:55 +00001307 return BinaryOperator::CreateMul(X, ConstantExpr::getSub(C1, C2));
Chris Lattner50af16a2004-11-13 19:50:12 +00001308 }
Chris Lattner092543c2009-11-04 08:05:20 +00001309
1310 // Optimize pointer differences into the same array into a size. Consider:
1311 // &A[10] - &A[0]: we should compile this to "10".
1312 if (TD) {
Chris Lattner33767182010-01-01 22:12:03 +00001313 Value *LHSOp, *RHSOp;
Chris Lattnerf2ebc682010-01-01 22:29:12 +00001314 if (match(Op0, m_PtrToInt(m_Value(LHSOp))) &&
1315 match(Op1, m_PtrToInt(m_Value(RHSOp))))
Chris Lattner33767182010-01-01 22:12:03 +00001316 if (Value *Res = OptimizePointerDifference(LHSOp, RHSOp, I.getType()))
1317 return ReplaceInstUsesWith(I, Res);
Chris Lattner092543c2009-11-04 08:05:20 +00001318
1319 // trunc(p)-trunc(q) -> trunc(p-q)
Chris Lattnerf2ebc682010-01-01 22:29:12 +00001320 if (match(Op0, m_Trunc(m_PtrToInt(m_Value(LHSOp)))) &&
1321 match(Op1, m_Trunc(m_PtrToInt(m_Value(RHSOp)))))
1322 if (Value *Res = OptimizePointerDifference(LHSOp, RHSOp, I.getType()))
1323 return ReplaceInstUsesWith(I, Res);
Chris Lattner092543c2009-11-04 08:05:20 +00001324 }
1325
Chris Lattner3f5b8772002-05-06 16:14:14 +00001326 return 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00001327}
1328
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001329Instruction *InstCombiner::visitFSub(BinaryOperator &I) {
1330 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1331
1332 // If this is a 'B = x-(-A)', change to B = x+A...
Dan Gohman186a6362009-08-12 16:04:34 +00001333 if (Value *V = dyn_castFNegVal(Op1))
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001334 return BinaryOperator::CreateFAdd(Op0, V);
1335
1336 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
1337 if (Op1I->getOpcode() == Instruction::FAdd) {
1338 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
Dan Gohman4ae51262009-08-12 16:23:25 +00001339 return BinaryOperator::CreateFNeg(Op1I->getOperand(1),
Owen Anderson0a5372e2009-07-13 04:09:18 +00001340 I.getName());
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001341 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
Dan Gohman4ae51262009-08-12 16:23:25 +00001342 return BinaryOperator::CreateFNeg(Op1I->getOperand(0),
Owen Anderson0a5372e2009-07-13 04:09:18 +00001343 I.getName());
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001344 }
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001345 }
1346
1347 return 0;
1348}
1349
Chris Lattner7e708292002-06-25 16:13:24 +00001350Instruction *InstCombiner::visitMul(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00001351 bool Changed = SimplifyCommutative(I);
Chris Lattnera2498472009-10-11 21:36:10 +00001352 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerdd841ae2002-04-18 17:39:14 +00001353
Chris Lattnera2498472009-10-11 21:36:10 +00001354 if (isa<UndefValue>(Op1)) // undef * X -> 0
Owen Andersona7235ea2009-07-31 20:28:14 +00001355 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00001356
Chris Lattner8af304a2009-10-11 07:53:15 +00001357 // Simplify mul instructions with a constant RHS.
Chris Lattnera2498472009-10-11 21:36:10 +00001358 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
1359 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1C)) {
Chris Lattnere92d2f42003-08-13 04:18:28 +00001360
1361 // ((X << C1)*C2) == (X * (C2 << C1))
Reid Spencer832254e2007-02-02 02:16:23 +00001362 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op0))
Chris Lattnere92d2f42003-08-13 04:18:28 +00001363 if (SI->getOpcode() == Instruction::Shl)
1364 if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001365 return BinaryOperator::CreateMul(SI->getOperand(0),
Owen Andersonbaf3c402009-07-29 18:55:55 +00001366 ConstantExpr::getShl(CI, ShOp));
Misha Brukmanfd939082005-04-21 23:48:37 +00001367
Zhou Sheng843f07672007-04-19 05:39:12 +00001368 if (CI->isZero())
Chris Lattnera2498472009-10-11 21:36:10 +00001369 return ReplaceInstUsesWith(I, Op1C); // X * 0 == 0
Chris Lattner515c97c2003-09-11 22:24:54 +00001370 if (CI->equalsInt(1)) // X * 1 == X
1371 return ReplaceInstUsesWith(I, Op0);
1372 if (CI->isAllOnesValue()) // X * -1 == 0 - X
Dan Gohman4ae51262009-08-12 16:23:25 +00001373 return BinaryOperator::CreateNeg(Op0, I.getName());
Chris Lattner6c1ce212002-04-29 22:24:47 +00001374
Zhou Sheng97b52c22007-03-29 01:57:21 +00001375 const APInt& Val = cast<ConstantInt>(CI)->getValue();
Reid Spencerbca0e382007-03-23 20:05:17 +00001376 if (Val.isPowerOf2()) { // Replace X*(2^C) with X << C
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001377 return BinaryOperator::CreateShl(Op0,
Owen Andersoneed707b2009-07-24 23:12:02 +00001378 ConstantInt::get(Op0->getType(), Val.logBase2()));
Chris Lattnerbcd7db52005-08-02 19:16:58 +00001379 }
Chris Lattnera2498472009-10-11 21:36:10 +00001380 } else if (isa<VectorType>(Op1C->getType())) {
1381 if (Op1C->isNullValue())
1382 return ReplaceInstUsesWith(I, Op1C);
Nick Lewycky895f0852008-11-27 20:21:08 +00001383
Chris Lattnera2498472009-10-11 21:36:10 +00001384 if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1C)) {
Nick Lewycky895f0852008-11-27 20:21:08 +00001385 if (Op1V->isAllOnesValue()) // X * -1 == 0 - X
Dan Gohman4ae51262009-08-12 16:23:25 +00001386 return BinaryOperator::CreateNeg(Op0, I.getName());
Nick Lewycky895f0852008-11-27 20:21:08 +00001387
1388 // As above, vector X*splat(1.0) -> X in all defined cases.
1389 if (Constant *Splat = Op1V->getSplatValue()) {
Nick Lewycky895f0852008-11-27 20:21:08 +00001390 if (ConstantInt *CI = dyn_cast<ConstantInt>(Splat))
1391 if (CI->equalsInt(1))
1392 return ReplaceInstUsesWith(I, Op0);
1393 }
1394 }
Chris Lattnera2881962003-02-18 19:28:33 +00001395 }
Chris Lattnerab51f3f2006-03-04 06:04:02 +00001396
1397 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
1398 if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
Chris Lattnera2498472009-10-11 21:36:10 +00001399 isa<ConstantInt>(Op0I->getOperand(1)) && isa<ConstantInt>(Op1C)) {
Chris Lattnerab51f3f2006-03-04 06:04:02 +00001400 // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
Chris Lattnera2498472009-10-11 21:36:10 +00001401 Value *Add = Builder->CreateMul(Op0I->getOperand(0), Op1C, "tmp");
1402 Value *C1C2 = Builder->CreateMul(Op1C, Op0I->getOperand(1));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001403 return BinaryOperator::CreateAdd(Add, C1C2);
Chris Lattnerab51f3f2006-03-04 06:04:02 +00001404
1405 }
Chris Lattner2eefe512004-04-09 19:05:30 +00001406
1407 // Try to fold constant mul into select arguments.
1408 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner80f43d32010-01-04 07:53:58 +00001409 if (Instruction *R = FoldOpIntoSelect(I, SI))
Chris Lattner2eefe512004-04-09 19:05:30 +00001410 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00001411
1412 if (isa<PHINode>(Op0))
1413 if (Instruction *NV = FoldOpIntoPhi(I))
1414 return NV;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00001415 }
1416
Dan Gohman186a6362009-08-12 16:04:34 +00001417 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
Chris Lattnera2498472009-10-11 21:36:10 +00001418 if (Value *Op1v = dyn_castNegVal(Op1))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001419 return BinaryOperator::CreateMul(Op0v, Op1v);
Chris Lattnera4f445b2003-03-10 23:23:04 +00001420
Nick Lewycky0c730792008-11-21 07:33:58 +00001421 // (X / Y) * Y = X - (X % Y)
1422 // (X / Y) * -Y = (X % Y) - X
1423 {
Chris Lattnera2498472009-10-11 21:36:10 +00001424 Value *Op1C = Op1;
Nick Lewycky0c730792008-11-21 07:33:58 +00001425 BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0);
1426 if (!BO ||
1427 (BO->getOpcode() != Instruction::UDiv &&
1428 BO->getOpcode() != Instruction::SDiv)) {
Chris Lattnera2498472009-10-11 21:36:10 +00001429 Op1C = Op0;
1430 BO = dyn_cast<BinaryOperator>(Op1);
Nick Lewycky0c730792008-11-21 07:33:58 +00001431 }
Chris Lattnera2498472009-10-11 21:36:10 +00001432 Value *Neg = dyn_castNegVal(Op1C);
Nick Lewycky0c730792008-11-21 07:33:58 +00001433 if (BO && BO->hasOneUse() &&
Chris Lattnera2498472009-10-11 21:36:10 +00001434 (BO->getOperand(1) == Op1C || BO->getOperand(1) == Neg) &&
Nick Lewycky0c730792008-11-21 07:33:58 +00001435 (BO->getOpcode() == Instruction::UDiv ||
1436 BO->getOpcode() == Instruction::SDiv)) {
1437 Value *Op0BO = BO->getOperand(0), *Op1BO = BO->getOperand(1);
1438
Dan Gohmanfa94b942009-08-12 16:33:09 +00001439 // If the division is exact, X % Y is zero.
1440 if (SDivOperator *SDiv = dyn_cast<SDivOperator>(BO))
1441 if (SDiv->isExact()) {
Chris Lattnera2498472009-10-11 21:36:10 +00001442 if (Op1BO == Op1C)
Dan Gohmanfa94b942009-08-12 16:33:09 +00001443 return ReplaceInstUsesWith(I, Op0BO);
Chris Lattnera2498472009-10-11 21:36:10 +00001444 return BinaryOperator::CreateNeg(Op0BO);
Dan Gohmanfa94b942009-08-12 16:33:09 +00001445 }
1446
Chris Lattner74381062009-08-30 07:44:24 +00001447 Value *Rem;
Nick Lewycky0c730792008-11-21 07:33:58 +00001448 if (BO->getOpcode() == Instruction::UDiv)
Chris Lattner74381062009-08-30 07:44:24 +00001449 Rem = Builder->CreateURem(Op0BO, Op1BO);
Nick Lewycky0c730792008-11-21 07:33:58 +00001450 else
Chris Lattner74381062009-08-30 07:44:24 +00001451 Rem = Builder->CreateSRem(Op0BO, Op1BO);
Nick Lewycky0c730792008-11-21 07:33:58 +00001452 Rem->takeName(BO);
1453
Chris Lattnera2498472009-10-11 21:36:10 +00001454 if (Op1BO == Op1C)
Nick Lewycky0c730792008-11-21 07:33:58 +00001455 return BinaryOperator::CreateSub(Op0BO, Rem);
Chris Lattner74381062009-08-30 07:44:24 +00001456 return BinaryOperator::CreateSub(Rem, Op0BO);
Nick Lewycky0c730792008-11-21 07:33:58 +00001457 }
1458 }
1459
Chris Lattner8af304a2009-10-11 07:53:15 +00001460 /// i1 mul -> i1 and.
Chris Lattner4de84762010-01-04 07:02:48 +00001461 if (I.getType() == Type::getInt1Ty(I.getContext()))
Chris Lattnera2498472009-10-11 21:36:10 +00001462 return BinaryOperator::CreateAnd(Op0, Op1);
Nick Lewycky9419ddb2008-05-31 17:59:52 +00001463
Chris Lattner8af304a2009-10-11 07:53:15 +00001464 // X*(1 << Y) --> X << Y
1465 // (1 << Y)*X --> X << Y
1466 {
1467 Value *Y;
1468 if (match(Op0, m_Shl(m_One(), m_Value(Y))))
Chris Lattnera2498472009-10-11 21:36:10 +00001469 return BinaryOperator::CreateShl(Op1, Y);
1470 if (match(Op1, m_Shl(m_One(), m_Value(Y))))
Chris Lattner8af304a2009-10-11 07:53:15 +00001471 return BinaryOperator::CreateShl(Op0, Y);
1472 }
1473
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00001474 // If one of the operands of the multiply is a cast from a boolean value, then
1475 // we know the bool is either zero or one, so this is a 'masking' multiply.
Chris Lattnerd2c58362009-10-11 21:29:45 +00001476 // X * Y (where Y is 0 or 1) -> X & (0-Y)
1477 if (!isa<VectorType>(I.getType())) {
1478 // -2 is "-1 << 1" so it is all bits set except the low one.
Dale Johannesenc1deda52009-10-12 18:45:32 +00001479 APInt Negative2(I.getType()->getPrimitiveSizeInBits(), (uint64_t)-2, true);
Chris Lattner0036e3a2009-10-11 21:22:21 +00001480
Chris Lattnerd2c58362009-10-11 21:29:45 +00001481 Value *BoolCast = 0, *OtherOp = 0;
1482 if (MaskedValueIsZero(Op0, Negative2))
Chris Lattnera2498472009-10-11 21:36:10 +00001483 BoolCast = Op0, OtherOp = Op1;
1484 else if (MaskedValueIsZero(Op1, Negative2))
1485 BoolCast = Op1, OtherOp = Op0;
Chris Lattnerd2c58362009-10-11 21:29:45 +00001486
Chris Lattner0036e3a2009-10-11 21:22:21 +00001487 if (BoolCast) {
Chris Lattner0036e3a2009-10-11 21:22:21 +00001488 Value *V = Builder->CreateSub(Constant::getNullValue(I.getType()),
1489 BoolCast, "tmp");
1490 return BinaryOperator::CreateAnd(V, OtherOp);
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00001491 }
1492 }
1493
Chris Lattner7e708292002-06-25 16:13:24 +00001494 return Changed ? &I : 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00001495}
1496
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001497Instruction *InstCombiner::visitFMul(BinaryOperator &I) {
1498 bool Changed = SimplifyCommutative(I);
Chris Lattnera2498472009-10-11 21:36:10 +00001499 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001500
1501 // Simplify mul instructions with a constant RHS...
Chris Lattnera2498472009-10-11 21:36:10 +00001502 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
1503 if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1C)) {
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001504 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
1505 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
1506 if (Op1F->isExactlyValue(1.0))
1507 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0'
Chris Lattnera2498472009-10-11 21:36:10 +00001508 } else if (isa<VectorType>(Op1C->getType())) {
1509 if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1C)) {
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001510 // As above, vector X*splat(1.0) -> X in all defined cases.
1511 if (Constant *Splat = Op1V->getSplatValue()) {
1512 if (ConstantFP *F = dyn_cast<ConstantFP>(Splat))
1513 if (F->isExactlyValue(1.0))
1514 return ReplaceInstUsesWith(I, Op0);
1515 }
1516 }
1517 }
1518
1519 // Try to fold constant mul into select arguments.
1520 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner80f43d32010-01-04 07:53:58 +00001521 if (Instruction *R = FoldOpIntoSelect(I, SI))
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001522 return R;
1523
1524 if (isa<PHINode>(Op0))
1525 if (Instruction *NV = FoldOpIntoPhi(I))
1526 return NV;
1527 }
1528
Dan Gohman186a6362009-08-12 16:04:34 +00001529 if (Value *Op0v = dyn_castFNegVal(Op0)) // -X * -Y = X*Y
Chris Lattnera2498472009-10-11 21:36:10 +00001530 if (Value *Op1v = dyn_castFNegVal(Op1))
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001531 return BinaryOperator::CreateFMul(Op0v, Op1v);
1532
1533 return Changed ? &I : 0;
1534}
1535
Chris Lattnerfdb19e52008-07-14 00:15:52 +00001536/// SimplifyDivRemOfSelect - Try to fold a divide or remainder of a select
1537/// instruction.
1538bool InstCombiner::SimplifyDivRemOfSelect(BinaryOperator &I) {
1539 SelectInst *SI = cast<SelectInst>(I.getOperand(1));
1540
1541 // div/rem X, (Cond ? 0 : Y) -> div/rem X, Y
1542 int NonNullOperand = -1;
1543 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
1544 if (ST->isNullValue())
1545 NonNullOperand = 2;
1546 // div/rem X, (Cond ? Y : 0) -> div/rem X, Y
1547 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
1548 if (ST->isNullValue())
1549 NonNullOperand = 1;
1550
1551 if (NonNullOperand == -1)
1552 return false;
1553
1554 Value *SelectCond = SI->getOperand(0);
1555
1556 // Change the div/rem to use 'Y' instead of the select.
1557 I.setOperand(1, SI->getOperand(NonNullOperand));
1558
1559 // Okay, we know we replace the operand of the div/rem with 'Y' with no
1560 // problem. However, the select, or the condition of the select may have
1561 // multiple uses. Based on our knowledge that the operand must be non-zero,
1562 // propagate the known value for the select into other uses of it, and
1563 // propagate a known value of the condition into its other users.
1564
1565 // If the select and condition only have a single use, don't bother with this,
1566 // early exit.
1567 if (SI->use_empty() && SelectCond->hasOneUse())
1568 return true;
1569
1570 // Scan the current block backward, looking for other uses of SI.
1571 BasicBlock::iterator BBI = &I, BBFront = I.getParent()->begin();
1572
1573 while (BBI != BBFront) {
1574 --BBI;
1575 // If we found a call to a function, we can't assume it will return, so
1576 // information from below it cannot be propagated above it.
1577 if (isa<CallInst>(BBI) && !isa<IntrinsicInst>(BBI))
1578 break;
1579
1580 // Replace uses of the select or its condition with the known values.
1581 for (Instruction::op_iterator I = BBI->op_begin(), E = BBI->op_end();
1582 I != E; ++I) {
1583 if (*I == SI) {
1584 *I = SI->getOperand(NonNullOperand);
Chris Lattner7a1e9242009-08-30 06:13:40 +00001585 Worklist.Add(BBI);
Chris Lattnerfdb19e52008-07-14 00:15:52 +00001586 } else if (*I == SelectCond) {
Chris Lattner4de84762010-01-04 07:02:48 +00001587 *I = NonNullOperand == 1 ? ConstantInt::getTrue(BBI->getContext()) :
1588 ConstantInt::getFalse(BBI->getContext());
Chris Lattner7a1e9242009-08-30 06:13:40 +00001589 Worklist.Add(BBI);
Chris Lattnerfdb19e52008-07-14 00:15:52 +00001590 }
1591 }
1592
1593 // If we past the instruction, quit looking for it.
1594 if (&*BBI == SI)
1595 SI = 0;
1596 if (&*BBI == SelectCond)
1597 SelectCond = 0;
1598
1599 // If we ran out of things to eliminate, break out of the loop.
1600 if (SelectCond == 0 && SI == 0)
1601 break;
1602
1603 }
1604 return true;
1605}
1606
1607
Reid Spencer1628cec2006-10-26 06:15:43 +00001608/// This function implements the transforms on div instructions that work
1609/// regardless of the kind of div instruction it is (udiv, sdiv, or fdiv). It is
1610/// used by the visitors to those instructions.
1611/// @brief Transforms common to all three div instructions
Reid Spencer3da59db2006-11-27 01:05:10 +00001612Instruction *InstCombiner::commonDivTransforms(BinaryOperator &I) {
Chris Lattner857e8cd2004-12-12 21:48:58 +00001613 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnere87597f2004-10-16 18:11:37 +00001614
Chris Lattner50b2ca42008-02-19 06:12:18 +00001615 // undef / X -> 0 for integer.
1616 // undef / X -> undef for FP (the undef could be a snan).
1617 if (isa<UndefValue>(Op0)) {
1618 if (Op0->getType()->isFPOrFPVector())
1619 return ReplaceInstUsesWith(I, Op0);
Owen Andersona7235ea2009-07-31 20:28:14 +00001620 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner50b2ca42008-02-19 06:12:18 +00001621 }
Reid Spencer1628cec2006-10-26 06:15:43 +00001622
1623 // X / undef -> undef
Chris Lattner857e8cd2004-12-12 21:48:58 +00001624 if (isa<UndefValue>(Op1))
Reid Spencer1628cec2006-10-26 06:15:43 +00001625 return ReplaceInstUsesWith(I, Op1);
Chris Lattner857e8cd2004-12-12 21:48:58 +00001626
Reid Spencer1628cec2006-10-26 06:15:43 +00001627 return 0;
1628}
Misha Brukmanfd939082005-04-21 23:48:37 +00001629
Reid Spencer1628cec2006-10-26 06:15:43 +00001630/// This function implements the transforms common to both integer division
1631/// instructions (udiv and sdiv). It is called by the visitors to those integer
1632/// division instructions.
1633/// @brief Common integer divide transforms
Reid Spencer3da59db2006-11-27 01:05:10 +00001634Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
Reid Spencer1628cec2006-10-26 06:15:43 +00001635 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1636
Chris Lattnerb2ae9e32008-05-16 02:59:42 +00001637 // (sdiv X, X) --> 1 (udiv X, X) --> 1
Nick Lewycky39ac3b52008-05-23 03:26:47 +00001638 if (Op0 == Op1) {
1639 if (const VectorType *Ty = dyn_cast<VectorType>(I.getType())) {
Owen Andersoneed707b2009-07-24 23:12:02 +00001640 Constant *CI = ConstantInt::get(Ty->getElementType(), 1);
Nick Lewycky39ac3b52008-05-23 03:26:47 +00001641 std::vector<Constant*> Elts(Ty->getNumElements(), CI);
Owen Andersonaf7ec972009-07-28 21:19:26 +00001642 return ReplaceInstUsesWith(I, ConstantVector::get(Elts));
Nick Lewycky39ac3b52008-05-23 03:26:47 +00001643 }
1644
Owen Andersoneed707b2009-07-24 23:12:02 +00001645 Constant *CI = ConstantInt::get(I.getType(), 1);
Nick Lewycky39ac3b52008-05-23 03:26:47 +00001646 return ReplaceInstUsesWith(I, CI);
1647 }
Chris Lattnerb2ae9e32008-05-16 02:59:42 +00001648
Reid Spencer1628cec2006-10-26 06:15:43 +00001649 if (Instruction *Common = commonDivTransforms(I))
1650 return Common;
Chris Lattnerfdb19e52008-07-14 00:15:52 +00001651
1652 // Handle cases involving: [su]div X, (select Cond, Y, Z)
1653 // This does not apply for fdiv.
1654 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
1655 return &I;
Reid Spencer1628cec2006-10-26 06:15:43 +00001656
1657 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
1658 // div X, 1 == X
1659 if (RHS->equalsInt(1))
1660 return ReplaceInstUsesWith(I, Op0);
1661
1662 // (X / C1) / C2 -> X / (C1*C2)
1663 if (Instruction *LHS = dyn_cast<Instruction>(Op0))
1664 if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
1665 if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
Owen Andersond672ecb2009-07-03 00:17:18 +00001666 if (MultiplyOverflows(RHS, LHSRHS,
Dan Gohman186a6362009-08-12 16:04:34 +00001667 I.getOpcode()==Instruction::SDiv))
Owen Andersona7235ea2009-07-31 20:28:14 +00001668 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Nick Lewyckye0cfecf2008-02-18 22:48:05 +00001669 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001670 return BinaryOperator::Create(I.getOpcode(), LHS->getOperand(0),
Owen Andersonbaf3c402009-07-29 18:55:55 +00001671 ConstantExpr::getMul(RHS, LHSRHS));
Chris Lattnerbf70b832005-04-08 04:03:26 +00001672 }
Reid Spencer1628cec2006-10-26 06:15:43 +00001673
Reid Spencerbca0e382007-03-23 20:05:17 +00001674 if (!RHS->isZero()) { // avoid X udiv 0
Reid Spencer1628cec2006-10-26 06:15:43 +00001675 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner80f43d32010-01-04 07:53:58 +00001676 if (Instruction *R = FoldOpIntoSelect(I, SI))
Reid Spencer1628cec2006-10-26 06:15:43 +00001677 return R;
1678 if (isa<PHINode>(Op0))
1679 if (Instruction *NV = FoldOpIntoPhi(I))
1680 return NV;
1681 }
Chris Lattner8e49e082006-09-09 20:26:32 +00001682 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001683
Chris Lattnera2881962003-02-18 19:28:33 +00001684 // 0 / X == 0, we don't need to preserve faults!
Chris Lattner857e8cd2004-12-12 21:48:58 +00001685 if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
Chris Lattnera2881962003-02-18 19:28:33 +00001686 if (LHS->equalsInt(0))
Owen Andersona7235ea2009-07-31 20:28:14 +00001687 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00001688
Nick Lewycky9419ddb2008-05-31 17:59:52 +00001689 // It can't be division by zero, hence it must be division by one.
Chris Lattner4de84762010-01-04 07:02:48 +00001690 if (I.getType() == Type::getInt1Ty(I.getContext()))
Nick Lewycky9419ddb2008-05-31 17:59:52 +00001691 return ReplaceInstUsesWith(I, Op0);
1692
Nick Lewycky895f0852008-11-27 20:21:08 +00001693 if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
1694 if (ConstantInt *X = cast_or_null<ConstantInt>(Op1V->getSplatValue()))
1695 // div X, 1 == X
1696 if (X->isOne())
1697 return ReplaceInstUsesWith(I, Op0);
1698 }
1699
Reid Spencer1628cec2006-10-26 06:15:43 +00001700 return 0;
1701}
1702
1703Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
1704 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1705
1706 // Handle the integer div common cases
1707 if (Instruction *Common = commonIDivTransforms(I))
1708 return Common;
1709
Reid Spencer1628cec2006-10-26 06:15:43 +00001710 if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
Nick Lewycky8ca52482008-11-27 22:41:10 +00001711 // X udiv C^2 -> X >> C
1712 // Check to see if this is an unsigned division with an exact power of 2,
1713 // if so, convert to a right shift.
Reid Spencer6eb0d992007-03-26 23:58:26 +00001714 if (C->getValue().isPowerOf2()) // 0 not included in isPowerOf2
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001715 return BinaryOperator::CreateLShr(Op0,
Owen Andersoneed707b2009-07-24 23:12:02 +00001716 ConstantInt::get(Op0->getType(), C->getValue().logBase2()));
Nick Lewycky8ca52482008-11-27 22:41:10 +00001717
1718 // X udiv C, where C >= signbit
1719 if (C->getValue().isNegative()) {
Chris Lattner74381062009-08-30 07:44:24 +00001720 Value *IC = Builder->CreateICmpULT( Op0, C);
Owen Andersona7235ea2009-07-31 20:28:14 +00001721 return SelectInst::Create(IC, Constant::getNullValue(I.getType()),
Owen Andersoneed707b2009-07-24 23:12:02 +00001722 ConstantInt::get(I.getType(), 1));
Nick Lewycky8ca52482008-11-27 22:41:10 +00001723 }
Reid Spencer1628cec2006-10-26 06:15:43 +00001724 }
1725
1726 // X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2)
Reid Spencer832254e2007-02-02 02:16:23 +00001727 if (BinaryOperator *RHSI = dyn_cast<BinaryOperator>(I.getOperand(1))) {
Reid Spencer1628cec2006-10-26 06:15:43 +00001728 if (RHSI->getOpcode() == Instruction::Shl &&
1729 isa<ConstantInt>(RHSI->getOperand(0))) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00001730 const APInt& C1 = cast<ConstantInt>(RHSI->getOperand(0))->getValue();
Reid Spencerbca0e382007-03-23 20:05:17 +00001731 if (C1.isPowerOf2()) {
Reid Spencer1628cec2006-10-26 06:15:43 +00001732 Value *N = RHSI->getOperand(1);
Reid Spencer3da59db2006-11-27 01:05:10 +00001733 const Type *NTy = N->getType();
Chris Lattner74381062009-08-30 07:44:24 +00001734 if (uint32_t C2 = C1.logBase2())
1735 N = Builder->CreateAdd(N, ConstantInt::get(NTy, C2), "tmp");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001736 return BinaryOperator::CreateLShr(Op0, N);
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00001737 }
1738 }
Chris Lattnerc812e5d2005-11-05 07:40:31 +00001739 }
1740
Reid Spencer1628cec2006-10-26 06:15:43 +00001741 // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
1742 // where C1&C2 are powers of two.
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00001743 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Reid Spencer1628cec2006-10-26 06:15:43 +00001744 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00001745 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00001746 const APInt &TVA = STO->getValue(), &FVA = SFO->getValue();
Reid Spencerbca0e382007-03-23 20:05:17 +00001747 if (TVA.isPowerOf2() && FVA.isPowerOf2()) {
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00001748 // Compute the shift amounts
Reid Spencerbca0e382007-03-23 20:05:17 +00001749 uint32_t TSA = TVA.logBase2(), FSA = FVA.logBase2();
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00001750 // Construct the "on true" case of the select
Owen Andersoneed707b2009-07-24 23:12:02 +00001751 Constant *TC = ConstantInt::get(Op0->getType(), TSA);
Chris Lattner74381062009-08-30 07:44:24 +00001752 Value *TSI = Builder->CreateLShr(Op0, TC, SI->getName()+".t");
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00001753
1754 // Construct the "on false" case of the select
Owen Andersoneed707b2009-07-24 23:12:02 +00001755 Constant *FC = ConstantInt::get(Op0->getType(), FSA);
Chris Lattner74381062009-08-30 07:44:24 +00001756 Value *FSI = Builder->CreateLShr(Op0, FC, SI->getName()+".f");
Reid Spencer1628cec2006-10-26 06:15:43 +00001757
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00001758 // construct the select instruction and return it.
Gabor Greif051a9502008-04-06 20:25:17 +00001759 return SelectInst::Create(SI->getOperand(0), TSI, FSI, SI->getName());
Reid Spencer1628cec2006-10-26 06:15:43 +00001760 }
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00001761 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00001762 return 0;
1763}
1764
Reid Spencer1628cec2006-10-26 06:15:43 +00001765Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
1766 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1767
1768 // Handle the integer div common cases
1769 if (Instruction *Common = commonIDivTransforms(I))
1770 return Common;
1771
1772 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
1773 // sdiv X, -1 == -X
1774 if (RHS->isAllOnesValue())
Dan Gohman4ae51262009-08-12 16:23:25 +00001775 return BinaryOperator::CreateNeg(Op0);
Dan Gohman1bdf5dc2009-08-11 20:47:47 +00001776
Dan Gohmanfa94b942009-08-12 16:33:09 +00001777 // sdiv X, C --> ashr X, log2(C)
Dan Gohman1bdf5dc2009-08-11 20:47:47 +00001778 if (cast<SDivOperator>(&I)->isExact() &&
1779 RHS->getValue().isNonNegative() &&
1780 RHS->getValue().isPowerOf2()) {
1781 Value *ShAmt = llvm::ConstantInt::get(RHS->getType(),
1782 RHS->getValue().exactLogBase2());
1783 return BinaryOperator::CreateAShr(Op0, ShAmt, I.getName());
1784 }
Dan Gohman9ca9daa2009-08-12 16:37:02 +00001785
1786 // -X/C --> X/-C provided the negation doesn't overflow.
1787 if (SubOperator *Sub = dyn_cast<SubOperator>(Op0))
1788 if (isa<Constant>(Sub->getOperand(0)) &&
1789 cast<Constant>(Sub->getOperand(0))->isNullValue() &&
Dan Gohman5078f842009-08-20 17:11:38 +00001790 Sub->hasNoSignedWrap())
Dan Gohman9ca9daa2009-08-12 16:37:02 +00001791 return BinaryOperator::CreateSDiv(Sub->getOperand(1),
1792 ConstantExpr::getNeg(RHS));
Reid Spencer1628cec2006-10-26 06:15:43 +00001793 }
1794
1795 // If the sign bits of both operands are zero (i.e. we can prove they are
1796 // unsigned inputs), turn this into a udiv.
Chris Lattner42a75512007-01-15 02:27:26 +00001797 if (I.getType()->isInteger()) {
Reid Spencerbca0e382007-03-23 20:05:17 +00001798 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
Eli Friedman8be17392009-07-18 09:53:21 +00001799 if (MaskedValueIsZero(Op0, Mask)) {
1800 if (MaskedValueIsZero(Op1, Mask)) {
1801 // X sdiv Y -> X udiv Y, iff X and Y don't have sign bit set
1802 return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
1803 }
1804 ConstantInt *ShiftedInt;
Dan Gohman4ae51262009-08-12 16:23:25 +00001805 if (match(Op1, m_Shl(m_ConstantInt(ShiftedInt), m_Value())) &&
Eli Friedman8be17392009-07-18 09:53:21 +00001806 ShiftedInt->getValue().isPowerOf2()) {
1807 // X sdiv (1 << Y) -> X udiv (1 << Y) ( -> X u>> Y)
1808 // Safe because the only negative value (1 << Y) can take on is
1809 // INT_MIN, and X sdiv INT_MIN == X udiv INT_MIN == 0 if X doesn't have
1810 // the sign bit set.
1811 return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
1812 }
Reid Spencer1628cec2006-10-26 06:15:43 +00001813 }
Eli Friedman8be17392009-07-18 09:53:21 +00001814 }
Reid Spencer1628cec2006-10-26 06:15:43 +00001815
1816 return 0;
1817}
1818
1819Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
1820 return commonDivTransforms(I);
1821}
Chris Lattner3f5b8772002-05-06 16:14:14 +00001822
Reid Spencer0a783f72006-11-02 01:53:59 +00001823/// This function implements the transforms on rem instructions that work
1824/// regardless of the kind of rem instruction it is (urem, srem, or frem). It
1825/// is used by the visitors to those instructions.
1826/// @brief Transforms common to all three rem instructions
1827Instruction *InstCombiner::commonRemTransforms(BinaryOperator &I) {
Chris Lattner857e8cd2004-12-12 21:48:58 +00001828 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Reid Spencer0a783f72006-11-02 01:53:59 +00001829
Chris Lattner50b2ca42008-02-19 06:12:18 +00001830 if (isa<UndefValue>(Op0)) { // undef % X -> 0
1831 if (I.getType()->isFPOrFPVector())
1832 return ReplaceInstUsesWith(I, Op0); // X % undef -> undef (could be SNaN)
Owen Andersona7235ea2009-07-31 20:28:14 +00001833 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner50b2ca42008-02-19 06:12:18 +00001834 }
Chris Lattner19ccd5c2006-02-28 05:30:45 +00001835 if (isa<UndefValue>(Op1))
1836 return ReplaceInstUsesWith(I, Op1); // X % undef -> undef
Reid Spencer0a783f72006-11-02 01:53:59 +00001837
1838 // Handle cases involving: rem X, (select Cond, Y, Z)
Chris Lattnerfdb19e52008-07-14 00:15:52 +00001839 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
1840 return &I;
Chris Lattner5b73c082004-07-06 07:01:22 +00001841
Reid Spencer0a783f72006-11-02 01:53:59 +00001842 return 0;
1843}
1844
1845/// This function implements the transforms common to both integer remainder
1846/// instructions (urem and srem). It is called by the visitors to those integer
1847/// remainder instructions.
1848/// @brief Common integer remainder transforms
1849Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
1850 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1851
1852 if (Instruction *common = commonRemTransforms(I))
1853 return common;
1854
Dale Johannesened6af242009-01-21 00:35:19 +00001855 // 0 % X == 0 for integer, we don't need to preserve faults!
1856 if (Constant *LHS = dyn_cast<Constant>(Op0))
1857 if (LHS->isNullValue())
Owen Andersona7235ea2009-07-31 20:28:14 +00001858 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Dale Johannesened6af242009-01-21 00:35:19 +00001859
Chris Lattner857e8cd2004-12-12 21:48:58 +00001860 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner19ccd5c2006-02-28 05:30:45 +00001861 // X % 0 == undef, we don't need to preserve faults!
1862 if (RHS->equalsInt(0))
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001863 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
Chris Lattner19ccd5c2006-02-28 05:30:45 +00001864
Chris Lattnera2881962003-02-18 19:28:33 +00001865 if (RHS->equalsInt(1)) // X % 1 == 0
Owen Andersona7235ea2009-07-31 20:28:14 +00001866 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00001867
Chris Lattner97943922006-02-28 05:49:21 +00001868 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
1869 if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
Chris Lattner80f43d32010-01-04 07:53:58 +00001870 if (Instruction *R = FoldOpIntoSelect(I, SI))
Chris Lattner97943922006-02-28 05:49:21 +00001871 return R;
1872 } else if (isa<PHINode>(Op0I)) {
1873 if (Instruction *NV = FoldOpIntoPhi(I))
1874 return NV;
Chris Lattner97943922006-02-28 05:49:21 +00001875 }
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001876
1877 // See if we can fold away this rem instruction.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001878 if (SimplifyDemandedInstructionBits(I))
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001879 return &I;
Chris Lattner97943922006-02-28 05:49:21 +00001880 }
Chris Lattnera2881962003-02-18 19:28:33 +00001881 }
1882
Reid Spencer0a783f72006-11-02 01:53:59 +00001883 return 0;
1884}
1885
1886Instruction *InstCombiner::visitURem(BinaryOperator &I) {
1887 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1888
1889 if (Instruction *common = commonIRemTransforms(I))
1890 return common;
1891
1892 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
1893 // X urem C^2 -> X and C
1894 // Check to see if this is an unsigned remainder with an exact power of 2,
1895 // if so, convert to a bitwise and.
1896 if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
Reid Spencerbca0e382007-03-23 20:05:17 +00001897 if (C->getValue().isPowerOf2())
Dan Gohman186a6362009-08-12 16:04:34 +00001898 return BinaryOperator::CreateAnd(Op0, SubOne(C));
Reid Spencer0a783f72006-11-02 01:53:59 +00001899 }
1900
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00001901 if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
Reid Spencer0a783f72006-11-02 01:53:59 +00001902 // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)
1903 if (RHSI->getOpcode() == Instruction::Shl &&
1904 isa<ConstantInt>(RHSI->getOperand(0))) {
Zhou Sheng0fc50952007-03-25 05:01:29 +00001905 if (cast<ConstantInt>(RHSI->getOperand(0))->getValue().isPowerOf2()) {
Owen Andersona7235ea2009-07-31 20:28:14 +00001906 Constant *N1 = Constant::getAllOnesValue(I.getType());
Chris Lattner74381062009-08-30 07:44:24 +00001907 Value *Add = Builder->CreateAdd(RHSI, N1, "tmp");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001908 return BinaryOperator::CreateAnd(Op0, Add);
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00001909 }
1910 }
Reid Spencer0a783f72006-11-02 01:53:59 +00001911 }
Chris Lattner8e49e082006-09-09 20:26:32 +00001912
Reid Spencer0a783f72006-11-02 01:53:59 +00001913 // urem X, (select Cond, 2^C1, 2^C2) --> select Cond, (and X, C1), (and X, C2)
1914 // where C1&C2 are powers of two.
1915 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
1916 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
1917 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
1918 // STO == 0 and SFO == 0 handled above.
Reid Spencerbca0e382007-03-23 20:05:17 +00001919 if ((STO->getValue().isPowerOf2()) &&
1920 (SFO->getValue().isPowerOf2())) {
Chris Lattner74381062009-08-30 07:44:24 +00001921 Value *TrueAnd = Builder->CreateAnd(Op0, SubOne(STO),
1922 SI->getName()+".t");
1923 Value *FalseAnd = Builder->CreateAnd(Op0, SubOne(SFO),
1924 SI->getName()+".f");
Gabor Greif051a9502008-04-06 20:25:17 +00001925 return SelectInst::Create(SI->getOperand(0), TrueAnd, FalseAnd);
Reid Spencer0a783f72006-11-02 01:53:59 +00001926 }
1927 }
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00001928 }
1929
Chris Lattner3f5b8772002-05-06 16:14:14 +00001930 return 0;
1931}
1932
Reid Spencer0a783f72006-11-02 01:53:59 +00001933Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
1934 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1935
Dan Gohmancff55092007-11-05 23:16:33 +00001936 // Handle the integer rem common cases
Chris Lattnere5ecdb52009-08-30 06:22:51 +00001937 if (Instruction *Common = commonIRemTransforms(I))
1938 return Common;
Reid Spencer0a783f72006-11-02 01:53:59 +00001939
Dan Gohman186a6362009-08-12 16:04:34 +00001940 if (Value *RHSNeg = dyn_castNegVal(Op1))
Nick Lewycky23c04302008-09-03 06:24:21 +00001941 if (!isa<Constant>(RHSNeg) ||
1942 (isa<ConstantInt>(RHSNeg) &&
1943 cast<ConstantInt>(RHSNeg)->getValue().isStrictlyPositive())) {
Reid Spencer0a783f72006-11-02 01:53:59 +00001944 // X % -Y -> X % Y
Chris Lattner3c4e38e2009-08-30 06:27:41 +00001945 Worklist.AddValue(I.getOperand(1));
Reid Spencer0a783f72006-11-02 01:53:59 +00001946 I.setOperand(1, RHSNeg);
1947 return &I;
1948 }
Nick Lewyckya06cf822008-09-30 06:08:34 +00001949
Dan Gohmancff55092007-11-05 23:16:33 +00001950 // If the sign bits of both operands are zero (i.e. we can prove they are
Reid Spencer0a783f72006-11-02 01:53:59 +00001951 // unsigned inputs), turn this into a urem.
Dan Gohmancff55092007-11-05 23:16:33 +00001952 if (I.getType()->isInteger()) {
1953 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
1954 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
1955 // X srem Y -> X urem Y, iff X and Y don't have sign bit set
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001956 return BinaryOperator::CreateURem(Op0, Op1, I.getName());
Dan Gohmancff55092007-11-05 23:16:33 +00001957 }
Reid Spencer0a783f72006-11-02 01:53:59 +00001958 }
1959
Nick Lewycky2a8f6592008-12-18 06:31:11 +00001960 // If it's a constant vector, flip any negative values positive.
Nick Lewycky9dce8732008-12-20 16:48:00 +00001961 if (ConstantVector *RHSV = dyn_cast<ConstantVector>(Op1)) {
1962 unsigned VWidth = RHSV->getNumOperands();
Nick Lewycky2a8f6592008-12-18 06:31:11 +00001963
Nick Lewycky9dce8732008-12-20 16:48:00 +00001964 bool hasNegative = false;
1965 for (unsigned i = 0; !hasNegative && i != VWidth; ++i)
1966 if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i)))
1967 if (RHS->getValue().isNegative())
1968 hasNegative = true;
1969
1970 if (hasNegative) {
1971 std::vector<Constant *> Elts(VWidth);
Nick Lewycky2a8f6592008-12-18 06:31:11 +00001972 for (unsigned i = 0; i != VWidth; ++i) {
1973 if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i))) {
1974 if (RHS->getValue().isNegative())
Owen Andersonbaf3c402009-07-29 18:55:55 +00001975 Elts[i] = cast<ConstantInt>(ConstantExpr::getNeg(RHS));
Nick Lewycky2a8f6592008-12-18 06:31:11 +00001976 else
1977 Elts[i] = RHS;
1978 }
1979 }
1980
Owen Andersonaf7ec972009-07-28 21:19:26 +00001981 Constant *NewRHSV = ConstantVector::get(Elts);
Nick Lewycky2a8f6592008-12-18 06:31:11 +00001982 if (NewRHSV != RHSV) {
Chris Lattner3c4e38e2009-08-30 06:27:41 +00001983 Worklist.AddValue(I.getOperand(1));
Nick Lewycky2a8f6592008-12-18 06:31:11 +00001984 I.setOperand(1, NewRHSV);
1985 return &I;
1986 }
1987 }
1988 }
1989
Reid Spencer0a783f72006-11-02 01:53:59 +00001990 return 0;
1991}
1992
1993Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
Reid Spencer0a783f72006-11-02 01:53:59 +00001994 return commonRemTransforms(I);
1995}
1996
Chris Lattner457dd822004-06-09 07:59:58 +00001997// isOneBitSet - Return true if there is exactly one bit set in the specified
1998// constant.
1999static bool isOneBitSet(const ConstantInt *CI) {
Reid Spencer5f6a8952007-03-20 00:16:52 +00002000 return CI->getValue().isPowerOf2();
Chris Lattner457dd822004-06-09 07:59:58 +00002001}
2002
Reid Spencere4d87aa2006-12-23 06:05:41 +00002003/// getICmpCode - Encode a icmp predicate into a three bit mask. These bits
Chris Lattneraa9c1f12003-08-13 20:16:26 +00002004/// are carefully arranged to allow folding of expressions such as:
2005///
2006/// (A < B) | (A > B) --> (A != B)
2007///
Reid Spencere4d87aa2006-12-23 06:05:41 +00002008/// Note that this is only valid if the first and second predicates have the
2009/// same sign. Is illegal to do: (A u< B) | (A s> B)
Chris Lattneraa9c1f12003-08-13 20:16:26 +00002010///
Reid Spencere4d87aa2006-12-23 06:05:41 +00002011/// Three bits are used to represent the condition, as follows:
2012/// 0 A > B
2013/// 1 A == B
2014/// 2 A < B
2015///
2016/// <=> Value Definition
2017/// 000 0 Always false
2018/// 001 1 A > B
2019/// 010 2 A == B
2020/// 011 3 A >= B
2021/// 100 4 A < B
2022/// 101 5 A != B
2023/// 110 6 A <= B
2024/// 111 7 Always true
2025///
2026static unsigned getICmpCode(const ICmpInst *ICI) {
2027 switch (ICI->getPredicate()) {
Chris Lattneraa9c1f12003-08-13 20:16:26 +00002028 // False -> 0
Reid Spencere4d87aa2006-12-23 06:05:41 +00002029 case ICmpInst::ICMP_UGT: return 1; // 001
2030 case ICmpInst::ICMP_SGT: return 1; // 001
2031 case ICmpInst::ICMP_EQ: return 2; // 010
2032 case ICmpInst::ICMP_UGE: return 3; // 011
2033 case ICmpInst::ICMP_SGE: return 3; // 011
2034 case ICmpInst::ICMP_ULT: return 4; // 100
2035 case ICmpInst::ICMP_SLT: return 4; // 100
2036 case ICmpInst::ICMP_NE: return 5; // 101
2037 case ICmpInst::ICMP_ULE: return 6; // 110
2038 case ICmpInst::ICMP_SLE: return 6; // 110
Chris Lattneraa9c1f12003-08-13 20:16:26 +00002039 // True -> 7
2040 default:
Torok Edwinc23197a2009-07-14 16:55:14 +00002041 llvm_unreachable("Invalid ICmp predicate!");
Chris Lattneraa9c1f12003-08-13 20:16:26 +00002042 return 0;
2043 }
2044}
2045
Evan Cheng8db90722008-10-14 17:15:11 +00002046/// getFCmpCode - Similar to getICmpCode but for FCmpInst. This encodes a fcmp
2047/// predicate into a three bit mask. It also returns whether it is an ordered
2048/// predicate by reference.
2049static unsigned getFCmpCode(FCmpInst::Predicate CC, bool &isOrdered) {
2050 isOrdered = false;
2051 switch (CC) {
2052 case FCmpInst::FCMP_ORD: isOrdered = true; return 0; // 000
2053 case FCmpInst::FCMP_UNO: return 0; // 000
Evan Cheng4990b252008-10-14 18:13:38 +00002054 case FCmpInst::FCMP_OGT: isOrdered = true; return 1; // 001
2055 case FCmpInst::FCMP_UGT: return 1; // 001
2056 case FCmpInst::FCMP_OEQ: isOrdered = true; return 2; // 010
2057 case FCmpInst::FCMP_UEQ: return 2; // 010
Evan Cheng8db90722008-10-14 17:15:11 +00002058 case FCmpInst::FCMP_OGE: isOrdered = true; return 3; // 011
2059 case FCmpInst::FCMP_UGE: return 3; // 011
2060 case FCmpInst::FCMP_OLT: isOrdered = true; return 4; // 100
2061 case FCmpInst::FCMP_ULT: return 4; // 100
Evan Cheng4990b252008-10-14 18:13:38 +00002062 case FCmpInst::FCMP_ONE: isOrdered = true; return 5; // 101
2063 case FCmpInst::FCMP_UNE: return 5; // 101
Evan Cheng8db90722008-10-14 17:15:11 +00002064 case FCmpInst::FCMP_OLE: isOrdered = true; return 6; // 110
2065 case FCmpInst::FCMP_ULE: return 6; // 110
Evan Cheng40300622008-10-14 18:44:08 +00002066 // True -> 7
Evan Cheng8db90722008-10-14 17:15:11 +00002067 default:
2068 // Not expecting FCMP_FALSE and FCMP_TRUE;
Torok Edwinc23197a2009-07-14 16:55:14 +00002069 llvm_unreachable("Unexpected FCmp predicate!");
Evan Cheng8db90722008-10-14 17:15:11 +00002070 return 0;
2071 }
2072}
2073
Reid Spencere4d87aa2006-12-23 06:05:41 +00002074/// getICmpValue - This is the complement of getICmpCode, which turns an
2075/// opcode and two operands into either a constant true or false, or a brand
Dan Gohman5d066ff2007-09-17 17:31:57 +00002076/// new ICmp instruction. The sign is passed in to determine which kind
Evan Cheng8db90722008-10-14 17:15:11 +00002077/// of predicate to use in the new icmp instruction.
Chris Lattner4de84762010-01-04 07:02:48 +00002078static Value *getICmpValue(bool sign, unsigned code, Value *LHS, Value *RHS) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00002079 switch (code) {
Torok Edwinc23197a2009-07-14 16:55:14 +00002080 default: llvm_unreachable("Illegal ICmp code!");
Chris Lattner4de84762010-01-04 07:02:48 +00002081 case 0: return ConstantInt::getFalse(LHS->getContext());
Reid Spencere4d87aa2006-12-23 06:05:41 +00002082 case 1:
2083 if (sign)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00002084 return new ICmpInst(ICmpInst::ICMP_SGT, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00002085 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00002086 return new ICmpInst(ICmpInst::ICMP_UGT, LHS, RHS);
2087 case 2: return new ICmpInst(ICmpInst::ICMP_EQ, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00002088 case 3:
2089 if (sign)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00002090 return new ICmpInst(ICmpInst::ICMP_SGE, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00002091 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00002092 return new ICmpInst(ICmpInst::ICMP_UGE, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00002093 case 4:
2094 if (sign)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00002095 return new ICmpInst(ICmpInst::ICMP_SLT, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00002096 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00002097 return new ICmpInst(ICmpInst::ICMP_ULT, LHS, RHS);
2098 case 5: return new ICmpInst(ICmpInst::ICMP_NE, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00002099 case 6:
2100 if (sign)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00002101 return new ICmpInst(ICmpInst::ICMP_SLE, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00002102 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00002103 return new ICmpInst(ICmpInst::ICMP_ULE, LHS, RHS);
Chris Lattner4de84762010-01-04 07:02:48 +00002104 case 7: return ConstantInt::getTrue(LHS->getContext());
Chris Lattneraa9c1f12003-08-13 20:16:26 +00002105 }
2106}
2107
Evan Cheng8db90722008-10-14 17:15:11 +00002108/// getFCmpValue - This is the complement of getFCmpCode, which turns an
2109/// opcode and two operands into either a FCmp instruction. isordered is passed
2110/// in to determine which kind of predicate to use in the new fcmp instruction.
2111static Value *getFCmpValue(bool isordered, unsigned code,
Chris Lattner4de84762010-01-04 07:02:48 +00002112 Value *LHS, Value *RHS) {
Evan Cheng8db90722008-10-14 17:15:11 +00002113 switch (code) {
Torok Edwinc23197a2009-07-14 16:55:14 +00002114 default: llvm_unreachable("Illegal FCmp code!");
Evan Cheng8db90722008-10-14 17:15:11 +00002115 case 0:
2116 if (isordered)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00002117 return new FCmpInst(FCmpInst::FCMP_ORD, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00002118 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00002119 return new FCmpInst(FCmpInst::FCMP_UNO, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00002120 case 1:
2121 if (isordered)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00002122 return new FCmpInst(FCmpInst::FCMP_OGT, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00002123 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00002124 return new FCmpInst(FCmpInst::FCMP_UGT, LHS, RHS);
Evan Cheng4990b252008-10-14 18:13:38 +00002125 case 2:
2126 if (isordered)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00002127 return new FCmpInst(FCmpInst::FCMP_OEQ, LHS, RHS);
Evan Cheng4990b252008-10-14 18:13:38 +00002128 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00002129 return new FCmpInst(FCmpInst::FCMP_UEQ, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00002130 case 3:
2131 if (isordered)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00002132 return new FCmpInst(FCmpInst::FCMP_OGE, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00002133 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00002134 return new FCmpInst(FCmpInst::FCMP_UGE, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00002135 case 4:
2136 if (isordered)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00002137 return new FCmpInst(FCmpInst::FCMP_OLT, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00002138 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00002139 return new FCmpInst(FCmpInst::FCMP_ULT, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00002140 case 5:
2141 if (isordered)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00002142 return new FCmpInst(FCmpInst::FCMP_ONE, LHS, RHS);
Evan Cheng4990b252008-10-14 18:13:38 +00002143 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00002144 return new FCmpInst(FCmpInst::FCMP_UNE, LHS, RHS);
Evan Cheng4990b252008-10-14 18:13:38 +00002145 case 6:
2146 if (isordered)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00002147 return new FCmpInst(FCmpInst::FCMP_OLE, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00002148 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00002149 return new FCmpInst(FCmpInst::FCMP_ULE, LHS, RHS);
Chris Lattner4de84762010-01-04 07:02:48 +00002150 case 7: return ConstantInt::getTrue(LHS->getContext());
Evan Cheng8db90722008-10-14 17:15:11 +00002151 }
2152}
2153
Chris Lattnerb9553d62008-11-16 04:55:20 +00002154/// PredicatesFoldable - Return true if both predicates match sign or if at
2155/// least one of them is an equality comparison (which is signless).
Reid Spencere4d87aa2006-12-23 06:05:41 +00002156static bool PredicatesFoldable(ICmpInst::Predicate p1, ICmpInst::Predicate p2) {
Nick Lewycky4a134af2009-10-25 05:20:17 +00002157 return (CmpInst::isSigned(p1) == CmpInst::isSigned(p2)) ||
2158 (CmpInst::isSigned(p1) && ICmpInst::isEquality(p2)) ||
2159 (CmpInst::isSigned(p2) && ICmpInst::isEquality(p1));
Reid Spencere4d87aa2006-12-23 06:05:41 +00002160}
2161
2162namespace {
2163// FoldICmpLogical - Implements (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
2164struct FoldICmpLogical {
Chris Lattneraa9c1f12003-08-13 20:16:26 +00002165 InstCombiner &IC;
2166 Value *LHS, *RHS;
Reid Spencere4d87aa2006-12-23 06:05:41 +00002167 ICmpInst::Predicate pred;
2168 FoldICmpLogical(InstCombiner &ic, ICmpInst *ICI)
2169 : IC(ic), LHS(ICI->getOperand(0)), RHS(ICI->getOperand(1)),
2170 pred(ICI->getPredicate()) {}
Chris Lattneraa9c1f12003-08-13 20:16:26 +00002171 bool shouldApply(Value *V) const {
Reid Spencere4d87aa2006-12-23 06:05:41 +00002172 if (ICmpInst *ICI = dyn_cast<ICmpInst>(V))
2173 if (PredicatesFoldable(pred, ICI->getPredicate()))
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00002174 return ((ICI->getOperand(0) == LHS && ICI->getOperand(1) == RHS) ||
2175 (ICI->getOperand(0) == RHS && ICI->getOperand(1) == LHS));
Chris Lattneraa9c1f12003-08-13 20:16:26 +00002176 return false;
2177 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00002178 Instruction *apply(Instruction &Log) const {
2179 ICmpInst *ICI = cast<ICmpInst>(Log.getOperand(0));
2180 if (ICI->getOperand(0) != LHS) {
2181 assert(ICI->getOperand(1) == LHS);
2182 ICI->swapOperands(); // Swap the LHS and RHS of the ICmp
Chris Lattneraa9c1f12003-08-13 20:16:26 +00002183 }
2184
Chris Lattnerbc1dbfc2007-03-13 14:27:42 +00002185 ICmpInst *RHSICI = cast<ICmpInst>(Log.getOperand(1));
Reid Spencere4d87aa2006-12-23 06:05:41 +00002186 unsigned LHSCode = getICmpCode(ICI);
Chris Lattnerbc1dbfc2007-03-13 14:27:42 +00002187 unsigned RHSCode = getICmpCode(RHSICI);
Chris Lattneraa9c1f12003-08-13 20:16:26 +00002188 unsigned Code;
2189 switch (Log.getOpcode()) {
2190 case Instruction::And: Code = LHSCode & RHSCode; break;
2191 case Instruction::Or: Code = LHSCode | RHSCode; break;
2192 case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
Torok Edwinc23197a2009-07-14 16:55:14 +00002193 default: llvm_unreachable("Illegal logical opcode!"); return 0;
Chris Lattneraa9c1f12003-08-13 20:16:26 +00002194 }
2195
Nick Lewycky4a134af2009-10-25 05:20:17 +00002196 bool isSigned = RHSICI->isSigned() || ICI->isSigned();
Chris Lattner4de84762010-01-04 07:02:48 +00002197 Value *RV = getICmpValue(isSigned, Code, LHS, RHS);
Chris Lattneraa9c1f12003-08-13 20:16:26 +00002198 if (Instruction *I = dyn_cast<Instruction>(RV))
2199 return I;
2200 // Otherwise, it's a constant boolean value...
2201 return IC.ReplaceInstUsesWith(Log, RV);
2202 }
2203};
Chris Lattnerd23b5ba2006-11-15 04:53:24 +00002204} // end anonymous namespace
Chris Lattneraa9c1f12003-08-13 20:16:26 +00002205
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00002206// OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
2207// the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
Reid Spencer832254e2007-02-02 02:16:23 +00002208// guaranteed to be a binary operator.
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00002209Instruction *InstCombiner::OptAndOp(Instruction *Op,
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002210 ConstantInt *OpRHS,
2211 ConstantInt *AndRHS,
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00002212 BinaryOperator &TheAnd) {
2213 Value *X = Op->getOperand(0);
Chris Lattner76f7fe22004-01-12 19:47:05 +00002214 Constant *Together = 0;
Reid Spencer832254e2007-02-02 02:16:23 +00002215 if (!Op->isShift())
Owen Andersonbaf3c402009-07-29 18:55:55 +00002216 Together = ConstantExpr::getAnd(AndRHS, OpRHS);
Chris Lattner7c4049c2004-01-12 19:35:11 +00002217
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00002218 switch (Op->getOpcode()) {
2219 case Instruction::Xor:
Chris Lattner6e7ba452005-01-01 16:22:27 +00002220 if (Op->hasOneUse()) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00002221 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
Chris Lattner74381062009-08-30 07:44:24 +00002222 Value *And = Builder->CreateAnd(X, AndRHS);
Chris Lattner6934a042007-02-11 01:23:03 +00002223 And->takeName(Op);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002224 return BinaryOperator::CreateXor(And, Together);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00002225 }
2226 break;
2227 case Instruction::Or:
Chris Lattner6e7ba452005-01-01 16:22:27 +00002228 if (Together == AndRHS) // (X | C) & C --> C
2229 return ReplaceInstUsesWith(TheAnd, AndRHS);
Misha Brukmanfd939082005-04-21 23:48:37 +00002230
Chris Lattner6e7ba452005-01-01 16:22:27 +00002231 if (Op->hasOneUse() && Together != OpRHS) {
2232 // (X | C1) & C2 --> (X | (C1&C2)) & C2
Chris Lattner74381062009-08-30 07:44:24 +00002233 Value *Or = Builder->CreateOr(X, Together);
Chris Lattner6934a042007-02-11 01:23:03 +00002234 Or->takeName(Op);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002235 return BinaryOperator::CreateAnd(Or, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00002236 }
2237 break;
2238 case Instruction::Add:
Chris Lattnerfd059242003-10-15 16:48:29 +00002239 if (Op->hasOneUse()) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00002240 // Adding a one to a single bit bit-field should be turned into an XOR
2241 // of the bit. First thing to check is to see if this AND is with a
2242 // single bit constant.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002243 const APInt& AndRHSV = cast<ConstantInt>(AndRHS)->getValue();
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00002244
2245 // If there is only one bit set...
Chris Lattner457dd822004-06-09 07:59:58 +00002246 if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00002247 // Ok, at this point, we know that we are masking the result of the
2248 // ADD down to exactly one bit. If the constant we are adding has
2249 // no bits set below this bit, then we can eliminate the ADD.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002250 const APInt& AddRHS = cast<ConstantInt>(OpRHS)->getValue();
Misha Brukmanfd939082005-04-21 23:48:37 +00002251
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00002252 // Check to see if any bits below the one bit set in AndRHSV are set.
2253 if ((AddRHS & (AndRHSV-1)) == 0) {
2254 // If not, the only thing that can effect the output of the AND is
2255 // the bit specified by AndRHSV. If that bit is set, the effect of
2256 // the XOR is to toggle the bit. If it is clear, then the ADD has
2257 // no effect.
2258 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
2259 TheAnd.setOperand(0, X);
2260 return &TheAnd;
2261 } else {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00002262 // Pull the XOR out of the AND.
Chris Lattner74381062009-08-30 07:44:24 +00002263 Value *NewAnd = Builder->CreateAnd(X, AndRHS);
Chris Lattner6934a042007-02-11 01:23:03 +00002264 NewAnd->takeName(Op);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002265 return BinaryOperator::CreateXor(NewAnd, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00002266 }
2267 }
2268 }
2269 }
2270 break;
Chris Lattner62a355c2003-09-19 19:05:02 +00002271
2272 case Instruction::Shl: {
2273 // We know that the AND will not produce any of the bits shifted in, so if
2274 // the anded constant includes them, clear them now!
2275 //
Zhou Sheng290bec52007-03-29 08:15:12 +00002276 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00002277 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +00002278 APInt ShlMask(APInt::getHighBitsSet(BitWidth, BitWidth-OpRHSVal));
Chris Lattner4de84762010-01-04 07:02:48 +00002279 ConstantInt *CI = ConstantInt::get(AndRHS->getContext(),
2280 AndRHS->getValue() & ShlMask);
Misha Brukmanfd939082005-04-21 23:48:37 +00002281
Zhou Sheng290bec52007-03-29 08:15:12 +00002282 if (CI->getValue() == ShlMask) {
2283 // Masking out bits that the shift already masks
Chris Lattner0c967662004-09-24 15:21:34 +00002284 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
2285 } else if (CI != AndRHS) { // Reducing bits set in and.
Chris Lattner62a355c2003-09-19 19:05:02 +00002286 TheAnd.setOperand(1, CI);
2287 return &TheAnd;
2288 }
2289 break;
Misha Brukmanfd939082005-04-21 23:48:37 +00002290 }
Chris Lattner4de84762010-01-04 07:02:48 +00002291 case Instruction::LShr: {
Chris Lattner62a355c2003-09-19 19:05:02 +00002292 // We know that the AND will not produce any of the bits shifted in, so if
2293 // the anded constant includes them, clear them now! This only applies to
2294 // unsigned shifts, because a signed shr may bring in set bits!
2295 //
Zhou Sheng290bec52007-03-29 08:15:12 +00002296 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00002297 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +00002298 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
Chris Lattner4de84762010-01-04 07:02:48 +00002299 ConstantInt *CI = ConstantInt::get(Op->getContext(),
2300 AndRHS->getValue() & ShrMask);
Chris Lattner0c967662004-09-24 15:21:34 +00002301
Zhou Sheng290bec52007-03-29 08:15:12 +00002302 if (CI->getValue() == ShrMask) {
2303 // Masking out bits that the shift already masks.
Reid Spencer3822ff52006-11-08 06:47:33 +00002304 return ReplaceInstUsesWith(TheAnd, Op);
2305 } else if (CI != AndRHS) {
2306 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
2307 return &TheAnd;
2308 }
2309 break;
2310 }
2311 case Instruction::AShr:
2312 // Signed shr.
2313 // See if this is shifting in some sign extension, then masking it out
2314 // with an and.
2315 if (Op->hasOneUse()) {
Zhou Sheng290bec52007-03-29 08:15:12 +00002316 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00002317 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +00002318 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
Chris Lattner4de84762010-01-04 07:02:48 +00002319 Constant *C = ConstantInt::get(Op->getContext(),
2320 AndRHS->getValue() & ShrMask);
Reid Spencer7eb76382006-12-13 17:19:09 +00002321 if (C == AndRHS) { // Masking out bits shifted in.
Reid Spencer17212df2006-12-12 09:18:51 +00002322 // (Val ashr C1) & C2 -> (Val lshr C1) & C2
Reid Spencer3822ff52006-11-08 06:47:33 +00002323 // Make the argument unsigned.
2324 Value *ShVal = Op->getOperand(0);
Chris Lattner74381062009-08-30 07:44:24 +00002325 ShVal = Builder->CreateLShr(ShVal, OpRHS, Op->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002326 return BinaryOperator::CreateAnd(ShVal, AndRHS, TheAnd.getName());
Chris Lattner0c967662004-09-24 15:21:34 +00002327 }
Chris Lattner62a355c2003-09-19 19:05:02 +00002328 }
2329 break;
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00002330 }
2331 return 0;
2332}
2333
Chris Lattner8b170942002-08-09 23:47:40 +00002334
Chris Lattnera96879a2004-09-29 17:40:11 +00002335/// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
2336/// true, otherwise (V < Lo || V >= Hi). In pratice, we emit the more efficient
Reid Spencere4d87aa2006-12-23 06:05:41 +00002337/// (V-Lo) <u Hi-Lo. This method expects that Lo <= Hi. isSigned indicates
2338/// whether to treat the V, Lo and HI as signed or not. IB is the location to
Chris Lattnera96879a2004-09-29 17:40:11 +00002339/// insert new instructions.
2340Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
Reid Spencere4d87aa2006-12-23 06:05:41 +00002341 bool isSigned, bool Inside,
2342 Instruction &IB) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00002343 assert(cast<ConstantInt>(ConstantExpr::getICmp((isSigned ?
Reid Spencer579dca12007-01-12 04:24:46 +00002344 ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
Chris Lattnera96879a2004-09-29 17:40:11 +00002345 "Lo is not <= Hi in range emission code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00002346
Chris Lattnera96879a2004-09-29 17:40:11 +00002347 if (Inside) {
2348 if (Lo == Hi) // Trivially false.
Dan Gohman1c8a23c2009-08-25 23:17:54 +00002349 return new ICmpInst(ICmpInst::ICMP_NE, V, V);
Misha Brukmanfd939082005-04-21 23:48:37 +00002350
Reid Spencere4d87aa2006-12-23 06:05:41 +00002351 // V >= Min && V < Hi --> V < Hi
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002352 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
Reid Spencere4e40032007-03-21 23:19:50 +00002353 ICmpInst::Predicate pred = (isSigned ?
Reid Spencere4d87aa2006-12-23 06:05:41 +00002354 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00002355 return new ICmpInst(pred, V, Hi);
Reid Spencere4d87aa2006-12-23 06:05:41 +00002356 }
2357
2358 // Emit V-Lo <u Hi-Lo
Owen Andersonbaf3c402009-07-29 18:55:55 +00002359 Constant *NegLo = ConstantExpr::getNeg(Lo);
Chris Lattner74381062009-08-30 07:44:24 +00002360 Value *Add = Builder->CreateAdd(V, NegLo, V->getName()+".off");
Owen Andersonbaf3c402009-07-29 18:55:55 +00002361 Constant *UpperBound = ConstantExpr::getAdd(NegLo, Hi);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00002362 return new ICmpInst(ICmpInst::ICMP_ULT, Add, UpperBound);
Chris Lattnera96879a2004-09-29 17:40:11 +00002363 }
2364
2365 if (Lo == Hi) // Trivially true.
Dan Gohman1c8a23c2009-08-25 23:17:54 +00002366 return new ICmpInst(ICmpInst::ICMP_EQ, V, V);
Chris Lattnera96879a2004-09-29 17:40:11 +00002367
Reid Spencere4e40032007-03-21 23:19:50 +00002368 // V < Min || V >= Hi -> V > Hi-1
Dan Gohman186a6362009-08-12 16:04:34 +00002369 Hi = SubOne(cast<ConstantInt>(Hi));
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002370 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00002371 ICmpInst::Predicate pred = (isSigned ?
2372 ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00002373 return new ICmpInst(pred, V, Hi);
Reid Spencere4d87aa2006-12-23 06:05:41 +00002374 }
Reid Spencerb83eb642006-10-20 07:07:24 +00002375
Reid Spencere4e40032007-03-21 23:19:50 +00002376 // Emit V-Lo >u Hi-1-Lo
2377 // Note that Hi has already had one subtracted from it, above.
Owen Andersonbaf3c402009-07-29 18:55:55 +00002378 ConstantInt *NegLo = cast<ConstantInt>(ConstantExpr::getNeg(Lo));
Chris Lattner74381062009-08-30 07:44:24 +00002379 Value *Add = Builder->CreateAdd(V, NegLo, V->getName()+".off");
Owen Andersonbaf3c402009-07-29 18:55:55 +00002380 Constant *LowerBound = ConstantExpr::getAdd(NegLo, Hi);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00002381 return new ICmpInst(ICmpInst::ICMP_UGT, Add, LowerBound);
Chris Lattnera96879a2004-09-29 17:40:11 +00002382}
2383
Chris Lattner7203e152005-09-18 07:22:02 +00002384// isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
2385// any number of 0s on either side. The 1s are allowed to wrap from LSB to
2386// MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs. 0x0F0F0000 is
2387// not, since all 1s are not contiguous.
Zhou Sheng4351c642007-04-02 08:20:41 +00002388static bool isRunOfOnes(ConstantInt *Val, uint32_t &MB, uint32_t &ME) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002389 const APInt& V = Val->getValue();
Reid Spencerf2442522007-03-24 00:42:08 +00002390 uint32_t BitWidth = Val->getType()->getBitWidth();
2391 if (!APIntOps::isShiftedMask(BitWidth, V)) return false;
Chris Lattner7203e152005-09-18 07:22:02 +00002392
2393 // look for the first zero bit after the run of ones
Reid Spencerf2442522007-03-24 00:42:08 +00002394 MB = BitWidth - ((V - 1) ^ V).countLeadingZeros();
Chris Lattner7203e152005-09-18 07:22:02 +00002395 // look for the first non-zero bit
Reid Spencerf2442522007-03-24 00:42:08 +00002396 ME = V.getActiveBits();
Chris Lattner7203e152005-09-18 07:22:02 +00002397 return true;
2398}
2399
Chris Lattner7203e152005-09-18 07:22:02 +00002400/// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
2401/// where isSub determines whether the operator is a sub. If we can fold one of
2402/// the following xforms:
Chris Lattnerc8e77562005-09-18 04:24:45 +00002403///
2404/// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
2405/// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
2406/// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
2407///
2408/// return (A +/- B).
2409///
2410Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002411 ConstantInt *Mask, bool isSub,
Chris Lattnerc8e77562005-09-18 04:24:45 +00002412 Instruction &I) {
2413 Instruction *LHSI = dyn_cast<Instruction>(LHS);
2414 if (!LHSI || LHSI->getNumOperands() != 2 ||
2415 !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
2416
2417 ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
2418
2419 switch (LHSI->getOpcode()) {
2420 default: return 0;
2421 case Instruction::And:
Owen Andersonbaf3c402009-07-29 18:55:55 +00002422 if (ConstantExpr::getAnd(N, Mask) == Mask) {
Chris Lattner7203e152005-09-18 07:22:02 +00002423 // If the AndRHS is a power of two minus one (0+1+), this is simple.
Zhou Sheng00f436c2007-03-24 15:34:37 +00002424 if ((Mask->getValue().countLeadingZeros() +
2425 Mask->getValue().countPopulation()) ==
2426 Mask->getValue().getBitWidth())
Chris Lattner7203e152005-09-18 07:22:02 +00002427 break;
2428
2429 // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
2430 // part, we don't need any explicit masks to take them out of A. If that
2431 // is all N is, ignore it.
Zhou Sheng4351c642007-04-02 08:20:41 +00002432 uint32_t MB = 0, ME = 0;
Chris Lattner7203e152005-09-18 07:22:02 +00002433 if (isRunOfOnes(Mask, MB, ME)) { // begin/end bit of run, inclusive
Reid Spencerb35ae032007-03-23 18:46:34 +00002434 uint32_t BitWidth = cast<IntegerType>(RHS->getType())->getBitWidth();
Zhou Sheng290bec52007-03-29 08:15:12 +00002435 APInt Mask(APInt::getLowBitsSet(BitWidth, MB-1));
Chris Lattner3bedbd92006-02-07 07:27:52 +00002436 if (MaskedValueIsZero(RHS, Mask))
Chris Lattner7203e152005-09-18 07:22:02 +00002437 break;
2438 }
2439 }
Chris Lattnerc8e77562005-09-18 04:24:45 +00002440 return 0;
2441 case Instruction::Or:
2442 case Instruction::Xor:
Chris Lattner7203e152005-09-18 07:22:02 +00002443 // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
Zhou Sheng00f436c2007-03-24 15:34:37 +00002444 if ((Mask->getValue().countLeadingZeros() +
2445 Mask->getValue().countPopulation()) == Mask->getValue().getBitWidth()
Owen Andersonbaf3c402009-07-29 18:55:55 +00002446 && ConstantExpr::getAnd(N, Mask)->isNullValue())
Chris Lattnerc8e77562005-09-18 04:24:45 +00002447 break;
2448 return 0;
2449 }
2450
Chris Lattnerc8e77562005-09-18 04:24:45 +00002451 if (isSub)
Chris Lattner74381062009-08-30 07:44:24 +00002452 return Builder->CreateSub(LHSI->getOperand(0), RHS, "fold");
2453 return Builder->CreateAdd(LHSI->getOperand(0), RHS, "fold");
Chris Lattnerc8e77562005-09-18 04:24:45 +00002454}
2455
Chris Lattner29cd5ba2008-11-16 05:06:21 +00002456/// FoldAndOfICmps - Fold (icmp)&(icmp) if possible.
2457Instruction *InstCombiner::FoldAndOfICmps(Instruction &I,
2458 ICmpInst *LHS, ICmpInst *RHS) {
Chris Lattnerea065fb2008-11-16 05:10:52 +00002459 Value *Val, *Val2;
Chris Lattner29cd5ba2008-11-16 05:06:21 +00002460 ConstantInt *LHSCst, *RHSCst;
2461 ICmpInst::Predicate LHSCC, RHSCC;
2462
Chris Lattnerea065fb2008-11-16 05:10:52 +00002463 // This only handles icmp of constants: (icmp1 A, C1) & (icmp2 B, C2).
Owen Andersonc7d2ce72009-07-10 17:35:01 +00002464 if (!match(LHS, m_ICmp(LHSCC, m_Value(Val),
Dan Gohman4ae51262009-08-12 16:23:25 +00002465 m_ConstantInt(LHSCst))) ||
Owen Andersonc7d2ce72009-07-10 17:35:01 +00002466 !match(RHS, m_ICmp(RHSCC, m_Value(Val2),
Dan Gohman4ae51262009-08-12 16:23:25 +00002467 m_ConstantInt(RHSCst))))
Chris Lattner29cd5ba2008-11-16 05:06:21 +00002468 return 0;
Chris Lattnerea065fb2008-11-16 05:10:52 +00002469
Chris Lattner3f40e232009-11-29 00:51:17 +00002470 if (LHSCst == RHSCst && LHSCC == RHSCC) {
2471 // (icmp ult A, C) & (icmp ult B, C) --> (icmp ult (A|B), C)
2472 // where C is a power of 2
2473 if (LHSCC == ICmpInst::ICMP_ULT &&
2474 LHSCst->getValue().isPowerOf2()) {
2475 Value *NewOr = Builder->CreateOr(Val, Val2);
2476 return new ICmpInst(LHSCC, NewOr, LHSCst);
2477 }
2478
2479 // (icmp eq A, 0) & (icmp eq B, 0) --> (icmp eq (A|B), 0)
2480 if (LHSCC == ICmpInst::ICMP_EQ && LHSCst->isZero()) {
2481 Value *NewOr = Builder->CreateOr(Val, Val2);
2482 return new ICmpInst(LHSCC, NewOr, LHSCst);
2483 }
Chris Lattnerea065fb2008-11-16 05:10:52 +00002484 }
2485
2486 // From here on, we only handle:
2487 // (icmp1 A, C1) & (icmp2 A, C2) --> something simpler.
2488 if (Val != Val2) return 0;
2489
Chris Lattner29cd5ba2008-11-16 05:06:21 +00002490 // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
2491 if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
2492 RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
2493 LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
2494 RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
2495 return 0;
2496
2497 // We can't fold (ugt x, C) & (sgt x, C2).
2498 if (!PredicatesFoldable(LHSCC, RHSCC))
2499 return 0;
2500
2501 // Ensure that the larger constant is on the RHS.
Chris Lattneraa3e1572008-11-16 05:14:43 +00002502 bool ShouldSwap;
Nick Lewycky4a134af2009-10-25 05:20:17 +00002503 if (CmpInst::isSigned(LHSCC) ||
Chris Lattner29cd5ba2008-11-16 05:06:21 +00002504 (ICmpInst::isEquality(LHSCC) &&
Nick Lewycky4a134af2009-10-25 05:20:17 +00002505 CmpInst::isSigned(RHSCC)))
Chris Lattneraa3e1572008-11-16 05:14:43 +00002506 ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
Chris Lattner29cd5ba2008-11-16 05:06:21 +00002507 else
Chris Lattneraa3e1572008-11-16 05:14:43 +00002508 ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
2509
2510 if (ShouldSwap) {
Chris Lattner29cd5ba2008-11-16 05:06:21 +00002511 std::swap(LHS, RHS);
2512 std::swap(LHSCst, RHSCst);
2513 std::swap(LHSCC, RHSCC);
2514 }
2515
2516 // At this point, we know we have have two icmp instructions
2517 // comparing a value against two constants and and'ing the result
2518 // together. Because of the above check, we know that we only have
2519 // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know
2520 // (from the FoldICmpLogical check above), that the two constants
2521 // are not equal and that the larger constant is on the RHS
2522 assert(LHSCst != RHSCst && "Compares not folded above?");
2523
2524 switch (LHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00002525 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00002526 case ICmpInst::ICMP_EQ:
2527 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00002528 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00002529 case ICmpInst::ICMP_EQ: // (X == 13 & X == 15) -> false
2530 case ICmpInst::ICMP_UGT: // (X == 13 & X > 15) -> false
2531 case ICmpInst::ICMP_SGT: // (X == 13 & X > 15) -> false
Chris Lattner4de84762010-01-04 07:02:48 +00002532 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getContext()));
Chris Lattner29cd5ba2008-11-16 05:06:21 +00002533 case ICmpInst::ICMP_NE: // (X == 13 & X != 15) -> X == 13
2534 case ICmpInst::ICMP_ULT: // (X == 13 & X < 15) -> X == 13
2535 case ICmpInst::ICMP_SLT: // (X == 13 & X < 15) -> X == 13
2536 return ReplaceInstUsesWith(I, LHS);
2537 }
2538 case ICmpInst::ICMP_NE:
2539 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00002540 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00002541 case ICmpInst::ICMP_ULT:
Dan Gohman186a6362009-08-12 16:04:34 +00002542 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X u< 14) -> X < 13
Dan Gohman1c8a23c2009-08-25 23:17:54 +00002543 return new ICmpInst(ICmpInst::ICMP_ULT, Val, LHSCst);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00002544 break; // (X != 13 & X u< 15) -> no change
2545 case ICmpInst::ICMP_SLT:
Dan Gohman186a6362009-08-12 16:04:34 +00002546 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X s< 14) -> X < 13
Dan Gohman1c8a23c2009-08-25 23:17:54 +00002547 return new ICmpInst(ICmpInst::ICMP_SLT, Val, LHSCst);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00002548 break; // (X != 13 & X s< 15) -> no change
2549 case ICmpInst::ICMP_EQ: // (X != 13 & X == 15) -> X == 15
2550 case ICmpInst::ICMP_UGT: // (X != 13 & X u> 15) -> X u> 15
2551 case ICmpInst::ICMP_SGT: // (X != 13 & X s> 15) -> X s> 15
2552 return ReplaceInstUsesWith(I, RHS);
2553 case ICmpInst::ICMP_NE:
Dan Gohman186a6362009-08-12 16:04:34 +00002554 if (LHSCst == SubOne(RHSCst)){// (X != 13 & X != 14) -> X-13 >u 1
Owen Andersonbaf3c402009-07-29 18:55:55 +00002555 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
Chris Lattner74381062009-08-30 07:44:24 +00002556 Value *Add = Builder->CreateAdd(Val, AddCST, Val->getName()+".off");
Dan Gohman1c8a23c2009-08-25 23:17:54 +00002557 return new ICmpInst(ICmpInst::ICMP_UGT, Add,
Owen Andersoneed707b2009-07-24 23:12:02 +00002558 ConstantInt::get(Add->getType(), 1));
Chris Lattner29cd5ba2008-11-16 05:06:21 +00002559 }
2560 break; // (X != 13 & X != 15) -> no change
2561 }
2562 break;
2563 case ICmpInst::ICMP_ULT:
2564 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00002565 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00002566 case ICmpInst::ICMP_EQ: // (X u< 13 & X == 15) -> false
2567 case ICmpInst::ICMP_UGT: // (X u< 13 & X u> 15) -> false
Chris Lattner4de84762010-01-04 07:02:48 +00002568 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getContext()));
Chris Lattner29cd5ba2008-11-16 05:06:21 +00002569 case ICmpInst::ICMP_SGT: // (X u< 13 & X s> 15) -> no change
2570 break;
2571 case ICmpInst::ICMP_NE: // (X u< 13 & X != 15) -> X u< 13
2572 case ICmpInst::ICMP_ULT: // (X u< 13 & X u< 15) -> X u< 13
2573 return ReplaceInstUsesWith(I, LHS);
2574 case ICmpInst::ICMP_SLT: // (X u< 13 & X s< 15) -> no change
2575 break;
2576 }
2577 break;
2578 case ICmpInst::ICMP_SLT:
2579 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00002580 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00002581 case ICmpInst::ICMP_EQ: // (X s< 13 & X == 15) -> false
2582 case ICmpInst::ICMP_SGT: // (X s< 13 & X s> 15) -> false
Chris Lattner4de84762010-01-04 07:02:48 +00002583 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getContext()));
Chris Lattner29cd5ba2008-11-16 05:06:21 +00002584 case ICmpInst::ICMP_UGT: // (X s< 13 & X u> 15) -> no change
2585 break;
2586 case ICmpInst::ICMP_NE: // (X s< 13 & X != 15) -> X < 13
2587 case ICmpInst::ICMP_SLT: // (X s< 13 & X s< 15) -> X < 13
2588 return ReplaceInstUsesWith(I, LHS);
2589 case ICmpInst::ICMP_ULT: // (X s< 13 & X u< 15) -> no change
2590 break;
2591 }
2592 break;
2593 case ICmpInst::ICMP_UGT:
2594 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00002595 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00002596 case ICmpInst::ICMP_EQ: // (X u> 13 & X == 15) -> X == 15
2597 case ICmpInst::ICMP_UGT: // (X u> 13 & X u> 15) -> X u> 15
2598 return ReplaceInstUsesWith(I, RHS);
2599 case ICmpInst::ICMP_SGT: // (X u> 13 & X s> 15) -> no change
2600 break;
2601 case ICmpInst::ICMP_NE:
Dan Gohman186a6362009-08-12 16:04:34 +00002602 if (RHSCst == AddOne(LHSCst)) // (X u> 13 & X != 14) -> X u> 14
Dan Gohman1c8a23c2009-08-25 23:17:54 +00002603 return new ICmpInst(LHSCC, Val, RHSCst);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00002604 break; // (X u> 13 & X != 15) -> no change
Chris Lattner69d4ced2008-11-16 05:20:07 +00002605 case ICmpInst::ICMP_ULT: // (X u> 13 & X u< 15) -> (X-14) <u 1
Dan Gohman186a6362009-08-12 16:04:34 +00002606 return InsertRangeTest(Val, AddOne(LHSCst),
Owen Andersond672ecb2009-07-03 00:17:18 +00002607 RHSCst, false, true, I);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00002608 case ICmpInst::ICMP_SLT: // (X u> 13 & X s< 15) -> no change
2609 break;
2610 }
2611 break;
2612 case ICmpInst::ICMP_SGT:
2613 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00002614 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00002615 case ICmpInst::ICMP_EQ: // (X s> 13 & X == 15) -> X == 15
2616 case ICmpInst::ICMP_SGT: // (X s> 13 & X s> 15) -> X s> 15
2617 return ReplaceInstUsesWith(I, RHS);
2618 case ICmpInst::ICMP_UGT: // (X s> 13 & X u> 15) -> no change
2619 break;
2620 case ICmpInst::ICMP_NE:
Dan Gohman186a6362009-08-12 16:04:34 +00002621 if (RHSCst == AddOne(LHSCst)) // (X s> 13 & X != 14) -> X s> 14
Dan Gohman1c8a23c2009-08-25 23:17:54 +00002622 return new ICmpInst(LHSCC, Val, RHSCst);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00002623 break; // (X s> 13 & X != 15) -> no change
Chris Lattner69d4ced2008-11-16 05:20:07 +00002624 case ICmpInst::ICMP_SLT: // (X s> 13 & X s< 15) -> (X-14) s< 1
Dan Gohman186a6362009-08-12 16:04:34 +00002625 return InsertRangeTest(Val, AddOne(LHSCst),
Owen Andersond672ecb2009-07-03 00:17:18 +00002626 RHSCst, true, true, I);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00002627 case ICmpInst::ICMP_ULT: // (X s> 13 & X u< 15) -> no change
2628 break;
2629 }
2630 break;
2631 }
Chris Lattner29cd5ba2008-11-16 05:06:21 +00002632
2633 return 0;
2634}
2635
Chris Lattner42d1be02009-07-23 05:14:02 +00002636Instruction *InstCombiner::FoldAndOfFCmps(Instruction &I, FCmpInst *LHS,
2637 FCmpInst *RHS) {
2638
2639 if (LHS->getPredicate() == FCmpInst::FCMP_ORD &&
2640 RHS->getPredicate() == FCmpInst::FCMP_ORD) {
2641 // (fcmp ord x, c) & (fcmp ord y, c) -> (fcmp ord x, y)
2642 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
2643 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
2644 // If either of the constants are nans, then the whole thing returns
2645 // false.
2646 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Chris Lattner4de84762010-01-04 07:02:48 +00002647 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getContext()));
Dan Gohman1c8a23c2009-08-25 23:17:54 +00002648 return new FCmpInst(FCmpInst::FCMP_ORD,
Chris Lattner42d1be02009-07-23 05:14:02 +00002649 LHS->getOperand(0), RHS->getOperand(0));
2650 }
Chris Lattnerf98d2532009-07-23 05:32:17 +00002651
2652 // Handle vector zeros. This occurs because the canonical form of
2653 // "fcmp ord x,x" is "fcmp ord x, 0".
2654 if (isa<ConstantAggregateZero>(LHS->getOperand(1)) &&
2655 isa<ConstantAggregateZero>(RHS->getOperand(1)))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00002656 return new FCmpInst(FCmpInst::FCMP_ORD,
Chris Lattnerf98d2532009-07-23 05:32:17 +00002657 LHS->getOperand(0), RHS->getOperand(0));
Chris Lattner42d1be02009-07-23 05:14:02 +00002658 return 0;
2659 }
2660
2661 Value *Op0LHS = LHS->getOperand(0), *Op0RHS = LHS->getOperand(1);
2662 Value *Op1LHS = RHS->getOperand(0), *Op1RHS = RHS->getOperand(1);
2663 FCmpInst::Predicate Op0CC = LHS->getPredicate(), Op1CC = RHS->getPredicate();
2664
2665
2666 if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
2667 // Swap RHS operands to match LHS.
2668 Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
2669 std::swap(Op1LHS, Op1RHS);
2670 }
2671
2672 if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
2673 // Simplify (fcmp cc0 x, y) & (fcmp cc1 x, y).
2674 if (Op0CC == Op1CC)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00002675 return new FCmpInst((FCmpInst::Predicate)Op0CC, Op0LHS, Op0RHS);
Chris Lattner42d1be02009-07-23 05:14:02 +00002676
2677 if (Op0CC == FCmpInst::FCMP_FALSE || Op1CC == FCmpInst::FCMP_FALSE)
Chris Lattner4de84762010-01-04 07:02:48 +00002678 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getContext()));
Chris Lattner42d1be02009-07-23 05:14:02 +00002679 if (Op0CC == FCmpInst::FCMP_TRUE)
2680 return ReplaceInstUsesWith(I, RHS);
2681 if (Op1CC == FCmpInst::FCMP_TRUE)
2682 return ReplaceInstUsesWith(I, LHS);
2683
2684 bool Op0Ordered;
2685 bool Op1Ordered;
2686 unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
2687 unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
2688 if (Op1Pred == 0) {
2689 std::swap(LHS, RHS);
2690 std::swap(Op0Pred, Op1Pred);
2691 std::swap(Op0Ordered, Op1Ordered);
2692 }
2693 if (Op0Pred == 0) {
2694 // uno && ueq -> uno && (uno || eq) -> ueq
2695 // ord && olt -> ord && (ord && lt) -> olt
2696 if (Op0Ordered == Op1Ordered)
2697 return ReplaceInstUsesWith(I, RHS);
2698
2699 // uno && oeq -> uno && (ord && eq) -> false
2700 // uno && ord -> false
2701 if (!Op0Ordered)
Chris Lattner4de84762010-01-04 07:02:48 +00002702 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getContext()));
Chris Lattner42d1be02009-07-23 05:14:02 +00002703 // ord && ueq -> ord && (uno || eq) -> oeq
Chris Lattner4de84762010-01-04 07:02:48 +00002704 return cast<Instruction>(getFCmpValue(true, Op1Pred, Op0LHS, Op0RHS));
Chris Lattner42d1be02009-07-23 05:14:02 +00002705 }
2706 }
2707
2708 return 0;
2709}
2710
Chris Lattner29cd5ba2008-11-16 05:06:21 +00002711
Chris Lattner7e708292002-06-25 16:13:24 +00002712Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00002713 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00002714 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00002715
Chris Lattnerd06094f2009-11-10 00:55:12 +00002716 if (Value *V = SimplifyAndInst(Op0, Op1, TD))
2717 return ReplaceInstUsesWith(I, V);
Chris Lattner3f5b8772002-05-06 16:14:14 +00002718
Chris Lattnerf8c36f52006-02-12 08:02:11 +00002719 // See if we can simplify any instructions used by the instruction whose sole
Chris Lattner9ca96412006-02-08 03:25:32 +00002720 // purpose is to compute bits we don't care about.
Dan Gohman6de29f82009-06-15 22:12:54 +00002721 if (SimplifyDemandedInstructionBits(I))
Nick Lewycky546d6312010-01-02 15:25:44 +00002722 return &I;
Dan Gohman6de29f82009-06-15 22:12:54 +00002723
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002724 if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner7acdf1d2009-10-11 22:00:32 +00002725 const APInt &AndRHSMask = AndRHS->getValue();
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002726 APInt NotAndRHS(~AndRHSMask);
Chris Lattner6e7ba452005-01-01 16:22:27 +00002727
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00002728 // Optimize a variety of ((val OP C1) & C2) combinations...
Chris Lattner7acdf1d2009-10-11 22:00:32 +00002729 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Chris Lattner6e7ba452005-01-01 16:22:27 +00002730 Value *Op0LHS = Op0I->getOperand(0);
2731 Value *Op0RHS = Op0I->getOperand(1);
2732 switch (Op0I->getOpcode()) {
Chris Lattner7acdf1d2009-10-11 22:00:32 +00002733 default: break;
Chris Lattner6e7ba452005-01-01 16:22:27 +00002734 case Instruction::Xor:
2735 case Instruction::Or:
Chris Lattnerad1e3022005-01-23 20:26:55 +00002736 // If the mask is only needed on one incoming arm, push it up.
Chris Lattner7acdf1d2009-10-11 22:00:32 +00002737 if (!Op0I->hasOneUse()) break;
2738
2739 if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
2740 // Not masking anything out for the LHS, move to RHS.
2741 Value *NewRHS = Builder->CreateAnd(Op0RHS, AndRHS,
2742 Op0RHS->getName()+".masked");
2743 return BinaryOperator::Create(Op0I->getOpcode(), Op0LHS, NewRHS);
2744 }
2745 if (!isa<Constant>(Op0RHS) &&
2746 MaskedValueIsZero(Op0RHS, NotAndRHS)) {
2747 // Not masking anything out for the RHS, move to LHS.
2748 Value *NewLHS = Builder->CreateAnd(Op0LHS, AndRHS,
2749 Op0LHS->getName()+".masked");
2750 return BinaryOperator::Create(Op0I->getOpcode(), NewLHS, Op0RHS);
Chris Lattnerad1e3022005-01-23 20:26:55 +00002751 }
2752
Chris Lattner6e7ba452005-01-01 16:22:27 +00002753 break;
Chris Lattnerc8e77562005-09-18 04:24:45 +00002754 case Instruction::Add:
Chris Lattner7203e152005-09-18 07:22:02 +00002755 // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
2756 // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
2757 // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
2758 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002759 return BinaryOperator::CreateAnd(V, AndRHS);
Chris Lattner7203e152005-09-18 07:22:02 +00002760 if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002761 return BinaryOperator::CreateAnd(V, AndRHS); // Add commutes
Chris Lattnerc8e77562005-09-18 04:24:45 +00002762 break;
2763
2764 case Instruction::Sub:
Chris Lattner7203e152005-09-18 07:22:02 +00002765 // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
2766 // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
2767 // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
2768 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002769 return BinaryOperator::CreateAnd(V, AndRHS);
Nick Lewyckyb4d1bc92008-07-09 04:32:37 +00002770
Nick Lewycky5dcc41f2008-07-10 05:51:40 +00002771 // (A - N) & AndRHS -> -N & AndRHS iff A&AndRHS==0 and AndRHS
2772 // has 1's for all bits that the subtraction with A might affect.
2773 if (Op0I->hasOneUse()) {
2774 uint32_t BitWidth = AndRHSMask.getBitWidth();
2775 uint32_t Zeros = AndRHSMask.countLeadingZeros();
2776 APInt Mask = APInt::getLowBitsSet(BitWidth, BitWidth - Zeros);
2777
Nick Lewyckyb4d1bc92008-07-09 04:32:37 +00002778 ConstantInt *A = dyn_cast<ConstantInt>(Op0LHS);
Nick Lewycky5dcc41f2008-07-10 05:51:40 +00002779 if (!(A && A->isZero()) && // avoid infinite recursion.
2780 MaskedValueIsZero(Op0LHS, Mask)) {
Chris Lattner74381062009-08-30 07:44:24 +00002781 Value *NewNeg = Builder->CreateNeg(Op0RHS);
Nick Lewyckyb4d1bc92008-07-09 04:32:37 +00002782 return BinaryOperator::CreateAnd(NewNeg, AndRHS);
2783 }
2784 }
Chris Lattnerc8e77562005-09-18 04:24:45 +00002785 break;
Nick Lewyckyd1f77bf2008-07-09 05:20:13 +00002786
2787 case Instruction::Shl:
2788 case Instruction::LShr:
2789 // (1 << x) & 1 --> zext(x == 0)
2790 // (1 >> x) & 1 --> zext(x == 0)
Nick Lewyckyd8ad4922008-07-09 07:35:26 +00002791 if (AndRHSMask == 1 && Op0LHS == AndRHS) {
Chris Lattner74381062009-08-30 07:44:24 +00002792 Value *NewICmp =
2793 Builder->CreateICmpEQ(Op0RHS, Constant::getNullValue(I.getType()));
Nick Lewyckyd1f77bf2008-07-09 05:20:13 +00002794 return new ZExtInst(NewICmp, I.getType());
2795 }
2796 break;
Chris Lattner6e7ba452005-01-01 16:22:27 +00002797 }
2798
Chris Lattner58403262003-07-23 19:25:52 +00002799 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002800 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00002801 return Res;
Chris Lattner6e7ba452005-01-01 16:22:27 +00002802 } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
Chris Lattner2b83af22005-08-07 07:03:10 +00002803 // If this is an integer truncation or change from signed-to-unsigned, and
2804 // if the source is an and/or with immediate, transform it. This
2805 // frequently occurs for bitfield accesses.
2806 if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
Reid Spencer3da59db2006-11-27 01:05:10 +00002807 if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
Chris Lattner2b83af22005-08-07 07:03:10 +00002808 CastOp->getNumOperands() == 2)
Chris Lattner48b59ec2009-10-26 15:40:07 +00002809 if (ConstantInt *AndCI =dyn_cast<ConstantInt>(CastOp->getOperand(1))){
Chris Lattner2b83af22005-08-07 07:03:10 +00002810 if (CastOp->getOpcode() == Instruction::And) {
2811 // Change: and (cast (and X, C1) to T), C2
Reid Spencer3da59db2006-11-27 01:05:10 +00002812 // into : and (cast X to T), trunc_or_bitcast(C1)&C2
2813 // This will fold the two constants together, which may allow
2814 // other simplifications.
Chris Lattner74381062009-08-30 07:44:24 +00002815 Value *NewCast = Builder->CreateTruncOrBitCast(
Reid Spencerd977d862006-12-12 23:36:14 +00002816 CastOp->getOperand(0), I.getType(),
2817 CastOp->getName()+".shrunk");
Reid Spencer3da59db2006-11-27 01:05:10 +00002818 // trunc_or_bitcast(C1)&C2
Chris Lattner74381062009-08-30 07:44:24 +00002819 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
Owen Andersonbaf3c402009-07-29 18:55:55 +00002820 C3 = ConstantExpr::getAnd(C3, AndRHS);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002821 return BinaryOperator::CreateAnd(NewCast, C3);
Chris Lattner2b83af22005-08-07 07:03:10 +00002822 } else if (CastOp->getOpcode() == Instruction::Or) {
2823 // Change: and (cast (or X, C1) to T), C2
2824 // into : trunc(C1)&C2 iff trunc(C1)&C2 == C2
Chris Lattner74381062009-08-30 07:44:24 +00002825 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
Owen Andersonbaf3c402009-07-29 18:55:55 +00002826 if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS)
Owen Andersond672ecb2009-07-03 00:17:18 +00002827 // trunc(C1)&C2
Chris Lattner2b83af22005-08-07 07:03:10 +00002828 return ReplaceInstUsesWith(I, AndRHS);
2829 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00002830 }
Chris Lattner2b83af22005-08-07 07:03:10 +00002831 }
Chris Lattner06782f82003-07-23 19:36:21 +00002832 }
Chris Lattner2eefe512004-04-09 19:05:30 +00002833
2834 // Try to fold constant and into select arguments.
2835 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner80f43d32010-01-04 07:53:58 +00002836 if (Instruction *R = FoldOpIntoSelect(I, SI))
Chris Lattner2eefe512004-04-09 19:05:30 +00002837 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00002838 if (isa<PHINode>(Op0))
2839 if (Instruction *NV = FoldOpIntoPhi(I))
2840 return NV;
Chris Lattnerc6a8aff2003-07-23 17:57:01 +00002841 }
2842
Chris Lattner5b62aa72004-06-18 06:07:51 +00002843
Misha Brukmancb6267b2004-07-30 12:50:08 +00002844 // (~A & ~B) == (~(A | B)) - De Morgan's Law
Chris Lattnerd06094f2009-11-10 00:55:12 +00002845 if (Value *Op0NotVal = dyn_castNotVal(Op0))
2846 if (Value *Op1NotVal = dyn_castNotVal(Op1))
2847 if (Op0->hasOneUse() && Op1->hasOneUse()) {
2848 Value *Or = Builder->CreateOr(Op0NotVal, Op1NotVal,
2849 I.getName()+".demorgan");
2850 return BinaryOperator::CreateNot(Or);
2851 }
2852
Chris Lattner2082ad92006-02-13 23:07:23 +00002853 {
Chris Lattner003b6202007-06-15 05:58:24 +00002854 Value *A = 0, *B = 0, *C = 0, *D = 0;
Chris Lattnerd06094f2009-11-10 00:55:12 +00002855 // (A|B) & ~(A&B) -> A^B
2856 if (match(Op0, m_Or(m_Value(A), m_Value(B))) &&
2857 match(Op1, m_Not(m_And(m_Value(C), m_Value(D)))) &&
2858 ((A == C && B == D) || (A == D && B == C)))
2859 return BinaryOperator::CreateXor(A, B);
Chris Lattner003b6202007-06-15 05:58:24 +00002860
Chris Lattnerd06094f2009-11-10 00:55:12 +00002861 // ~(A&B) & (A|B) -> A^B
2862 if (match(Op1, m_Or(m_Value(A), m_Value(B))) &&
2863 match(Op0, m_Not(m_And(m_Value(C), m_Value(D)))) &&
2864 ((A == C && B == D) || (A == D && B == C)))
2865 return BinaryOperator::CreateXor(A, B);
Chris Lattner64daab52006-04-01 08:03:55 +00002866
2867 if (Op0->hasOneUse() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00002868 match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
Chris Lattner64daab52006-04-01 08:03:55 +00002869 if (A == Op1) { // (A^B)&A -> A&(A^B)
2870 I.swapOperands(); // Simplify below
2871 std::swap(Op0, Op1);
2872 } else if (B == Op1) { // (A^B)&B -> B&(B^A)
2873 cast<BinaryOperator>(Op0)->swapOperands();
2874 I.swapOperands(); // Simplify below
2875 std::swap(Op0, Op1);
2876 }
2877 }
Bill Wendling7f0ef6b2008-11-30 13:08:13 +00002878
Chris Lattner64daab52006-04-01 08:03:55 +00002879 if (Op1->hasOneUse() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00002880 match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
Chris Lattner64daab52006-04-01 08:03:55 +00002881 if (B == Op0) { // B&(A^B) -> B&(B^A)
2882 cast<BinaryOperator>(Op1)->swapOperands();
2883 std::swap(A, B);
2884 }
Chris Lattner74381062009-08-30 07:44:24 +00002885 if (A == Op0) // A&(A^B) -> A & ~B
2886 return BinaryOperator::CreateAnd(A, Builder->CreateNot(B, "tmp"));
Chris Lattner64daab52006-04-01 08:03:55 +00002887 }
Bill Wendling7f0ef6b2008-11-30 13:08:13 +00002888
2889 // (A&((~A)|B)) -> A&B
Dan Gohman4ae51262009-08-12 16:23:25 +00002890 if (match(Op0, m_Or(m_Not(m_Specific(Op1)), m_Value(A))) ||
2891 match(Op0, m_Or(m_Value(A), m_Not(m_Specific(Op1)))))
Chris Lattnerd8aafcb2008-12-01 05:16:26 +00002892 return BinaryOperator::CreateAnd(A, Op1);
Dan Gohman4ae51262009-08-12 16:23:25 +00002893 if (match(Op1, m_Or(m_Not(m_Specific(Op0)), m_Value(A))) ||
2894 match(Op1, m_Or(m_Value(A), m_Not(m_Specific(Op0)))))
Chris Lattnerd8aafcb2008-12-01 05:16:26 +00002895 return BinaryOperator::CreateAnd(A, Op0);
Chris Lattner2082ad92006-02-13 23:07:23 +00002896 }
2897
Reid Spencere4d87aa2006-12-23 06:05:41 +00002898 if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1)) {
2899 // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
Dan Gohman186a6362009-08-12 16:04:34 +00002900 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00002901 return R;
2902
Chris Lattner29cd5ba2008-11-16 05:06:21 +00002903 if (ICmpInst *LHS = dyn_cast<ICmpInst>(Op0))
2904 if (Instruction *Res = FoldAndOfICmps(I, LHS, RHS))
2905 return Res;
Chris Lattner955f3312004-09-28 21:48:02 +00002906 }
2907
Chris Lattner6fc205f2006-05-05 06:39:07 +00002908 // fold (and (cast A), (cast B)) -> (cast (and A, B))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00002909 if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
2910 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
2911 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind ?
2912 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattnerf98d2532009-07-23 05:32:17 +00002913 if (SrcTy == Op1C->getOperand(0)->getType() &&
2914 SrcTy->isIntOrIntVector() &&
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00002915 // Only do this if the casts both really cause code to be generated.
Chris Lattner80f43d32010-01-04 07:53:58 +00002916 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
2917 I.getType()) &&
Reid Spencere4d87aa2006-12-23 06:05:41 +00002918 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
Chris Lattner80f43d32010-01-04 07:53:58 +00002919 I.getType())) {
Chris Lattner74381062009-08-30 07:44:24 +00002920 Value *NewOp = Builder->CreateAnd(Op0C->getOperand(0),
2921 Op1C->getOperand(0), I.getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002922 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00002923 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00002924 }
Chris Lattnere511b742006-11-14 07:46:50 +00002925
2926 // (X >> Z) & (Y >> Z) -> (X&Y) >> Z for all shifts.
Reid Spencer832254e2007-02-02 02:16:23 +00002927 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
2928 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
2929 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
Chris Lattnere511b742006-11-14 07:46:50 +00002930 SI0->getOperand(1) == SI1->getOperand(1) &&
2931 (SI0->hasOneUse() || SI1->hasOneUse())) {
Chris Lattner74381062009-08-30 07:44:24 +00002932 Value *NewOp =
2933 Builder->CreateAnd(SI0->getOperand(0), SI1->getOperand(0),
2934 SI0->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002935 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
Reid Spencer832254e2007-02-02 02:16:23 +00002936 SI1->getOperand(1));
Chris Lattnere511b742006-11-14 07:46:50 +00002937 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00002938 }
2939
Evan Cheng8db90722008-10-14 17:15:11 +00002940 // If and'ing two fcmp, try combine them into one.
Chris Lattner99c65742007-10-24 05:38:08 +00002941 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
Chris Lattner42d1be02009-07-23 05:14:02 +00002942 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
2943 if (Instruction *Res = FoldAndOfFCmps(I, LHS, RHS))
2944 return Res;
Chris Lattner99c65742007-10-24 05:38:08 +00002945 }
Nick Lewyckyb4d1bc92008-07-09 04:32:37 +00002946
Chris Lattner7e708292002-06-25 16:13:24 +00002947 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00002948}
2949
Chris Lattner8c34cd22008-10-05 02:13:19 +00002950/// CollectBSwapParts - Analyze the specified subexpression and see if it is
2951/// capable of providing pieces of a bswap. The subexpression provides pieces
2952/// of a bswap if it is proven that each of the non-zero bytes in the output of
2953/// the expression came from the corresponding "byte swapped" byte in some other
2954/// value. For example, if the current subexpression is "(shl i32 %X, 24)" then
2955/// we know that the expression deposits the low byte of %X into the high byte
2956/// of the bswap result and that all other bytes are zero. This expression is
2957/// accepted, the high byte of ByteValues is set to X to indicate a correct
2958/// match.
2959///
2960/// This function returns true if the match was unsuccessful and false if so.
2961/// On entry to the function the "OverallLeftShift" is a signed integer value
2962/// indicating the number of bytes that the subexpression is later shifted. For
2963/// example, if the expression is later right shifted by 16 bits, the
2964/// OverallLeftShift value would be -2 on entry. This is used to specify which
2965/// byte of ByteValues is actually being set.
2966///
2967/// Similarly, ByteMask is a bitmask where a bit is clear if its corresponding
2968/// byte is masked to zero by a user. For example, in (X & 255), X will be
2969/// processed with a bytemask of 1. Because bytemask is 32-bits, this limits
2970/// this function to working on up to 32-byte (256 bit) values. ByteMask is
2971/// always in the local (OverallLeftShift) coordinate space.
2972///
2973static bool CollectBSwapParts(Value *V, int OverallLeftShift, uint32_t ByteMask,
2974 SmallVector<Value*, 8> &ByteValues) {
2975 if (Instruction *I = dyn_cast<Instruction>(V)) {
2976 // If this is an or instruction, it may be an inner node of the bswap.
2977 if (I->getOpcode() == Instruction::Or) {
2978 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
2979 ByteValues) ||
2980 CollectBSwapParts(I->getOperand(1), OverallLeftShift, ByteMask,
2981 ByteValues);
Chris Lattnerafe91a52006-06-15 19:07:26 +00002982 }
Chris Lattner8c34cd22008-10-05 02:13:19 +00002983
2984 // If this is a logical shift by a constant multiple of 8, recurse with
2985 // OverallLeftShift and ByteMask adjusted.
2986 if (I->isLogicalShift() && isa<ConstantInt>(I->getOperand(1))) {
2987 unsigned ShAmt =
2988 cast<ConstantInt>(I->getOperand(1))->getLimitedValue(~0U);
2989 // Ensure the shift amount is defined and of a byte value.
2990 if ((ShAmt & 7) || (ShAmt > 8*ByteValues.size()))
2991 return true;
2992
2993 unsigned ByteShift = ShAmt >> 3;
2994 if (I->getOpcode() == Instruction::Shl) {
2995 // X << 2 -> collect(X, +2)
2996 OverallLeftShift += ByteShift;
2997 ByteMask >>= ByteShift;
2998 } else {
2999 // X >>u 2 -> collect(X, -2)
3000 OverallLeftShift -= ByteShift;
3001 ByteMask <<= ByteShift;
Chris Lattnerde17ddc2008-10-08 06:42:28 +00003002 ByteMask &= (~0U >> (32-ByteValues.size()));
Chris Lattner8c34cd22008-10-05 02:13:19 +00003003 }
3004
3005 if (OverallLeftShift >= (int)ByteValues.size()) return true;
3006 if (OverallLeftShift <= -(int)ByteValues.size()) return true;
3007
3008 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
3009 ByteValues);
3010 }
3011
3012 // If this is a logical 'and' with a mask that clears bytes, clear the
3013 // corresponding bytes in ByteMask.
3014 if (I->getOpcode() == Instruction::And &&
3015 isa<ConstantInt>(I->getOperand(1))) {
3016 // Scan every byte of the and mask, seeing if the byte is either 0 or 255.
3017 unsigned NumBytes = ByteValues.size();
3018 APInt Byte(I->getType()->getPrimitiveSizeInBits(), 255);
3019 const APInt &AndMask = cast<ConstantInt>(I->getOperand(1))->getValue();
3020
3021 for (unsigned i = 0; i != NumBytes; ++i, Byte <<= 8) {
3022 // If this byte is masked out by a later operation, we don't care what
3023 // the and mask is.
3024 if ((ByteMask & (1 << i)) == 0)
3025 continue;
3026
3027 // If the AndMask is all zeros for this byte, clear the bit.
3028 APInt MaskB = AndMask & Byte;
3029 if (MaskB == 0) {
3030 ByteMask &= ~(1U << i);
3031 continue;
3032 }
3033
3034 // If the AndMask is not all ones for this byte, it's not a bytezap.
3035 if (MaskB != Byte)
3036 return true;
3037
3038 // Otherwise, this byte is kept.
3039 }
3040
3041 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
3042 ByteValues);
3043 }
Chris Lattnerafe91a52006-06-15 19:07:26 +00003044 }
3045
Chris Lattner8c34cd22008-10-05 02:13:19 +00003046 // Okay, we got to something that isn't a shift, 'or' or 'and'. This must be
3047 // the input value to the bswap. Some observations: 1) if more than one byte
3048 // is demanded from this input, then it could not be successfully assembled
3049 // into a byteswap. At least one of the two bytes would not be aligned with
3050 // their ultimate destination.
3051 if (!isPowerOf2_32(ByteMask)) return true;
3052 unsigned InputByteNo = CountTrailingZeros_32(ByteMask);
Chris Lattnerafe91a52006-06-15 19:07:26 +00003053
Chris Lattner8c34cd22008-10-05 02:13:19 +00003054 // 2) The input and ultimate destinations must line up: if byte 3 of an i32
3055 // is demanded, it needs to go into byte 0 of the result. This means that the
3056 // byte needs to be shifted until it lands in the right byte bucket. The
3057 // shift amount depends on the position: if the byte is coming from the high
3058 // part of the value (e.g. byte 3) then it must be shifted right. If from the
3059 // low part, it must be shifted left.
3060 unsigned DestByteNo = InputByteNo + OverallLeftShift;
3061 if (InputByteNo < ByteValues.size()/2) {
3062 if (ByteValues.size()-1-DestByteNo != InputByteNo)
3063 return true;
3064 } else {
3065 if (ByteValues.size()-1-DestByteNo != InputByteNo)
3066 return true;
3067 }
Chris Lattnerafe91a52006-06-15 19:07:26 +00003068
3069 // If the destination byte value is already defined, the values are or'd
3070 // together, which isn't a bswap (unless it's an or of the same bits).
Chris Lattner8c34cd22008-10-05 02:13:19 +00003071 if (ByteValues[DestByteNo] && ByteValues[DestByteNo] != V)
Chris Lattnerafe91a52006-06-15 19:07:26 +00003072 return true;
Chris Lattner8c34cd22008-10-05 02:13:19 +00003073 ByteValues[DestByteNo] = V;
Chris Lattnerafe91a52006-06-15 19:07:26 +00003074 return false;
3075}
3076
3077/// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
3078/// If so, insert the new bswap intrinsic and return it.
3079Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
Chris Lattner55fc8c42007-04-01 20:57:36 +00003080 const IntegerType *ITy = dyn_cast<IntegerType>(I.getType());
Chris Lattner8c34cd22008-10-05 02:13:19 +00003081 if (!ITy || ITy->getBitWidth() % 16 ||
3082 // ByteMask only allows up to 32-byte values.
3083 ITy->getBitWidth() > 32*8)
Chris Lattner55fc8c42007-04-01 20:57:36 +00003084 return 0; // Can only bswap pairs of bytes. Can't do vectors.
Chris Lattnerafe91a52006-06-15 19:07:26 +00003085
3086 /// ByteValues - For each byte of the result, we keep track of which value
3087 /// defines each byte.
Chris Lattner535014f2007-02-15 22:52:10 +00003088 SmallVector<Value*, 8> ByteValues;
Chris Lattner55fc8c42007-04-01 20:57:36 +00003089 ByteValues.resize(ITy->getBitWidth()/8);
Chris Lattnerafe91a52006-06-15 19:07:26 +00003090
3091 // Try to find all the pieces corresponding to the bswap.
Chris Lattner8c34cd22008-10-05 02:13:19 +00003092 uint32_t ByteMask = ~0U >> (32-ByteValues.size());
3093 if (CollectBSwapParts(&I, 0, ByteMask, ByteValues))
Chris Lattnerafe91a52006-06-15 19:07:26 +00003094 return 0;
3095
3096 // Check to see if all of the bytes come from the same value.
3097 Value *V = ByteValues[0];
3098 if (V == 0) return 0; // Didn't find a byte? Must be zero.
3099
3100 // Check to make sure that all of the bytes come from the same value.
3101 for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
3102 if (ByteValues[i] != V)
3103 return 0;
Chandler Carruth69940402007-08-04 01:51:18 +00003104 const Type *Tys[] = { ITy };
Chris Lattnerafe91a52006-06-15 19:07:26 +00003105 Module *M = I.getParent()->getParent()->getParent();
Chandler Carruth69940402007-08-04 01:51:18 +00003106 Function *F = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 1);
Gabor Greif051a9502008-04-06 20:25:17 +00003107 return CallInst::Create(F, V);
Chris Lattnerafe91a52006-06-15 19:07:26 +00003108}
3109
Chris Lattnerfaaf9512008-11-16 04:24:12 +00003110/// MatchSelectFromAndOr - We have an expression of the form (A&C)|(B&D). Check
3111/// If A is (cond?-1:0) and either B or D is ~(cond?-1,0) or (cond?0,-1), then
3112/// we can simplify this expression to "cond ? C : D or B".
3113static Instruction *MatchSelectFromAndOr(Value *A, Value *B,
Chris Lattner4de84762010-01-04 07:02:48 +00003114 Value *C, Value *D) {
Chris Lattnera6a474d2008-11-16 04:26:55 +00003115 // If A is not a select of -1/0, this cannot match.
Chris Lattner6046fb72008-11-16 04:46:19 +00003116 Value *Cond = 0;
Dan Gohman4ae51262009-08-12 16:23:25 +00003117 if (!match(A, m_SelectCst<-1, 0>(m_Value(Cond))))
Chris Lattnerfaaf9512008-11-16 04:24:12 +00003118 return 0;
3119
Chris Lattnera6a474d2008-11-16 04:26:55 +00003120 // ((cond?-1:0)&C) | (B&(cond?0:-1)) -> cond ? C : B.
Dan Gohman4ae51262009-08-12 16:23:25 +00003121 if (match(D, m_SelectCst<0, -1>(m_Specific(Cond))))
Chris Lattnera6a474d2008-11-16 04:26:55 +00003122 return SelectInst::Create(Cond, C, B);
Dan Gohman4ae51262009-08-12 16:23:25 +00003123 if (match(D, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond)))))
Chris Lattnera6a474d2008-11-16 04:26:55 +00003124 return SelectInst::Create(Cond, C, B);
3125 // ((cond?-1:0)&C) | ((cond?0:-1)&D) -> cond ? C : D.
Dan Gohman4ae51262009-08-12 16:23:25 +00003126 if (match(B, m_SelectCst<0, -1>(m_Specific(Cond))))
Chris Lattnera6a474d2008-11-16 04:26:55 +00003127 return SelectInst::Create(Cond, C, D);
Dan Gohman4ae51262009-08-12 16:23:25 +00003128 if (match(B, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond)))))
Chris Lattnera6a474d2008-11-16 04:26:55 +00003129 return SelectInst::Create(Cond, C, D);
Chris Lattnerfaaf9512008-11-16 04:24:12 +00003130 return 0;
3131}
Chris Lattnerafe91a52006-06-15 19:07:26 +00003132
Chris Lattner69d4ced2008-11-16 05:20:07 +00003133/// FoldOrOfICmps - Fold (icmp)|(icmp) if possible.
3134Instruction *InstCombiner::FoldOrOfICmps(Instruction &I,
3135 ICmpInst *LHS, ICmpInst *RHS) {
3136 Value *Val, *Val2;
3137 ConstantInt *LHSCst, *RHSCst;
3138 ICmpInst::Predicate LHSCC, RHSCC;
3139
3140 // This only handles icmp of constants: (icmp1 A, C1) | (icmp2 B, C2).
Chris Lattner3f40e232009-11-29 00:51:17 +00003141 if (!match(LHS, m_ICmp(LHSCC, m_Value(Val), m_ConstantInt(LHSCst))) ||
3142 !match(RHS, m_ICmp(RHSCC, m_Value(Val2), m_ConstantInt(RHSCst))))
Chris Lattner69d4ced2008-11-16 05:20:07 +00003143 return 0;
Chris Lattner3f40e232009-11-29 00:51:17 +00003144
3145
3146 // (icmp ne A, 0) | (icmp ne B, 0) --> (icmp ne (A|B), 0)
3147 if (LHSCst == RHSCst && LHSCC == RHSCC &&
3148 LHSCC == ICmpInst::ICMP_NE && LHSCst->isZero()) {
3149 Value *NewOr = Builder->CreateOr(Val, Val2);
3150 return new ICmpInst(LHSCC, NewOr, LHSCst);
3151 }
Chris Lattner69d4ced2008-11-16 05:20:07 +00003152
3153 // From here on, we only handle:
3154 // (icmp1 A, C1) | (icmp2 A, C2) --> something simpler.
3155 if (Val != Val2) return 0;
3156
3157 // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
3158 if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
3159 RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
3160 LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
3161 RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
3162 return 0;
3163
3164 // We can't fold (ugt x, C) | (sgt x, C2).
3165 if (!PredicatesFoldable(LHSCC, RHSCC))
3166 return 0;
3167
3168 // Ensure that the larger constant is on the RHS.
3169 bool ShouldSwap;
Nick Lewycky4a134af2009-10-25 05:20:17 +00003170 if (CmpInst::isSigned(LHSCC) ||
Chris Lattner69d4ced2008-11-16 05:20:07 +00003171 (ICmpInst::isEquality(LHSCC) &&
Nick Lewycky4a134af2009-10-25 05:20:17 +00003172 CmpInst::isSigned(RHSCC)))
Chris Lattner69d4ced2008-11-16 05:20:07 +00003173 ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
3174 else
3175 ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
3176
3177 if (ShouldSwap) {
3178 std::swap(LHS, RHS);
3179 std::swap(LHSCst, RHSCst);
3180 std::swap(LHSCC, RHSCC);
3181 }
3182
3183 // At this point, we know we have have two icmp instructions
3184 // comparing a value against two constants and or'ing the result
3185 // together. Because of the above check, we know that we only have
3186 // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
3187 // FoldICmpLogical check above), that the two constants are not
3188 // equal.
3189 assert(LHSCst != RHSCst && "Compares not folded above?");
3190
3191 switch (LHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003192 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00003193 case ICmpInst::ICMP_EQ:
3194 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003195 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00003196 case ICmpInst::ICMP_EQ:
Dan Gohman186a6362009-08-12 16:04:34 +00003197 if (LHSCst == SubOne(RHSCst)) {
Owen Andersond672ecb2009-07-03 00:17:18 +00003198 // (X == 13 | X == 14) -> X-13 <u 2
Owen Andersonbaf3c402009-07-29 18:55:55 +00003199 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
Chris Lattner74381062009-08-30 07:44:24 +00003200 Value *Add = Builder->CreateAdd(Val, AddCST, Val->getName()+".off");
Dan Gohman186a6362009-08-12 16:04:34 +00003201 AddCST = ConstantExpr::getSub(AddOne(RHSCst), LHSCst);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003202 return new ICmpInst(ICmpInst::ICMP_ULT, Add, AddCST);
Chris Lattner69d4ced2008-11-16 05:20:07 +00003203 }
3204 break; // (X == 13 | X == 15) -> no change
3205 case ICmpInst::ICMP_UGT: // (X == 13 | X u> 14) -> no change
3206 case ICmpInst::ICMP_SGT: // (X == 13 | X s> 14) -> no change
3207 break;
3208 case ICmpInst::ICMP_NE: // (X == 13 | X != 15) -> X != 15
3209 case ICmpInst::ICMP_ULT: // (X == 13 | X u< 15) -> X u< 15
3210 case ICmpInst::ICMP_SLT: // (X == 13 | X s< 15) -> X s< 15
3211 return ReplaceInstUsesWith(I, RHS);
3212 }
3213 break;
3214 case ICmpInst::ICMP_NE:
3215 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003216 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00003217 case ICmpInst::ICMP_EQ: // (X != 13 | X == 15) -> X != 13
3218 case ICmpInst::ICMP_UGT: // (X != 13 | X u> 15) -> X != 13
3219 case ICmpInst::ICMP_SGT: // (X != 13 | X s> 15) -> X != 13
3220 return ReplaceInstUsesWith(I, LHS);
3221 case ICmpInst::ICMP_NE: // (X != 13 | X != 15) -> true
3222 case ICmpInst::ICMP_ULT: // (X != 13 | X u< 15) -> true
3223 case ICmpInst::ICMP_SLT: // (X != 13 | X s< 15) -> true
Chris Lattner4de84762010-01-04 07:02:48 +00003224 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getContext()));
Chris Lattner69d4ced2008-11-16 05:20:07 +00003225 }
3226 break;
3227 case ICmpInst::ICMP_ULT:
3228 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003229 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00003230 case ICmpInst::ICMP_EQ: // (X u< 13 | X == 14) -> no change
3231 break;
3232 case ICmpInst::ICMP_UGT: // (X u< 13 | X u> 15) -> (X-13) u> 2
3233 // If RHSCst is [us]MAXINT, it is always false. Not handling
3234 // this can cause overflow.
3235 if (RHSCst->isMaxValue(false))
3236 return ReplaceInstUsesWith(I, LHS);
Dan Gohman186a6362009-08-12 16:04:34 +00003237 return InsertRangeTest(Val, LHSCst, AddOne(RHSCst),
Owen Andersond672ecb2009-07-03 00:17:18 +00003238 false, false, I);
Chris Lattner69d4ced2008-11-16 05:20:07 +00003239 case ICmpInst::ICMP_SGT: // (X u< 13 | X s> 15) -> no change
3240 break;
3241 case ICmpInst::ICMP_NE: // (X u< 13 | X != 15) -> X != 15
3242 case ICmpInst::ICMP_ULT: // (X u< 13 | X u< 15) -> X u< 15
3243 return ReplaceInstUsesWith(I, RHS);
3244 case ICmpInst::ICMP_SLT: // (X u< 13 | X s< 15) -> no change
3245 break;
3246 }
3247 break;
3248 case ICmpInst::ICMP_SLT:
3249 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003250 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00003251 case ICmpInst::ICMP_EQ: // (X s< 13 | X == 14) -> no change
3252 break;
3253 case ICmpInst::ICMP_SGT: // (X s< 13 | X s> 15) -> (X-13) s> 2
3254 // If RHSCst is [us]MAXINT, it is always false. Not handling
3255 // this can cause overflow.
3256 if (RHSCst->isMaxValue(true))
3257 return ReplaceInstUsesWith(I, LHS);
Dan Gohman186a6362009-08-12 16:04:34 +00003258 return InsertRangeTest(Val, LHSCst, AddOne(RHSCst),
Owen Andersond672ecb2009-07-03 00:17:18 +00003259 true, false, I);
Chris Lattner69d4ced2008-11-16 05:20:07 +00003260 case ICmpInst::ICMP_UGT: // (X s< 13 | X u> 15) -> no change
3261 break;
3262 case ICmpInst::ICMP_NE: // (X s< 13 | X != 15) -> X != 15
3263 case ICmpInst::ICMP_SLT: // (X s< 13 | X s< 15) -> X s< 15
3264 return ReplaceInstUsesWith(I, RHS);
3265 case ICmpInst::ICMP_ULT: // (X s< 13 | X u< 15) -> no change
3266 break;
3267 }
3268 break;
3269 case ICmpInst::ICMP_UGT:
3270 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003271 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00003272 case ICmpInst::ICMP_EQ: // (X u> 13 | X == 15) -> X u> 13
3273 case ICmpInst::ICMP_UGT: // (X u> 13 | X u> 15) -> X u> 13
3274 return ReplaceInstUsesWith(I, LHS);
3275 case ICmpInst::ICMP_SGT: // (X u> 13 | X s> 15) -> no change
3276 break;
3277 case ICmpInst::ICMP_NE: // (X u> 13 | X != 15) -> true
3278 case ICmpInst::ICMP_ULT: // (X u> 13 | X u< 15) -> true
Chris Lattner4de84762010-01-04 07:02:48 +00003279 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getContext()));
Chris Lattner69d4ced2008-11-16 05:20:07 +00003280 case ICmpInst::ICMP_SLT: // (X u> 13 | X s< 15) -> no change
3281 break;
3282 }
3283 break;
3284 case ICmpInst::ICMP_SGT:
3285 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003286 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00003287 case ICmpInst::ICMP_EQ: // (X s> 13 | X == 15) -> X > 13
3288 case ICmpInst::ICMP_SGT: // (X s> 13 | X s> 15) -> X > 13
3289 return ReplaceInstUsesWith(I, LHS);
3290 case ICmpInst::ICMP_UGT: // (X s> 13 | X u> 15) -> no change
3291 break;
3292 case ICmpInst::ICMP_NE: // (X s> 13 | X != 15) -> true
3293 case ICmpInst::ICMP_SLT: // (X s> 13 | X s< 15) -> true
Chris Lattner4de84762010-01-04 07:02:48 +00003294 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getContext()));
Chris Lattner69d4ced2008-11-16 05:20:07 +00003295 case ICmpInst::ICMP_ULT: // (X s> 13 | X u< 15) -> no change
3296 break;
3297 }
3298 break;
3299 }
3300 return 0;
3301}
3302
Chris Lattner5414cc52009-07-23 05:46:22 +00003303Instruction *InstCombiner::FoldOrOfFCmps(Instruction &I, FCmpInst *LHS,
3304 FCmpInst *RHS) {
3305 if (LHS->getPredicate() == FCmpInst::FCMP_UNO &&
3306 RHS->getPredicate() == FCmpInst::FCMP_UNO &&
3307 LHS->getOperand(0)->getType() == RHS->getOperand(0)->getType()) {
3308 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
3309 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
3310 // If either of the constants are nans, then the whole thing returns
3311 // true.
3312 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Chris Lattner4de84762010-01-04 07:02:48 +00003313 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getContext()));
Chris Lattner5414cc52009-07-23 05:46:22 +00003314
3315 // Otherwise, no need to compare the two constants, compare the
3316 // rest.
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003317 return new FCmpInst(FCmpInst::FCMP_UNO,
Chris Lattner5414cc52009-07-23 05:46:22 +00003318 LHS->getOperand(0), RHS->getOperand(0));
3319 }
3320
3321 // Handle vector zeros. This occurs because the canonical form of
3322 // "fcmp uno x,x" is "fcmp uno x, 0".
3323 if (isa<ConstantAggregateZero>(LHS->getOperand(1)) &&
3324 isa<ConstantAggregateZero>(RHS->getOperand(1)))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003325 return new FCmpInst(FCmpInst::FCMP_UNO,
Chris Lattner5414cc52009-07-23 05:46:22 +00003326 LHS->getOperand(0), RHS->getOperand(0));
3327
3328 return 0;
3329 }
3330
3331 Value *Op0LHS = LHS->getOperand(0), *Op0RHS = LHS->getOperand(1);
3332 Value *Op1LHS = RHS->getOperand(0), *Op1RHS = RHS->getOperand(1);
3333 FCmpInst::Predicate Op0CC = LHS->getPredicate(), Op1CC = RHS->getPredicate();
3334
3335 if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
3336 // Swap RHS operands to match LHS.
3337 Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
3338 std::swap(Op1LHS, Op1RHS);
3339 }
3340 if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
3341 // Simplify (fcmp cc0 x, y) | (fcmp cc1 x, y).
3342 if (Op0CC == Op1CC)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003343 return new FCmpInst((FCmpInst::Predicate)Op0CC,
Chris Lattner5414cc52009-07-23 05:46:22 +00003344 Op0LHS, Op0RHS);
3345 if (Op0CC == FCmpInst::FCMP_TRUE || Op1CC == FCmpInst::FCMP_TRUE)
Chris Lattner4de84762010-01-04 07:02:48 +00003346 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getContext()));
Chris Lattner5414cc52009-07-23 05:46:22 +00003347 if (Op0CC == FCmpInst::FCMP_FALSE)
3348 return ReplaceInstUsesWith(I, RHS);
3349 if (Op1CC == FCmpInst::FCMP_FALSE)
3350 return ReplaceInstUsesWith(I, LHS);
3351 bool Op0Ordered;
3352 bool Op1Ordered;
3353 unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
3354 unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
3355 if (Op0Ordered == Op1Ordered) {
3356 // If both are ordered or unordered, return a new fcmp with
3357 // or'ed predicates.
Chris Lattner4de84762010-01-04 07:02:48 +00003358 Value *RV = getFCmpValue(Op0Ordered, Op0Pred|Op1Pred, Op0LHS, Op0RHS);
Chris Lattner5414cc52009-07-23 05:46:22 +00003359 if (Instruction *I = dyn_cast<Instruction>(RV))
3360 return I;
3361 // Otherwise, it's a constant boolean value...
3362 return ReplaceInstUsesWith(I, RV);
3363 }
3364 }
3365 return 0;
3366}
3367
Bill Wendlinga698a472008-12-01 08:23:25 +00003368/// FoldOrWithConstants - This helper function folds:
3369///
Bill Wendlinga8bb13f2008-12-02 05:09:00 +00003370/// ((A | B) & C1) | (B & C2)
Bill Wendlinga698a472008-12-01 08:23:25 +00003371///
3372/// into:
3373///
Bill Wendlinga8bb13f2008-12-02 05:09:00 +00003374/// (A & C1) | B
Bill Wendlingd54d8602008-12-01 08:32:40 +00003375///
Bill Wendlinga8bb13f2008-12-02 05:09:00 +00003376/// when the XOR of the two constants is "all ones" (-1).
Bill Wendlingd54d8602008-12-01 08:32:40 +00003377Instruction *InstCombiner::FoldOrWithConstants(BinaryOperator &I, Value *Op,
Bill Wendlinga698a472008-12-01 08:23:25 +00003378 Value *A, Value *B, Value *C) {
Bill Wendlingdda74e02008-12-02 05:06:43 +00003379 ConstantInt *CI1 = dyn_cast<ConstantInt>(C);
3380 if (!CI1) return 0;
Bill Wendlinga698a472008-12-01 08:23:25 +00003381
Bill Wendling286a0542008-12-02 06:24:20 +00003382 Value *V1 = 0;
3383 ConstantInt *CI2 = 0;
Dan Gohman4ae51262009-08-12 16:23:25 +00003384 if (!match(Op, m_And(m_Value(V1), m_ConstantInt(CI2)))) return 0;
Bill Wendlinga698a472008-12-01 08:23:25 +00003385
Bill Wendling29976b92008-12-02 06:18:11 +00003386 APInt Xor = CI1->getValue() ^ CI2->getValue();
3387 if (!Xor.isAllOnesValue()) return 0;
3388
Bill Wendling286a0542008-12-02 06:24:20 +00003389 if (V1 == A || V1 == B) {
Chris Lattner74381062009-08-30 07:44:24 +00003390 Value *NewOp = Builder->CreateAnd((V1 == A) ? B : A, CI1);
Bill Wendlingd16c6e92008-12-02 06:22:04 +00003391 return BinaryOperator::CreateOr(NewOp, V1);
Bill Wendlinga698a472008-12-01 08:23:25 +00003392 }
3393
3394 return 0;
3395}
3396
Chris Lattner7e708292002-06-25 16:13:24 +00003397Instruction *InstCombiner::visitOr(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00003398 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00003399 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00003400
Chris Lattnerd06094f2009-11-10 00:55:12 +00003401 if (Value *V = SimplifyOrInst(Op0, Op1, TD))
3402 return ReplaceInstUsesWith(I, V);
3403
3404
Chris Lattnerf8c36f52006-02-12 08:02:11 +00003405 // See if we can simplify any instructions used by the instruction whose sole
3406 // purpose is to compute bits we don't care about.
Dan Gohman6de29f82009-06-15 22:12:54 +00003407 if (SimplifyDemandedInstructionBits(I))
3408 return &I;
Chris Lattner041a6c92007-06-15 05:26:55 +00003409
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003410 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner4f637d42006-01-06 17:59:59 +00003411 ConstantInt *C1 = 0; Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +00003412 // (X & C1) | C2 --> (X | C2) & (C1|C2)
Dan Gohman4ae51262009-08-12 16:23:25 +00003413 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00003414 isOnlyUse(Op0)) {
Chris Lattner74381062009-08-30 07:44:24 +00003415 Value *Or = Builder->CreateOr(X, RHS);
Chris Lattner6934a042007-02-11 01:23:03 +00003416 Or->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003417 return BinaryOperator::CreateAnd(Or,
Chris Lattner4de84762010-01-04 07:02:48 +00003418 ConstantInt::get(I.getContext(),
3419 RHS->getValue() | C1->getValue()));
Chris Lattneracd1f0f2004-07-30 07:50:03 +00003420 }
Chris Lattnerad44ebf2003-07-23 18:29:44 +00003421
Chris Lattneracd1f0f2004-07-30 07:50:03 +00003422 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
Dan Gohman4ae51262009-08-12 16:23:25 +00003423 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00003424 isOnlyUse(Op0)) {
Chris Lattner74381062009-08-30 07:44:24 +00003425 Value *Or = Builder->CreateOr(X, RHS);
Chris Lattner6934a042007-02-11 01:23:03 +00003426 Or->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003427 return BinaryOperator::CreateXor(Or,
Chris Lattner4de84762010-01-04 07:02:48 +00003428 ConstantInt::get(I.getContext(),
3429 C1->getValue() & ~RHS->getValue()));
Chris Lattnerad44ebf2003-07-23 18:29:44 +00003430 }
Chris Lattner2eefe512004-04-09 19:05:30 +00003431
3432 // Try to fold constant and into select arguments.
3433 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner80f43d32010-01-04 07:53:58 +00003434 if (Instruction *R = FoldOpIntoSelect(I, SI))
Chris Lattner2eefe512004-04-09 19:05:30 +00003435 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00003436 if (isa<PHINode>(Op0))
3437 if (Instruction *NV = FoldOpIntoPhi(I))
3438 return NV;
Chris Lattnerad44ebf2003-07-23 18:29:44 +00003439 }
3440
Chris Lattner4f637d42006-01-06 17:59:59 +00003441 Value *A = 0, *B = 0;
3442 ConstantInt *C1 = 0, *C2 = 0;
Chris Lattnerf4d4c872005-05-07 23:49:08 +00003443
Chris Lattner6423d4c2006-07-10 20:25:24 +00003444 // (A | B) | C and A | (B | C) -> bswap if possible.
3445 // (A >> B) | (C << D) and (A << B) | (B >> C) -> bswap if possible.
Dan Gohman4ae51262009-08-12 16:23:25 +00003446 if (match(Op0, m_Or(m_Value(), m_Value())) ||
3447 match(Op1, m_Or(m_Value(), m_Value())) ||
3448 (match(Op0, m_Shift(m_Value(), m_Value())) &&
3449 match(Op1, m_Shift(m_Value(), m_Value())))) {
Chris Lattnerafe91a52006-06-15 19:07:26 +00003450 if (Instruction *BSwap = MatchBSwap(I))
3451 return BSwap;
3452 }
3453
Chris Lattner6e4c6492005-05-09 04:58:36 +00003454 // (X^C)|Y -> (X|Y)^C iff Y&C == 0
Owen Andersonc7d2ce72009-07-10 17:35:01 +00003455 if (Op0->hasOneUse() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00003456 match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Reid Spencera03d45f2007-03-22 22:19:58 +00003457 MaskedValueIsZero(Op1, C1->getValue())) {
Chris Lattner74381062009-08-30 07:44:24 +00003458 Value *NOr = Builder->CreateOr(A, Op1);
Chris Lattner6934a042007-02-11 01:23:03 +00003459 NOr->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003460 return BinaryOperator::CreateXor(NOr, C1);
Chris Lattner6e4c6492005-05-09 04:58:36 +00003461 }
3462
3463 // Y|(X^C) -> (X|Y)^C iff Y&C == 0
Owen Andersonc7d2ce72009-07-10 17:35:01 +00003464 if (Op1->hasOneUse() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00003465 match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Reid Spencera03d45f2007-03-22 22:19:58 +00003466 MaskedValueIsZero(Op0, C1->getValue())) {
Chris Lattner74381062009-08-30 07:44:24 +00003467 Value *NOr = Builder->CreateOr(A, Op0);
Chris Lattner6934a042007-02-11 01:23:03 +00003468 NOr->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003469 return BinaryOperator::CreateXor(NOr, C1);
Chris Lattner6e4c6492005-05-09 04:58:36 +00003470 }
3471
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00003472 // (A & C)|(B & D)
Chris Lattner2384d7b2007-06-19 05:43:49 +00003473 Value *C = 0, *D = 0;
Dan Gohman4ae51262009-08-12 16:23:25 +00003474 if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
3475 match(Op1, m_And(m_Value(B), m_Value(D)))) {
Chris Lattner6cae0e02007-04-08 07:55:22 +00003476 Value *V1 = 0, *V2 = 0, *V3 = 0;
3477 C1 = dyn_cast<ConstantInt>(C);
3478 C2 = dyn_cast<ConstantInt>(D);
3479 if (C1 && C2) { // (A & C1)|(B & C2)
3480 // If we have: ((V + N) & C1) | (V & C2)
3481 // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
3482 // replace with V+N.
3483 if (C1->getValue() == ~C2->getValue()) {
3484 if ((C2->getValue() & (C2->getValue()+1)) == 0 && // C2 == 0+1+
Dan Gohman4ae51262009-08-12 16:23:25 +00003485 match(A, m_Add(m_Value(V1), m_Value(V2)))) {
Chris Lattner6cae0e02007-04-08 07:55:22 +00003486 // Add commutes, try both ways.
3487 if (V1 == B && MaskedValueIsZero(V2, C2->getValue()))
3488 return ReplaceInstUsesWith(I, A);
3489 if (V2 == B && MaskedValueIsZero(V1, C2->getValue()))
3490 return ReplaceInstUsesWith(I, A);
3491 }
3492 // Or commutes, try both ways.
3493 if ((C1->getValue() & (C1->getValue()+1)) == 0 &&
Dan Gohman4ae51262009-08-12 16:23:25 +00003494 match(B, m_Add(m_Value(V1), m_Value(V2)))) {
Chris Lattner6cae0e02007-04-08 07:55:22 +00003495 // Add commutes, try both ways.
3496 if (V1 == A && MaskedValueIsZero(V2, C1->getValue()))
3497 return ReplaceInstUsesWith(I, B);
3498 if (V2 == A && MaskedValueIsZero(V1, C1->getValue()))
3499 return ReplaceInstUsesWith(I, B);
3500 }
3501 }
Chris Lattnere4412c12010-01-04 06:03:59 +00003502
3503 // ((V | N) & C1) | (V & C2) --> (V|N) & (C1|C2)
3504 // iff (C1&C2) == 0 and (N&~C1) == 0
3505 if ((C1->getValue() & C2->getValue()) == 0) {
3506 if (match(A, m_Or(m_Value(V1), m_Value(V2))) &&
3507 ((V1 == B && MaskedValueIsZero(V2, ~C1->getValue())) || // (V|N)
3508 (V2 == B && MaskedValueIsZero(V1, ~C1->getValue())))) // (N|V)
3509 return BinaryOperator::CreateAnd(A,
3510 ConstantInt::get(A->getContext(),
3511 C1->getValue()|C2->getValue()));
3512 // Or commutes, try both ways.
3513 if (match(B, m_Or(m_Value(V1), m_Value(V2))) &&
3514 ((V1 == A && MaskedValueIsZero(V2, ~C2->getValue())) || // (V|N)
3515 (V2 == A && MaskedValueIsZero(V1, ~C2->getValue())))) // (N|V)
3516 return BinaryOperator::CreateAnd(B,
3517 ConstantInt::get(B->getContext(),
3518 C1->getValue()|C2->getValue()));
3519 }
Chris Lattner6cae0e02007-04-08 07:55:22 +00003520 }
3521
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00003522 // Check to see if we have any common things being and'ed. If so, find the
3523 // terms for V1 & (V2|V3).
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00003524 if (isOnlyUse(Op0) || isOnlyUse(Op1)) {
Chris Lattnere4412c12010-01-04 06:03:59 +00003525 V1 = 0;
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00003526 if (A == B) // (A & C)|(A & D) == A & (C|D)
3527 V1 = A, V2 = C, V3 = D;
3528 else if (A == D) // (A & C)|(B & A) == A & (B|C)
3529 V1 = A, V2 = B, V3 = C;
3530 else if (C == B) // (A & C)|(C & D) == C & (A|D)
3531 V1 = C, V2 = A, V3 = D;
3532 else if (C == D) // (A & C)|(B & C) == C & (A|B)
3533 V1 = C, V2 = A, V3 = B;
3534
3535 if (V1) {
Chris Lattner74381062009-08-30 07:44:24 +00003536 Value *Or = Builder->CreateOr(V2, V3, "tmp");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003537 return BinaryOperator::CreateAnd(V1, Or);
Chris Lattner0b7c0bf2005-09-18 06:02:59 +00003538 }
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00003539 }
Dan Gohmanb493b272008-10-28 22:38:57 +00003540
Dan Gohman1975d032008-10-30 20:40:10 +00003541 // (A & (C0?-1:0)) | (B & ~(C0?-1:0)) -> C0 ? A : B, and commuted variants
Chris Lattner4de84762010-01-04 07:02:48 +00003542 if (Instruction *Match = MatchSelectFromAndOr(A, B, C, D))
Chris Lattnerfaaf9512008-11-16 04:24:12 +00003543 return Match;
Chris Lattner4de84762010-01-04 07:02:48 +00003544 if (Instruction *Match = MatchSelectFromAndOr(B, A, D, C))
Chris Lattnerfaaf9512008-11-16 04:24:12 +00003545 return Match;
Chris Lattner4de84762010-01-04 07:02:48 +00003546 if (Instruction *Match = MatchSelectFromAndOr(C, B, A, D))
Chris Lattnerfaaf9512008-11-16 04:24:12 +00003547 return Match;
Chris Lattner4de84762010-01-04 07:02:48 +00003548 if (Instruction *Match = MatchSelectFromAndOr(D, A, B, C))
Chris Lattnerfaaf9512008-11-16 04:24:12 +00003549 return Match;
Bill Wendlingb01865c2008-11-30 13:52:49 +00003550
Bill Wendlingb01865c2008-11-30 13:52:49 +00003551 // ((A&~B)|(~A&B)) -> A^B
Dan Gohman4ae51262009-08-12 16:23:25 +00003552 if ((match(C, m_Not(m_Specific(D))) &&
3553 match(B, m_Not(m_Specific(A)))))
Bill Wendling03aae5f2008-12-01 08:09:47 +00003554 return BinaryOperator::CreateXor(A, D);
Bill Wendlingb01865c2008-11-30 13:52:49 +00003555 // ((~B&A)|(~A&B)) -> A^B
Dan Gohman4ae51262009-08-12 16:23:25 +00003556 if ((match(A, m_Not(m_Specific(D))) &&
3557 match(B, m_Not(m_Specific(C)))))
Bill Wendling03aae5f2008-12-01 08:09:47 +00003558 return BinaryOperator::CreateXor(C, D);
Bill Wendlingb01865c2008-11-30 13:52:49 +00003559 // ((A&~B)|(B&~A)) -> A^B
Dan Gohman4ae51262009-08-12 16:23:25 +00003560 if ((match(C, m_Not(m_Specific(B))) &&
3561 match(D, m_Not(m_Specific(A)))))
Bill Wendling03aae5f2008-12-01 08:09:47 +00003562 return BinaryOperator::CreateXor(A, B);
Bill Wendlingb01865c2008-11-30 13:52:49 +00003563 // ((~B&A)|(B&~A)) -> A^B
Dan Gohman4ae51262009-08-12 16:23:25 +00003564 if ((match(A, m_Not(m_Specific(B))) &&
3565 match(D, m_Not(m_Specific(C)))))
Bill Wendling03aae5f2008-12-01 08:09:47 +00003566 return BinaryOperator::CreateXor(C, B);
Chris Lattnere9bed7d2005-09-18 03:42:07 +00003567 }
Chris Lattnere511b742006-11-14 07:46:50 +00003568
3569 // (X >> Z) | (Y >> Z) -> (X|Y) >> Z for all shifts.
Reid Spencer832254e2007-02-02 02:16:23 +00003570 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
3571 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
3572 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
Chris Lattnere511b742006-11-14 07:46:50 +00003573 SI0->getOperand(1) == SI1->getOperand(1) &&
3574 (SI0->hasOneUse() || SI1->hasOneUse())) {
Chris Lattner74381062009-08-30 07:44:24 +00003575 Value *NewOp = Builder->CreateOr(SI0->getOperand(0), SI1->getOperand(0),
3576 SI0->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003577 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
Reid Spencer832254e2007-02-02 02:16:23 +00003578 SI1->getOperand(1));
Chris Lattnere511b742006-11-14 07:46:50 +00003579 }
3580 }
Chris Lattner67ca7682003-08-12 19:11:07 +00003581
Bill Wendlingb3833d12008-12-01 01:07:11 +00003582 // ((A|B)&1)|(B&-2) -> (A&1) | B
Dan Gohman4ae51262009-08-12 16:23:25 +00003583 if (match(Op0, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C))) ||
3584 match(Op0, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))))) {
Bill Wendlingd54d8602008-12-01 08:32:40 +00003585 Instruction *Ret = FoldOrWithConstants(I, Op1, A, B, C);
Bill Wendlinga698a472008-12-01 08:23:25 +00003586 if (Ret) return Ret;
Bill Wendlingb3833d12008-12-01 01:07:11 +00003587 }
3588 // (B&-2)|((A|B)&1) -> (A&1) | B
Dan Gohman4ae51262009-08-12 16:23:25 +00003589 if (match(Op1, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C))) ||
3590 match(Op1, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))))) {
Bill Wendlingd54d8602008-12-01 08:32:40 +00003591 Instruction *Ret = FoldOrWithConstants(I, Op0, A, B, C);
Bill Wendlinga698a472008-12-01 08:23:25 +00003592 if (Ret) return Ret;
Bill Wendlingb3833d12008-12-01 01:07:11 +00003593 }
3594
Chris Lattnerd06094f2009-11-10 00:55:12 +00003595 // (~A | ~B) == (~(A & B)) - De Morgan's Law
3596 if (Value *Op0NotVal = dyn_castNotVal(Op0))
3597 if (Value *Op1NotVal = dyn_castNotVal(Op1))
3598 if (Op0->hasOneUse() && Op1->hasOneUse()) {
3599 Value *And = Builder->CreateAnd(Op0NotVal, Op1NotVal,
3600 I.getName()+".demorgan");
3601 return BinaryOperator::CreateNot(And);
3602 }
Chris Lattnera2881962003-02-18 19:28:33 +00003603
Reid Spencere4d87aa2006-12-23 06:05:41 +00003604 // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
3605 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1))) {
Dan Gohman186a6362009-08-12 16:04:34 +00003606 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003607 return R;
3608
Chris Lattner69d4ced2008-11-16 05:20:07 +00003609 if (ICmpInst *LHS = dyn_cast<ICmpInst>(I.getOperand(0)))
3610 if (Instruction *Res = FoldOrOfICmps(I, LHS, RHS))
3611 return Res;
Chris Lattnerb4f40d22004-09-28 22:33:08 +00003612 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00003613
3614 // fold (or (cast A), (cast B)) -> (cast (or A, B))
Chris Lattner99c65742007-10-24 05:38:08 +00003615 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Chris Lattner6fc205f2006-05-05 06:39:07 +00003616 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00003617 if (Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
Evan Chengb98a10e2008-03-24 00:21:34 +00003618 if (!isa<ICmpInst>(Op0C->getOperand(0)) ||
3619 !isa<ICmpInst>(Op1C->getOperand(0))) {
3620 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattnerf98d2532009-07-23 05:32:17 +00003621 if (SrcTy == Op1C->getOperand(0)->getType() &&
3622 SrcTy->isIntOrIntVector() &&
Evan Chengb98a10e2008-03-24 00:21:34 +00003623 // Only do this if the casts both really cause code to be
3624 // generated.
3625 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
Chris Lattner80f43d32010-01-04 07:53:58 +00003626 I.getType()) &&
Evan Chengb98a10e2008-03-24 00:21:34 +00003627 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
Chris Lattner80f43d32010-01-04 07:53:58 +00003628 I.getType())) {
Chris Lattner74381062009-08-30 07:44:24 +00003629 Value *NewOp = Builder->CreateOr(Op0C->getOperand(0),
3630 Op1C->getOperand(0), I.getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003631 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Evan Chengb98a10e2008-03-24 00:21:34 +00003632 }
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00003633 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00003634 }
Chris Lattner99c65742007-10-24 05:38:08 +00003635 }
3636
3637
3638 // (fcmp uno x, c) | (fcmp uno y, c) -> (fcmp uno x, y)
3639 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
Chris Lattner5414cc52009-07-23 05:46:22 +00003640 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
3641 if (Instruction *Res = FoldOrOfFCmps(I, LHS, RHS))
3642 return Res;
Chris Lattner99c65742007-10-24 05:38:08 +00003643 }
Chris Lattnere9bed7d2005-09-18 03:42:07 +00003644
Chris Lattner7e708292002-06-25 16:13:24 +00003645 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00003646}
3647
Dan Gohman844731a2008-05-13 00:00:25 +00003648namespace {
3649
Chris Lattnerc317d392004-02-16 01:20:27 +00003650// XorSelf - Implements: X ^ X --> 0
3651struct XorSelf {
3652 Value *RHS;
3653 XorSelf(Value *rhs) : RHS(rhs) {}
3654 bool shouldApply(Value *LHS) const { return LHS == RHS; }
3655 Instruction *apply(BinaryOperator &Xor) const {
3656 return &Xor;
3657 }
3658};
Chris Lattner3f5b8772002-05-06 16:14:14 +00003659
Dan Gohman844731a2008-05-13 00:00:25 +00003660}
Chris Lattner3f5b8772002-05-06 16:14:14 +00003661
Chris Lattner7e708292002-06-25 16:13:24 +00003662Instruction *InstCombiner::visitXor(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00003663 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00003664 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00003665
Evan Chengd34af782008-03-25 20:07:13 +00003666 if (isa<UndefValue>(Op1)) {
3667 if (isa<UndefValue>(Op0))
3668 // Handle undef ^ undef -> 0 special case. This is a common
3669 // idiom (misuse).
Owen Andersona7235ea2009-07-31 20:28:14 +00003670 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00003671 return ReplaceInstUsesWith(I, Op1); // X ^ undef -> undef
Evan Chengd34af782008-03-25 20:07:13 +00003672 }
Chris Lattnere87597f2004-10-16 18:11:37 +00003673
Chris Lattnerc317d392004-02-16 01:20:27 +00003674 // xor X, X = 0, even if X is nested in a sequence of Xor's.
Dan Gohman186a6362009-08-12 16:04:34 +00003675 if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
Chris Lattnera9ff5eb2007-08-05 08:47:58 +00003676 assert(Result == &I && "AssociativeOpt didn't work?"); Result=Result;
Owen Andersona7235ea2009-07-31 20:28:14 +00003677 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerc317d392004-02-16 01:20:27 +00003678 }
Chris Lattnerf8c36f52006-02-12 08:02:11 +00003679
3680 // See if we can simplify any instructions used by the instruction whose sole
3681 // purpose is to compute bits we don't care about.
Dan Gohman6de29f82009-06-15 22:12:54 +00003682 if (SimplifyDemandedInstructionBits(I))
3683 return &I;
3684 if (isa<VectorType>(I.getType()))
3685 if (isa<ConstantAggregateZero>(Op1))
3686 return ReplaceInstUsesWith(I, Op0); // X ^ <0,0> -> X
Chris Lattner3f5b8772002-05-06 16:14:14 +00003687
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00003688 // Is this a ~ operation?
Dan Gohman186a6362009-08-12 16:04:34 +00003689 if (Value *NotOp = dyn_castNotVal(&I)) {
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00003690 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(NotOp)) {
3691 if (Op0I->getOpcode() == Instruction::And ||
3692 Op0I->getOpcode() == Instruction::Or) {
Chris Lattner48b59ec2009-10-26 15:40:07 +00003693 // ~(~X & Y) --> (X | ~Y) - De Morgan's Law
3694 // ~(~X | Y) === (X & ~Y) - De Morgan's Law
3695 if (dyn_castNotVal(Op0I->getOperand(1)))
3696 Op0I->swapOperands();
Dan Gohman186a6362009-08-12 16:04:34 +00003697 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
Chris Lattner74381062009-08-30 07:44:24 +00003698 Value *NotY =
3699 Builder->CreateNot(Op0I->getOperand(1),
3700 Op0I->getOperand(1)->getName()+".not");
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00003701 if (Op0I->getOpcode() == Instruction::And)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003702 return BinaryOperator::CreateOr(Op0NotVal, NotY);
Chris Lattner74381062009-08-30 07:44:24 +00003703 return BinaryOperator::CreateAnd(Op0NotVal, NotY);
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00003704 }
Chris Lattner48b59ec2009-10-26 15:40:07 +00003705
3706 // ~(X & Y) --> (~X | ~Y) - De Morgan's Law
3707 // ~(X | Y) === (~X & ~Y) - De Morgan's Law
3708 if (isFreeToInvert(Op0I->getOperand(0)) &&
3709 isFreeToInvert(Op0I->getOperand(1))) {
3710 Value *NotX =
3711 Builder->CreateNot(Op0I->getOperand(0), "notlhs");
3712 Value *NotY =
3713 Builder->CreateNot(Op0I->getOperand(1), "notrhs");
3714 if (Op0I->getOpcode() == Instruction::And)
3715 return BinaryOperator::CreateOr(NotX, NotY);
3716 return BinaryOperator::CreateAnd(NotX, NotY);
3717 }
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00003718 }
3719 }
3720 }
3721
3722
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003723 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner7acdf1d2009-10-11 22:00:32 +00003724 if (RHS->isOne() && Op0->hasOneUse()) {
Bill Wendling3479be92009-01-01 01:18:23 +00003725 // xor (cmp A, B), true = not (cmp A, B) = !cmp A, B
Nick Lewyckyf947b3e2007-08-06 20:04:16 +00003726 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Op0))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003727 return new ICmpInst(ICI->getInversePredicate(),
Reid Spencere4d87aa2006-12-23 06:05:41 +00003728 ICI->getOperand(0), ICI->getOperand(1));
Chris Lattnerad5b4fb2003-11-04 23:50:51 +00003729
Nick Lewyckyf947b3e2007-08-06 20:04:16 +00003730 if (FCmpInst *FCI = dyn_cast<FCmpInst>(Op0))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003731 return new FCmpInst(FCI->getInversePredicate(),
Nick Lewyckyf947b3e2007-08-06 20:04:16 +00003732 FCI->getOperand(0), FCI->getOperand(1));
3733 }
3734
Nick Lewycky517e1f52008-05-31 19:01:33 +00003735 // fold (xor(zext(cmp)), 1) and (xor(sext(cmp)), -1) to ext(!cmp).
3736 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
3737 if (CmpInst *CI = dyn_cast<CmpInst>(Op0C->getOperand(0))) {
3738 if (CI->hasOneUse() && Op0C->hasOneUse()) {
3739 Instruction::CastOps Opcode = Op0C->getOpcode();
Chris Lattner74381062009-08-30 07:44:24 +00003740 if ((Opcode == Instruction::ZExt || Opcode == Instruction::SExt) &&
3741 (RHS == ConstantExpr::getCast(Opcode,
Chris Lattner4de84762010-01-04 07:02:48 +00003742 ConstantInt::getTrue(I.getContext()),
Chris Lattner74381062009-08-30 07:44:24 +00003743 Op0C->getDestTy()))) {
3744 CI->setPredicate(CI->getInversePredicate());
3745 return CastInst::Create(Opcode, CI, Op0C->getType());
Nick Lewycky517e1f52008-05-31 19:01:33 +00003746 }
3747 }
3748 }
3749 }
3750
Reid Spencere4d87aa2006-12-23 06:05:41 +00003751 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Chris Lattnerd65460f2003-11-05 01:06:05 +00003752 // ~(c-X) == X-c-1 == X+(-c-1)
Chris Lattner7c4049c2004-01-12 19:35:11 +00003753 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
3754 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00003755 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
3756 Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
Owen Andersoneed707b2009-07-24 23:12:02 +00003757 ConstantInt::get(I.getType(), 1));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003758 return BinaryOperator::CreateAdd(Op0I->getOperand(1), ConstantRHS);
Chris Lattner7c4049c2004-01-12 19:35:11 +00003759 }
Chris Lattner5c6e2db2007-04-02 05:36:22 +00003760
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00003761 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
Chris Lattnerf8c36f52006-02-12 08:02:11 +00003762 if (Op0I->getOpcode() == Instruction::Add) {
Chris Lattner689d24b2003-11-04 23:37:10 +00003763 // ~(X-c) --> (-c-1)-X
Chris Lattner7c4049c2004-01-12 19:35:11 +00003764 if (RHS->isAllOnesValue()) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00003765 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003766 return BinaryOperator::CreateSub(
Owen Andersonbaf3c402009-07-29 18:55:55 +00003767 ConstantExpr::getSub(NegOp0CI,
Owen Andersoneed707b2009-07-24 23:12:02 +00003768 ConstantInt::get(I.getType(), 1)),
Owen Andersond672ecb2009-07-03 00:17:18 +00003769 Op0I->getOperand(0));
Chris Lattneracf4e072007-04-02 05:42:22 +00003770 } else if (RHS->getValue().isSignBit()) {
Chris Lattner5c6e2db2007-04-02 05:36:22 +00003771 // (X + C) ^ signbit -> (X + C + signbit)
Chris Lattner4de84762010-01-04 07:02:48 +00003772 Constant *C = ConstantInt::get(I.getContext(),
Owen Andersoneed707b2009-07-24 23:12:02 +00003773 RHS->getValue() + Op0CI->getValue());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003774 return BinaryOperator::CreateAdd(Op0I->getOperand(0), C);
Chris Lattnercd1d6d52007-04-02 05:48:58 +00003775
Chris Lattner7c4049c2004-01-12 19:35:11 +00003776 }
Chris Lattner02bd1b32006-02-26 19:57:54 +00003777 } else if (Op0I->getOpcode() == Instruction::Or) {
3778 // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
Reid Spencera03d45f2007-03-22 22:19:58 +00003779 if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue())) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00003780 Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
Chris Lattner02bd1b32006-02-26 19:57:54 +00003781 // Anything in both C1 and C2 is known to be zero, remove it from
3782 // NewRHS.
Owen Andersonbaf3c402009-07-29 18:55:55 +00003783 Constant *CommonBits = ConstantExpr::getAnd(Op0CI, RHS);
3784 NewRHS = ConstantExpr::getAnd(NewRHS,
3785 ConstantExpr::getNot(CommonBits));
Chris Lattner7a1e9242009-08-30 06:13:40 +00003786 Worklist.Add(Op0I);
Chris Lattner02bd1b32006-02-26 19:57:54 +00003787 I.setOperand(0, Op0I->getOperand(0));
3788 I.setOperand(1, NewRHS);
3789 return &I;
3790 }
Chris Lattnereca0c5c2003-07-23 21:37:07 +00003791 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00003792 }
Chris Lattner05bd1b22002-08-20 18:24:26 +00003793 }
Chris Lattner2eefe512004-04-09 19:05:30 +00003794
3795 // Try to fold constant and into select arguments.
3796 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner80f43d32010-01-04 07:53:58 +00003797 if (Instruction *R = FoldOpIntoSelect(I, SI))
Chris Lattner2eefe512004-04-09 19:05:30 +00003798 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00003799 if (isa<PHINode>(Op0))
3800 if (Instruction *NV = FoldOpIntoPhi(I))
3801 return NV;
Chris Lattner3f5b8772002-05-06 16:14:14 +00003802 }
3803
Dan Gohman186a6362009-08-12 16:04:34 +00003804 if (Value *X = dyn_castNotVal(Op0)) // ~A ^ A == -1
Chris Lattnera2881962003-02-18 19:28:33 +00003805 if (X == Op1)
Owen Andersona7235ea2009-07-31 20:28:14 +00003806 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00003807
Dan Gohman186a6362009-08-12 16:04:34 +00003808 if (Value *X = dyn_castNotVal(Op1)) // A ^ ~A == -1
Chris Lattnera2881962003-02-18 19:28:33 +00003809 if (X == Op0)
Owen Andersona7235ea2009-07-31 20:28:14 +00003810 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00003811
Chris Lattner318bf792007-03-18 22:51:34 +00003812
3813 BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1);
3814 if (Op1I) {
3815 Value *A, *B;
Dan Gohman4ae51262009-08-12 16:23:25 +00003816 if (match(Op1I, m_Or(m_Value(A), m_Value(B)))) {
Chris Lattner318bf792007-03-18 22:51:34 +00003817 if (A == Op0) { // B^(B|A) == (A|B)^B
Chris Lattner64daab52006-04-01 08:03:55 +00003818 Op1I->swapOperands();
Chris Lattnercb40a372003-03-10 18:24:17 +00003819 I.swapOperands();
3820 std::swap(Op0, Op1);
Chris Lattner318bf792007-03-18 22:51:34 +00003821 } else if (B == Op0) { // B^(A|B) == (A|B)^B
Chris Lattner64daab52006-04-01 08:03:55 +00003822 I.swapOperands(); // Simplified below.
Chris Lattnercb40a372003-03-10 18:24:17 +00003823 std::swap(Op0, Op1);
Misha Brukmanfd939082005-04-21 23:48:37 +00003824 }
Dan Gohman4ae51262009-08-12 16:23:25 +00003825 } else if (match(Op1I, m_Xor(m_Specific(Op0), m_Value(B)))) {
Chris Lattnercb504b92008-11-16 05:38:51 +00003826 return ReplaceInstUsesWith(I, B); // A^(A^B) == B
Dan Gohman4ae51262009-08-12 16:23:25 +00003827 } else if (match(Op1I, m_Xor(m_Value(A), m_Specific(Op0)))) {
Chris Lattnercb504b92008-11-16 05:38:51 +00003828 return ReplaceInstUsesWith(I, A); // A^(B^A) == B
Dan Gohman4ae51262009-08-12 16:23:25 +00003829 } else if (match(Op1I, m_And(m_Value(A), m_Value(B))) &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00003830 Op1I->hasOneUse()){
Chris Lattner6abbdf92007-04-01 05:36:37 +00003831 if (A == Op0) { // A^(A&B) -> A^(B&A)
Chris Lattner64daab52006-04-01 08:03:55 +00003832 Op1I->swapOperands();
Chris Lattner6abbdf92007-04-01 05:36:37 +00003833 std::swap(A, B);
3834 }
Chris Lattner318bf792007-03-18 22:51:34 +00003835 if (B == Op0) { // A^(B&A) -> (B&A)^A
Chris Lattner64daab52006-04-01 08:03:55 +00003836 I.swapOperands(); // Simplified below.
3837 std::swap(Op0, Op1);
3838 }
Chris Lattner26ca7e12004-02-16 03:54:20 +00003839 }
Chris Lattner318bf792007-03-18 22:51:34 +00003840 }
3841
3842 BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0);
3843 if (Op0I) {
3844 Value *A, *B;
Dan Gohman4ae51262009-08-12 16:23:25 +00003845 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00003846 Op0I->hasOneUse()) {
Chris Lattner318bf792007-03-18 22:51:34 +00003847 if (A == Op1) // (B|A)^B == (A|B)^B
3848 std::swap(A, B);
Chris Lattner74381062009-08-30 07:44:24 +00003849 if (B == Op1) // (A|B)^B == A & ~B
3850 return BinaryOperator::CreateAnd(A, Builder->CreateNot(Op1, "tmp"));
Dan Gohman4ae51262009-08-12 16:23:25 +00003851 } else if (match(Op0I, m_Xor(m_Specific(Op1), m_Value(B)))) {
Chris Lattnercb504b92008-11-16 05:38:51 +00003852 return ReplaceInstUsesWith(I, B); // (A^B)^A == B
Dan Gohman4ae51262009-08-12 16:23:25 +00003853 } else if (match(Op0I, m_Xor(m_Value(A), m_Specific(Op1)))) {
Chris Lattnercb504b92008-11-16 05:38:51 +00003854 return ReplaceInstUsesWith(I, A); // (B^A)^A == B
Dan Gohman4ae51262009-08-12 16:23:25 +00003855 } else if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00003856 Op0I->hasOneUse()){
Chris Lattner318bf792007-03-18 22:51:34 +00003857 if (A == Op1) // (A&B)^A -> (B&A)^A
3858 std::swap(A, B);
3859 if (B == Op1 && // (B&A)^A == ~B & A
Chris Lattnerae1ab392006-04-01 22:05:01 +00003860 !isa<ConstantInt>(Op1)) { // Canonical form is (B&C)^C
Chris Lattner74381062009-08-30 07:44:24 +00003861 return BinaryOperator::CreateAnd(Builder->CreateNot(A, "tmp"), Op1);
Chris Lattner64daab52006-04-01 08:03:55 +00003862 }
Chris Lattnercb40a372003-03-10 18:24:17 +00003863 }
Chris Lattner318bf792007-03-18 22:51:34 +00003864 }
3865
3866 // (X >> Z) ^ (Y >> Z) -> (X^Y) >> Z for all shifts.
3867 if (Op0I && Op1I && Op0I->isShift() &&
3868 Op0I->getOpcode() == Op1I->getOpcode() &&
3869 Op0I->getOperand(1) == Op1I->getOperand(1) &&
3870 (Op1I->hasOneUse() || Op1I->hasOneUse())) {
Chris Lattner74381062009-08-30 07:44:24 +00003871 Value *NewOp =
3872 Builder->CreateXor(Op0I->getOperand(0), Op1I->getOperand(0),
3873 Op0I->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003874 return BinaryOperator::Create(Op1I->getOpcode(), NewOp,
Chris Lattner318bf792007-03-18 22:51:34 +00003875 Op1I->getOperand(1));
3876 }
3877
3878 if (Op0I && Op1I) {
3879 Value *A, *B, *C, *D;
3880 // (A & B)^(A | B) -> A ^ B
Dan Gohman4ae51262009-08-12 16:23:25 +00003881 if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
3882 match(Op1I, m_Or(m_Value(C), m_Value(D)))) {
Chris Lattner318bf792007-03-18 22:51:34 +00003883 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003884 return BinaryOperator::CreateXor(A, B);
Chris Lattner318bf792007-03-18 22:51:34 +00003885 }
3886 // (A | B)^(A & B) -> A ^ B
Dan Gohman4ae51262009-08-12 16:23:25 +00003887 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
3888 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
Chris Lattner318bf792007-03-18 22:51:34 +00003889 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003890 return BinaryOperator::CreateXor(A, B);
Chris Lattner318bf792007-03-18 22:51:34 +00003891 }
3892
3893 // (A & B)^(C & D)
3894 if ((Op0I->hasOneUse() || Op1I->hasOneUse()) &&
Dan Gohman4ae51262009-08-12 16:23:25 +00003895 match(Op0I, m_And(m_Value(A), m_Value(B))) &&
3896 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
Chris Lattner318bf792007-03-18 22:51:34 +00003897 // (X & Y)^(X & Y) -> (Y^Z) & X
3898 Value *X = 0, *Y = 0, *Z = 0;
3899 if (A == C)
3900 X = A, Y = B, Z = D;
3901 else if (A == D)
3902 X = A, Y = B, Z = C;
3903 else if (B == C)
3904 X = B, Y = A, Z = D;
3905 else if (B == D)
3906 X = B, Y = A, Z = C;
3907
3908 if (X) {
Chris Lattner74381062009-08-30 07:44:24 +00003909 Value *NewOp = Builder->CreateXor(Y, Z, Op0->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003910 return BinaryOperator::CreateAnd(NewOp, X);
Chris Lattner318bf792007-03-18 22:51:34 +00003911 }
3912 }
3913 }
3914
Reid Spencere4d87aa2006-12-23 06:05:41 +00003915 // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
3916 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
Dan Gohman186a6362009-08-12 16:04:34 +00003917 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003918 return R;
3919
Chris Lattner6fc205f2006-05-05 06:39:07 +00003920 // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
Chris Lattner99c65742007-10-24 05:38:08 +00003921 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Chris Lattner6fc205f2006-05-05 06:39:07 +00003922 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00003923 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
3924 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner42a75512007-01-15 02:27:26 +00003925 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00003926 // Only do this if the casts both really cause code to be generated.
Reid Spencere4d87aa2006-12-23 06:05:41 +00003927 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
Chris Lattner80f43d32010-01-04 07:53:58 +00003928 I.getType()) &&
Reid Spencere4d87aa2006-12-23 06:05:41 +00003929 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
Chris Lattner80f43d32010-01-04 07:53:58 +00003930 I.getType())) {
Chris Lattner74381062009-08-30 07:44:24 +00003931 Value *NewOp = Builder->CreateXor(Op0C->getOperand(0),
3932 Op1C->getOperand(0), I.getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003933 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00003934 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00003935 }
Chris Lattner99c65742007-10-24 05:38:08 +00003936 }
Nick Lewycky517e1f52008-05-31 19:01:33 +00003937
Chris Lattner7e708292002-06-25 16:13:24 +00003938 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00003939}
3940
Chris Lattner3f5b8772002-05-06 16:14:14 +00003941
Reid Spencer832254e2007-02-02 02:16:23 +00003942Instruction *InstCombiner::visitShl(BinaryOperator &I) {
3943 return commonShiftTransforms(I);
3944}
3945
3946Instruction *InstCombiner::visitLShr(BinaryOperator &I) {
3947 return commonShiftTransforms(I);
3948}
3949
3950Instruction *InstCombiner::visitAShr(BinaryOperator &I) {
Chris Lattner348f6652007-12-06 01:59:46 +00003951 if (Instruction *R = commonShiftTransforms(I))
3952 return R;
3953
3954 Value *Op0 = I.getOperand(0);
3955
3956 // ashr int -1, X = -1 (for any arithmetic shift rights of ~0)
3957 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
3958 if (CSI->isAllOnesValue())
3959 return ReplaceInstUsesWith(I, CSI);
Dan Gohman0001e562009-02-24 02:00:40 +00003960
Dan Gohmanc6ac3222009-06-16 19:55:29 +00003961 // See if we can turn a signed shr into an unsigned shr.
3962 if (MaskedValueIsZero(Op0,
3963 APInt::getSignBit(I.getType()->getScalarSizeInBits())))
3964 return BinaryOperator::CreateLShr(Op0, I.getOperand(1));
3965
3966 // Arithmetic shifting an all-sign-bit value is a no-op.
3967 unsigned NumSignBits = ComputeNumSignBits(Op0);
3968 if (NumSignBits == Op0->getType()->getScalarSizeInBits())
3969 return ReplaceInstUsesWith(I, Op0);
Dan Gohman0001e562009-02-24 02:00:40 +00003970
Chris Lattner348f6652007-12-06 01:59:46 +00003971 return 0;
Reid Spencer832254e2007-02-02 02:16:23 +00003972}
3973
3974Instruction *InstCombiner::commonShiftTransforms(BinaryOperator &I) {
3975 assert(I.getOperand(1)->getType() == I.getOperand(0)->getType());
Chris Lattner7e708292002-06-25 16:13:24 +00003976 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00003977
3978 // shl X, 0 == X and shr X, 0 == X
3979 // shl 0, X == 0 and shr 0, X == 0
Owen Andersona7235ea2009-07-31 20:28:14 +00003980 if (Op1 == Constant::getNullValue(Op1->getType()) ||
3981 Op0 == Constant::getNullValue(Op0->getType()))
Chris Lattner233f7dc2002-08-12 21:17:25 +00003982 return ReplaceInstUsesWith(I, Op0);
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00003983
Reid Spencere4d87aa2006-12-23 06:05:41 +00003984 if (isa<UndefValue>(Op0)) {
3985 if (I.getOpcode() == Instruction::AShr) // undef >>s X -> undef
Chris Lattner79a564c2004-10-16 23:28:04 +00003986 return ReplaceInstUsesWith(I, Op0);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003987 else // undef << X -> 0, undef >>u X -> 0
Owen Andersona7235ea2009-07-31 20:28:14 +00003988 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00003989 }
3990 if (isa<UndefValue>(Op1)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00003991 if (I.getOpcode() == Instruction::AShr) // X >>s undef -> X
3992 return ReplaceInstUsesWith(I, Op0);
3993 else // X << undef, X >>u undef -> 0
Owen Andersona7235ea2009-07-31 20:28:14 +00003994 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00003995 }
3996
Dan Gohman9004c8a2009-05-21 02:28:33 +00003997 // See if we can fold away this shift.
Dan Gohman6de29f82009-06-15 22:12:54 +00003998 if (SimplifyDemandedInstructionBits(I))
Dan Gohman9004c8a2009-05-21 02:28:33 +00003999 return &I;
4000
Chris Lattner2eefe512004-04-09 19:05:30 +00004001 // Try to fold constant and into select arguments.
4002 if (isa<Constant>(Op0))
4003 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner80f43d32010-01-04 07:53:58 +00004004 if (Instruction *R = FoldOpIntoSelect(I, SI))
Chris Lattner2eefe512004-04-09 19:05:30 +00004005 return R;
4006
Reid Spencerb83eb642006-10-20 07:07:24 +00004007 if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
Reid Spencerc5b206b2006-12-31 05:48:39 +00004008 if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
4009 return Res;
Chris Lattner4d5542c2006-01-06 07:12:35 +00004010 return 0;
4011}
4012
Reid Spencerb83eb642006-10-20 07:07:24 +00004013Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
Reid Spencer832254e2007-02-02 02:16:23 +00004014 BinaryOperator &I) {
Chris Lattner4598c942009-01-31 08:24:16 +00004015 bool isLeftShift = I.getOpcode() == Instruction::Shl;
Chris Lattner4d5542c2006-01-06 07:12:35 +00004016
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00004017 // See if we can simplify any instructions used by the instruction whose sole
4018 // purpose is to compute bits we don't care about.
Dan Gohmanc6ac3222009-06-16 19:55:29 +00004019 uint32_t TypeBits = Op0->getType()->getScalarSizeInBits();
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00004020
Dan Gohmana119de82009-06-14 23:30:43 +00004021 // shl i32 X, 32 = 0 and srl i8 Y, 9 = 0, ... just don't eliminate
4022 // a signed shift.
Chris Lattner4d5542c2006-01-06 07:12:35 +00004023 //
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00004024 if (Op1->uge(TypeBits)) {
Chris Lattner0737c242007-02-02 05:29:55 +00004025 if (I.getOpcode() != Instruction::AShr)
Owen Andersona7235ea2009-07-31 20:28:14 +00004026 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
Chris Lattner4d5542c2006-01-06 07:12:35 +00004027 else {
Owen Andersoneed707b2009-07-24 23:12:02 +00004028 I.setOperand(1, ConstantInt::get(I.getType(), TypeBits-1));
Chris Lattner4d5542c2006-01-06 07:12:35 +00004029 return &I;
Chris Lattner8adac752004-02-23 20:30:06 +00004030 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00004031 }
4032
4033 // ((X*C1) << C2) == (X * (C1 << C2))
4034 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
4035 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
4036 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004037 return BinaryOperator::CreateMul(BO->getOperand(0),
Owen Andersonbaf3c402009-07-29 18:55:55 +00004038 ConstantExpr::getShl(BOOp, Op1));
Chris Lattner4d5542c2006-01-06 07:12:35 +00004039
4040 // Try to fold constant and into select arguments.
4041 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner80f43d32010-01-04 07:53:58 +00004042 if (Instruction *R = FoldOpIntoSelect(I, SI))
Chris Lattner4d5542c2006-01-06 07:12:35 +00004043 return R;
4044 if (isa<PHINode>(Op0))
4045 if (Instruction *NV = FoldOpIntoPhi(I))
4046 return NV;
4047
Chris Lattner8999dd32007-12-22 09:07:47 +00004048 // Fold shift2(trunc(shift1(x,c1)), c2) -> trunc(shift2(shift1(x,c1),c2))
4049 if (TruncInst *TI = dyn_cast<TruncInst>(Op0)) {
4050 Instruction *TrOp = dyn_cast<Instruction>(TI->getOperand(0));
4051 // If 'shift2' is an ashr, we would have to get the sign bit into a funny
4052 // place. Don't try to do this transformation in this case. Also, we
4053 // require that the input operand is a shift-by-constant so that we have
4054 // confidence that the shifts will get folded together. We could do this
4055 // xform in more cases, but it is unlikely to be profitable.
4056 if (TrOp && I.isLogicalShift() && TrOp->isShift() &&
4057 isa<ConstantInt>(TrOp->getOperand(1))) {
4058 // Okay, we'll do this xform. Make the shift of shift.
Owen Andersonbaf3c402009-07-29 18:55:55 +00004059 Constant *ShAmt = ConstantExpr::getZExt(Op1, TrOp->getType());
Chris Lattner74381062009-08-30 07:44:24 +00004060 // (shift2 (shift1 & 0x00FF), c2)
4061 Value *NSh = Builder->CreateBinOp(I.getOpcode(), TrOp, ShAmt,I.getName());
Chris Lattner8999dd32007-12-22 09:07:47 +00004062
4063 // For logical shifts, the truncation has the effect of making the high
4064 // part of the register be zeros. Emulate this by inserting an AND to
4065 // clear the top bits as needed. This 'and' will usually be zapped by
4066 // other xforms later if dead.
Dan Gohmanc6ac3222009-06-16 19:55:29 +00004067 unsigned SrcSize = TrOp->getType()->getScalarSizeInBits();
4068 unsigned DstSize = TI->getType()->getScalarSizeInBits();
Chris Lattner8999dd32007-12-22 09:07:47 +00004069 APInt MaskV(APInt::getLowBitsSet(SrcSize, DstSize));
4070
4071 // The mask we constructed says what the trunc would do if occurring
4072 // between the shifts. We want to know the effect *after* the second
4073 // shift. We know that it is a logical shift by a constant, so adjust the
4074 // mask as appropriate.
4075 if (I.getOpcode() == Instruction::Shl)
4076 MaskV <<= Op1->getZExtValue();
4077 else {
4078 assert(I.getOpcode() == Instruction::LShr && "Unknown logical shift");
4079 MaskV = MaskV.lshr(Op1->getZExtValue());
4080 }
4081
Chris Lattner74381062009-08-30 07:44:24 +00004082 // shift1 & 0x00FF
Chris Lattner4de84762010-01-04 07:02:48 +00004083 Value *And = Builder->CreateAnd(NSh,
4084 ConstantInt::get(I.getContext(), MaskV),
Chris Lattner74381062009-08-30 07:44:24 +00004085 TI->getName());
Chris Lattner8999dd32007-12-22 09:07:47 +00004086
4087 // Return the value truncated to the interesting size.
4088 return new TruncInst(And, I.getType());
4089 }
4090 }
4091
Chris Lattner4d5542c2006-01-06 07:12:35 +00004092 if (Op0->hasOneUse()) {
Chris Lattner4d5542c2006-01-06 07:12:35 +00004093 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
4094 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
4095 Value *V1, *V2;
4096 ConstantInt *CC;
4097 switch (Op0BO->getOpcode()) {
Chris Lattner11021cb2005-09-18 05:12:10 +00004098 default: break;
4099 case Instruction::Add:
4100 case Instruction::And:
4101 case Instruction::Or:
Reid Spencera07cb7d2007-02-02 14:41:37 +00004102 case Instruction::Xor: {
Chris Lattner11021cb2005-09-18 05:12:10 +00004103 // These operators commute.
4104 // Turn (Y + (X >> C)) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00004105 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004106 match(Op0BO->getOperand(1), m_Shr(m_Value(V1),
Chris Lattnerf925cbd2009-08-30 18:50:58 +00004107 m_Specific(Op1)))) {
4108 Value *YS = // (Y << C)
4109 Builder->CreateShl(Op0BO->getOperand(0), Op1, Op0BO->getName());
4110 // (X + (Y << C))
4111 Value *X = Builder->CreateBinOp(Op0BO->getOpcode(), YS, V1,
4112 Op0BO->getOperand(1)->getName());
Zhou Sheng302748d2007-03-30 17:20:39 +00004113 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
Chris Lattner4de84762010-01-04 07:02:48 +00004114 return BinaryOperator::CreateAnd(X, ConstantInt::get(I.getContext(),
Zhou Sheng90b96812007-03-30 05:45:18 +00004115 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
Chris Lattner150f12a2005-09-18 06:30:59 +00004116 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00004117
Chris Lattner150f12a2005-09-18 06:30:59 +00004118 // Turn (Y + ((X >> C) & CC)) << C -> ((X & (CC << C)) + (Y << C))
Reid Spencera07cb7d2007-02-02 14:41:37 +00004119 Value *Op0BOOp1 = Op0BO->getOperand(1);
Chris Lattner3c698492007-03-05 00:11:19 +00004120 if (isLeftShift && Op0BOOp1->hasOneUse() &&
Reid Spencera07cb7d2007-02-02 14:41:37 +00004121 match(Op0BOOp1,
Chris Lattnercb504b92008-11-16 05:38:51 +00004122 m_And(m_Shr(m_Value(V1), m_Specific(Op1)),
Dan Gohman4ae51262009-08-12 16:23:25 +00004123 m_ConstantInt(CC))) &&
Chris Lattnercb504b92008-11-16 05:38:51 +00004124 cast<BinaryOperator>(Op0BOOp1)->getOperand(0)->hasOneUse()) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +00004125 Value *YS = // (Y << C)
4126 Builder->CreateShl(Op0BO->getOperand(0), Op1,
4127 Op0BO->getName());
4128 // X & (CC << C)
4129 Value *XM = Builder->CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
4130 V1->getName()+".mask");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004131 return BinaryOperator::Create(Op0BO->getOpcode(), YS, XM);
Chris Lattner150f12a2005-09-18 06:30:59 +00004132 }
Reid Spencera07cb7d2007-02-02 14:41:37 +00004133 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00004134
Reid Spencera07cb7d2007-02-02 14:41:37 +00004135 // FALL THROUGH.
4136 case Instruction::Sub: {
Chris Lattner11021cb2005-09-18 05:12:10 +00004137 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00004138 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004139 match(Op0BO->getOperand(0), m_Shr(m_Value(V1),
Dan Gohman4ae51262009-08-12 16:23:25 +00004140 m_Specific(Op1)))) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +00004141 Value *YS = // (Y << C)
4142 Builder->CreateShl(Op0BO->getOperand(1), Op1, Op0BO->getName());
4143 // (X + (Y << C))
4144 Value *X = Builder->CreateBinOp(Op0BO->getOpcode(), V1, YS,
4145 Op0BO->getOperand(0)->getName());
Zhou Sheng302748d2007-03-30 17:20:39 +00004146 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
Chris Lattner4de84762010-01-04 07:02:48 +00004147 return BinaryOperator::CreateAnd(X, ConstantInt::get(I.getContext(),
Zhou Sheng90b96812007-03-30 05:45:18 +00004148 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
Chris Lattner150f12a2005-09-18 06:30:59 +00004149 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00004150
Chris Lattner13d4ab42006-05-31 21:14:00 +00004151 // Turn (((X >> C)&CC) + Y) << C -> (X + (Y << C)) & (CC << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00004152 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
4153 match(Op0BO->getOperand(0),
4154 m_And(m_Shr(m_Value(V1), m_Value(V2)),
Dan Gohman4ae51262009-08-12 16:23:25 +00004155 m_ConstantInt(CC))) && V2 == Op1 &&
Chris Lattner9a4cacb2006-02-09 07:41:14 +00004156 cast<BinaryOperator>(Op0BO->getOperand(0))
4157 ->getOperand(0)->hasOneUse()) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +00004158 Value *YS = // (Y << C)
4159 Builder->CreateShl(Op0BO->getOperand(1), Op1, Op0BO->getName());
4160 // X & (CC << C)
4161 Value *XM = Builder->CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
4162 V1->getName()+".mask");
Chris Lattner150f12a2005-09-18 06:30:59 +00004163
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004164 return BinaryOperator::Create(Op0BO->getOpcode(), XM, YS);
Chris Lattner150f12a2005-09-18 06:30:59 +00004165 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00004166
Chris Lattner11021cb2005-09-18 05:12:10 +00004167 break;
Reid Spencera07cb7d2007-02-02 14:41:37 +00004168 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00004169 }
4170
4171
4172 // If the operand is an bitwise operator with a constant RHS, and the
4173 // shift is the only use, we can pull it out of the shift.
4174 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
4175 bool isValid = true; // Valid only for And, Or, Xor
4176 bool highBitSet = false; // Transform if high bit of constant set?
4177
4178 switch (Op0BO->getOpcode()) {
Chris Lattnerdf17af12003-08-12 21:53:41 +00004179 default: isValid = false; break; // Do not perform transform!
Chris Lattner1f7e1602004-10-08 03:46:20 +00004180 case Instruction::Add:
4181 isValid = isLeftShift;
4182 break;
Chris Lattnerdf17af12003-08-12 21:53:41 +00004183 case Instruction::Or:
4184 case Instruction::Xor:
4185 highBitSet = false;
4186 break;
4187 case Instruction::And:
4188 highBitSet = true;
4189 break;
Chris Lattner4d5542c2006-01-06 07:12:35 +00004190 }
4191
4192 // If this is a signed shift right, and the high bit is modified
4193 // by the logical operation, do not perform the transformation.
4194 // The highBitSet boolean indicates the value of the high bit of
4195 // the constant which would cause it to be modified for this
4196 // operation.
4197 //
Chris Lattnerc95ba442007-12-06 06:25:04 +00004198 if (isValid && I.getOpcode() == Instruction::AShr)
Zhou Shenge9e03f62007-03-28 15:02:20 +00004199 isValid = Op0C->getValue()[TypeBits-1] == highBitSet;
Chris Lattner4d5542c2006-01-06 07:12:35 +00004200
4201 if (isValid) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00004202 Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
Chris Lattner4d5542c2006-01-06 07:12:35 +00004203
Chris Lattnerf925cbd2009-08-30 18:50:58 +00004204 Value *NewShift =
4205 Builder->CreateBinOp(I.getOpcode(), Op0BO->getOperand(0), Op1);
Chris Lattner6934a042007-02-11 01:23:03 +00004206 NewShift->takeName(Op0BO);
Chris Lattner4d5542c2006-01-06 07:12:35 +00004207
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004208 return BinaryOperator::Create(Op0BO->getOpcode(), NewShift,
Chris Lattner4d5542c2006-01-06 07:12:35 +00004209 NewRHS);
4210 }
4211 }
4212 }
4213 }
4214
Chris Lattnerad0124c2006-01-06 07:52:12 +00004215 // Find out if this is a shift of a shift by a constant.
Reid Spencer832254e2007-02-02 02:16:23 +00004216 BinaryOperator *ShiftOp = dyn_cast<BinaryOperator>(Op0);
4217 if (ShiftOp && !ShiftOp->isShift())
4218 ShiftOp = 0;
Chris Lattnerad0124c2006-01-06 07:52:12 +00004219
Reid Spencerb83eb642006-10-20 07:07:24 +00004220 if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
Reid Spencerb83eb642006-10-20 07:07:24 +00004221 ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00004222 uint32_t ShiftAmt1 = ShiftAmt1C->getLimitedValue(TypeBits);
4223 uint32_t ShiftAmt2 = Op1->getLimitedValue(TypeBits);
Chris Lattnerb87056f2007-02-05 00:57:54 +00004224 assert(ShiftAmt2 != 0 && "Should have been simplified earlier");
4225 if (ShiftAmt1 == 0) return 0; // Will be simplified in the future.
4226 Value *X = ShiftOp->getOperand(0);
Chris Lattnerad0124c2006-01-06 07:52:12 +00004227
Zhou Sheng4351c642007-04-02 08:20:41 +00004228 uint32_t AmtSum = ShiftAmt1+ShiftAmt2; // Fold into one big shift.
Chris Lattnerb87056f2007-02-05 00:57:54 +00004229
4230 const IntegerType *Ty = cast<IntegerType>(I.getType());
4231
4232 // Check for (X << c1) << c2 and (X >> c1) >> c2
Chris Lattner7f3da2d2007-02-03 23:28:07 +00004233 if (I.getOpcode() == ShiftOp->getOpcode()) {
Chris Lattner344c7c52009-03-20 22:41:15 +00004234 // If this is oversized composite shift, then unsigned shifts get 0, ashr
4235 // saturates.
4236 if (AmtSum >= TypeBits) {
4237 if (I.getOpcode() != Instruction::AShr)
Owen Andersona7235ea2009-07-31 20:28:14 +00004238 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner344c7c52009-03-20 22:41:15 +00004239 AmtSum = TypeBits-1; // Saturate to 31 for i32 ashr.
4240 }
4241
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004242 return BinaryOperator::Create(I.getOpcode(), X,
Owen Andersoneed707b2009-07-24 23:12:02 +00004243 ConstantInt::get(Ty, AmtSum));
Chris Lattnerf925cbd2009-08-30 18:50:58 +00004244 }
4245
4246 if (ShiftOp->getOpcode() == Instruction::LShr &&
4247 I.getOpcode() == Instruction::AShr) {
Chris Lattner344c7c52009-03-20 22:41:15 +00004248 if (AmtSum >= TypeBits)
Owen Andersona7235ea2009-07-31 20:28:14 +00004249 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner344c7c52009-03-20 22:41:15 +00004250
Chris Lattnerb87056f2007-02-05 00:57:54 +00004251 // ((X >>u C1) >>s C2) -> (X >>u (C1+C2)) since C1 != 0.
Owen Andersoneed707b2009-07-24 23:12:02 +00004252 return BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, AmtSum));
Chris Lattnerf925cbd2009-08-30 18:50:58 +00004253 }
4254
4255 if (ShiftOp->getOpcode() == Instruction::AShr &&
4256 I.getOpcode() == Instruction::LShr) {
Chris Lattnerb87056f2007-02-05 00:57:54 +00004257 // ((X >>s C1) >>u C2) -> ((X >>s (C1+C2)) & mask) since C1 != 0.
Chris Lattner344c7c52009-03-20 22:41:15 +00004258 if (AmtSum >= TypeBits)
4259 AmtSum = TypeBits-1;
4260
Chris Lattnerf925cbd2009-08-30 18:50:58 +00004261 Value *Shift = Builder->CreateAShr(X, ConstantInt::get(Ty, AmtSum));
Chris Lattnerb87056f2007-02-05 00:57:54 +00004262
Zhou Shenge9e03f62007-03-28 15:02:20 +00004263 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Chris Lattner4de84762010-01-04 07:02:48 +00004264 return BinaryOperator::CreateAnd(Shift,
4265 ConstantInt::get(I.getContext(), Mask));
Chris Lattnerad0124c2006-01-06 07:52:12 +00004266 }
4267
Chris Lattnerb87056f2007-02-05 00:57:54 +00004268 // Okay, if we get here, one shift must be left, and the other shift must be
4269 // right. See if the amounts are equal.
4270 if (ShiftAmt1 == ShiftAmt2) {
4271 // If we have ((X >>? C) << C), turn this into X & (-1 << C).
4272 if (I.getOpcode() == Instruction::Shl) {
Reid Spencer55702aa2007-03-25 21:11:44 +00004273 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt1));
Chris Lattner4de84762010-01-04 07:02:48 +00004274 return BinaryOperator::CreateAnd(X,
4275 ConstantInt::get(I.getContext(),Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00004276 }
4277 // If we have ((X << C) >>u C), turn this into X & (-1 >>u C).
4278 if (I.getOpcode() == Instruction::LShr) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00004279 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt1));
Chris Lattner4de84762010-01-04 07:02:48 +00004280 return BinaryOperator::CreateAnd(X,
4281 ConstantInt::get(I.getContext(), Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00004282 }
4283 // We can simplify ((X << C) >>s C) into a trunc + sext.
4284 // NOTE: we could do this for any C, but that would make 'unusual' integer
4285 // types. For now, just stick to ones well-supported by the code
4286 // generators.
4287 const Type *SExtType = 0;
4288 switch (Ty->getBitWidth() - ShiftAmt1) {
Zhou Shenge9e03f62007-03-28 15:02:20 +00004289 case 1 :
4290 case 8 :
4291 case 16 :
4292 case 32 :
4293 case 64 :
4294 case 128:
Chris Lattner4de84762010-01-04 07:02:48 +00004295 SExtType = IntegerType::get(I.getContext(),
4296 Ty->getBitWidth() - ShiftAmt1);
Zhou Shenge9e03f62007-03-28 15:02:20 +00004297 break;
Chris Lattnerb87056f2007-02-05 00:57:54 +00004298 default: break;
4299 }
Chris Lattnerf925cbd2009-08-30 18:50:58 +00004300 if (SExtType)
4301 return new SExtInst(Builder->CreateTrunc(X, SExtType, "sext"), Ty);
Chris Lattnerb87056f2007-02-05 00:57:54 +00004302 // Otherwise, we can't handle it yet.
4303 } else if (ShiftAmt1 < ShiftAmt2) {
Zhou Sheng4351c642007-04-02 08:20:41 +00004304 uint32_t ShiftDiff = ShiftAmt2-ShiftAmt1;
Chris Lattnerad0124c2006-01-06 07:52:12 +00004305
Chris Lattnerb0b991a2007-02-05 05:57:49 +00004306 // (X >>? C1) << C2 --> X << (C2-C1) & (-1 << C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00004307 if (I.getOpcode() == Instruction::Shl) {
4308 assert(ShiftOp->getOpcode() == Instruction::LShr ||
4309 ShiftOp->getOpcode() == Instruction::AShr);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00004310 Value *Shift = Builder->CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
Chris Lattnere8d56c52006-01-07 01:32:28 +00004311
Reid Spencer55702aa2007-03-25 21:11:44 +00004312 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersoneed707b2009-07-24 23:12:02 +00004313 return BinaryOperator::CreateAnd(Shift,
Chris Lattner4de84762010-01-04 07:02:48 +00004314 ConstantInt::get(I.getContext(),Mask));
Chris Lattnerad0124c2006-01-06 07:52:12 +00004315 }
Chris Lattnerb87056f2007-02-05 00:57:54 +00004316
Chris Lattnerb0b991a2007-02-05 05:57:49 +00004317 // (X << C1) >>u C2 --> X >>u (C2-C1) & (-1 >> C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00004318 if (I.getOpcode() == Instruction::LShr) {
4319 assert(ShiftOp->getOpcode() == Instruction::Shl);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00004320 Value *Shift = Builder->CreateLShr(X, ConstantInt::get(Ty, ShiftDiff));
Chris Lattnerad0124c2006-01-06 07:52:12 +00004321
Reid Spencerd5e30f02007-03-26 17:18:58 +00004322 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersoneed707b2009-07-24 23:12:02 +00004323 return BinaryOperator::CreateAnd(Shift,
Chris Lattner4de84762010-01-04 07:02:48 +00004324 ConstantInt::get(I.getContext(),Mask));
Chris Lattner11021cb2005-09-18 05:12:10 +00004325 }
Chris Lattnerb87056f2007-02-05 00:57:54 +00004326
4327 // We can't handle (X << C1) >>s C2, it shifts arbitrary bits in.
4328 } else {
4329 assert(ShiftAmt2 < ShiftAmt1);
Zhou Sheng4351c642007-04-02 08:20:41 +00004330 uint32_t ShiftDiff = ShiftAmt1-ShiftAmt2;
Chris Lattnerb87056f2007-02-05 00:57:54 +00004331
Chris Lattnerb0b991a2007-02-05 05:57:49 +00004332 // (X >>? C1) << C2 --> X >>? (C1-C2) & (-1 << C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00004333 if (I.getOpcode() == Instruction::Shl) {
4334 assert(ShiftOp->getOpcode() == Instruction::LShr ||
4335 ShiftOp->getOpcode() == Instruction::AShr);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00004336 Value *Shift = Builder->CreateBinOp(ShiftOp->getOpcode(), X,
4337 ConstantInt::get(Ty, ShiftDiff));
Chris Lattnerb87056f2007-02-05 00:57:54 +00004338
Reid Spencer55702aa2007-03-25 21:11:44 +00004339 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersoneed707b2009-07-24 23:12:02 +00004340 return BinaryOperator::CreateAnd(Shift,
Chris Lattner4de84762010-01-04 07:02:48 +00004341 ConstantInt::get(I.getContext(),Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00004342 }
4343
Chris Lattnerb0b991a2007-02-05 05:57:49 +00004344 // (X << C1) >>u C2 --> X << (C1-C2) & (-1 >> C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00004345 if (I.getOpcode() == Instruction::LShr) {
4346 assert(ShiftOp->getOpcode() == Instruction::Shl);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00004347 Value *Shift = Builder->CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
Chris Lattnerb87056f2007-02-05 00:57:54 +00004348
Reid Spencer68d27cf2007-03-26 23:45:51 +00004349 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersoneed707b2009-07-24 23:12:02 +00004350 return BinaryOperator::CreateAnd(Shift,
Chris Lattner4de84762010-01-04 07:02:48 +00004351 ConstantInt::get(I.getContext(),Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00004352 }
4353
4354 // We can't handle (X << C1) >>a C2, it shifts arbitrary bits in.
Chris Lattner6e7ba452005-01-01 16:22:27 +00004355 }
Chris Lattnerad0124c2006-01-06 07:52:12 +00004356 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00004357 return 0;
4358}
4359
Chris Lattnera1be5662002-05-02 17:06:02 +00004360
Reid Spencer3da59db2006-11-27 01:05:10 +00004361
Chris Lattner46cd5a12009-01-09 05:44:56 +00004362/// FindElementAtOffset - Given a type and a constant offset, determine whether
4363/// or not there is a sequence of GEP indices into the type that will land us at
Chris Lattner3914f722009-01-24 01:00:13 +00004364/// the specified offset. If so, fill them into NewIndices and return the
4365/// resultant element type, otherwise return null.
Chris Lattner80f43d32010-01-04 07:53:58 +00004366const Type *InstCombiner::FindElementAtOffset(const Type *Ty, int64_t Offset,
4367 SmallVectorImpl<Value*> &NewIndices) {
Dan Gohmance9fe9f2009-07-21 23:21:54 +00004368 if (!TD) return 0;
Chris Lattner3914f722009-01-24 01:00:13 +00004369 if (!Ty->isSized()) return 0;
Chris Lattner46cd5a12009-01-09 05:44:56 +00004370
4371 // Start with the index over the outer type. Note that the type size
4372 // might be zero (even if the offset isn't zero) if the indexed type
4373 // is something like [0 x {int, int}]
Chris Lattner4de84762010-01-04 07:02:48 +00004374 const Type *IntPtrTy = TD->getIntPtrType(Ty->getContext());
Chris Lattner46cd5a12009-01-09 05:44:56 +00004375 int64_t FirstIdx = 0;
Duncan Sands777d2302009-05-09 07:06:46 +00004376 if (int64_t TySize = TD->getTypeAllocSize(Ty)) {
Chris Lattner46cd5a12009-01-09 05:44:56 +00004377 FirstIdx = Offset/TySize;
Chris Lattner31a69cb2009-01-11 20:41:36 +00004378 Offset -= FirstIdx*TySize;
Chris Lattner46cd5a12009-01-09 05:44:56 +00004379
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00004380 // Handle hosts where % returns negative instead of values [0..TySize).
Chris Lattner46cd5a12009-01-09 05:44:56 +00004381 if (Offset < 0) {
4382 --FirstIdx;
4383 Offset += TySize;
4384 assert(Offset >= 0);
4385 }
4386 assert((uint64_t)Offset < (uint64_t)TySize && "Out of range offset");
4387 }
4388
Owen Andersoneed707b2009-07-24 23:12:02 +00004389 NewIndices.push_back(ConstantInt::get(IntPtrTy, FirstIdx));
Chris Lattner46cd5a12009-01-09 05:44:56 +00004390
4391 // Index into the types. If we fail, set OrigBase to null.
4392 while (Offset) {
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00004393 // Indexing into tail padding between struct/array elements.
4394 if (uint64_t(Offset*8) >= TD->getTypeSizeInBits(Ty))
Chris Lattner3914f722009-01-24 01:00:13 +00004395 return 0;
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00004396
Chris Lattner46cd5a12009-01-09 05:44:56 +00004397 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
4398 const StructLayout *SL = TD->getStructLayout(STy);
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00004399 assert(Offset < (int64_t)SL->getSizeInBytes() &&
4400 "Offset must stay within the indexed type");
4401
Chris Lattner46cd5a12009-01-09 05:44:56 +00004402 unsigned Elt = SL->getElementContainingOffset(Offset);
Chris Lattner4de84762010-01-04 07:02:48 +00004403 NewIndices.push_back(ConstantInt::get(Type::getInt32Ty(Ty->getContext()),
4404 Elt));
Chris Lattner46cd5a12009-01-09 05:44:56 +00004405
4406 Offset -= SL->getElementOffset(Elt);
4407 Ty = STy->getElementType(Elt);
Chris Lattner1c412d92009-01-11 20:23:52 +00004408 } else if (const ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
Duncan Sands777d2302009-05-09 07:06:46 +00004409 uint64_t EltSize = TD->getTypeAllocSize(AT->getElementType());
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00004410 assert(EltSize && "Cannot index into a zero-sized array");
Owen Andersoneed707b2009-07-24 23:12:02 +00004411 NewIndices.push_back(ConstantInt::get(IntPtrTy,Offset/EltSize));
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00004412 Offset %= EltSize;
Chris Lattner1c412d92009-01-11 20:23:52 +00004413 Ty = AT->getElementType();
Chris Lattner46cd5a12009-01-09 05:44:56 +00004414 } else {
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00004415 // Otherwise, we can't index into the middle of this atomic type, bail.
Chris Lattner3914f722009-01-24 01:00:13 +00004416 return 0;
Chris Lattner46cd5a12009-01-09 05:44:56 +00004417 }
4418 }
4419
Chris Lattner3914f722009-01-24 01:00:13 +00004420 return Ty;
Chris Lattner46cd5a12009-01-09 05:44:56 +00004421}
4422
Chris Lattner8a2a3112001-12-14 16:52:21 +00004423
Chris Lattnere576b912004-04-09 23:46:01 +00004424/// GetSelectFoldableOperands - We want to turn code that looks like this:
4425/// %C = or %A, %B
4426/// %D = select %cond, %C, %A
4427/// into:
4428/// %C = select %cond, %B, 0
4429/// %D = or %A, %C
4430///
4431/// Assuming that the specified instruction is an operand to the select, return
4432/// a bitmask indicating which operands of this instruction are foldable if they
4433/// equal the other incoming value of the select.
4434///
4435static unsigned GetSelectFoldableOperands(Instruction *I) {
4436 switch (I->getOpcode()) {
4437 case Instruction::Add:
4438 case Instruction::Mul:
4439 case Instruction::And:
4440 case Instruction::Or:
4441 case Instruction::Xor:
4442 return 3; // Can fold through either operand.
4443 case Instruction::Sub: // Can only fold on the amount subtracted.
4444 case Instruction::Shl: // Can only fold on the shift amount.
Reid Spencer3822ff52006-11-08 06:47:33 +00004445 case Instruction::LShr:
4446 case Instruction::AShr:
Misha Brukmanfd939082005-04-21 23:48:37 +00004447 return 1;
Chris Lattnere576b912004-04-09 23:46:01 +00004448 default:
4449 return 0; // Cannot fold
4450 }
4451}
4452
4453/// GetSelectFoldableConstant - For the same transformation as the previous
4454/// function, return the identity constant that goes into the select.
Chris Lattner4de84762010-01-04 07:02:48 +00004455static Constant *GetSelectFoldableConstant(Instruction *I) {
Chris Lattnere576b912004-04-09 23:46:01 +00004456 switch (I->getOpcode()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004457 default: llvm_unreachable("This cannot happen!");
Chris Lattnere576b912004-04-09 23:46:01 +00004458 case Instruction::Add:
4459 case Instruction::Sub:
4460 case Instruction::Or:
4461 case Instruction::Xor:
Chris Lattnere576b912004-04-09 23:46:01 +00004462 case Instruction::Shl:
Reid Spencer3822ff52006-11-08 06:47:33 +00004463 case Instruction::LShr:
4464 case Instruction::AShr:
Owen Andersona7235ea2009-07-31 20:28:14 +00004465 return Constant::getNullValue(I->getType());
Chris Lattnere576b912004-04-09 23:46:01 +00004466 case Instruction::And:
Owen Andersona7235ea2009-07-31 20:28:14 +00004467 return Constant::getAllOnesValue(I->getType());
Chris Lattnere576b912004-04-09 23:46:01 +00004468 case Instruction::Mul:
Owen Andersoneed707b2009-07-24 23:12:02 +00004469 return ConstantInt::get(I->getType(), 1);
Chris Lattnere576b912004-04-09 23:46:01 +00004470 }
4471}
4472
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00004473/// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
4474/// have the same opcode and only one use each. Try to simplify this.
4475Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
4476 Instruction *FI) {
4477 if (TI->getNumOperands() == 1) {
4478 // If this is a non-volatile load or a cast from the same type,
4479 // merge.
Reid Spencer3da59db2006-11-27 01:05:10 +00004480 if (TI->isCast()) {
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00004481 if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
4482 return 0;
4483 } else {
4484 return 0; // unknown unary op.
4485 }
Misha Brukmanfd939082005-04-21 23:48:37 +00004486
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00004487 // Fold this by inserting a select from the input values.
Gabor Greif051a9502008-04-06 20:25:17 +00004488 SelectInst *NewSI = SelectInst::Create(SI.getCondition(), TI->getOperand(0),
Eric Christophera66297a2009-07-25 02:45:27 +00004489 FI->getOperand(0), SI.getName()+".v");
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00004490 InsertNewInstBefore(NewSI, SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004491 return CastInst::Create(Instruction::CastOps(TI->getOpcode()), NewSI,
Reid Spencer3da59db2006-11-27 01:05:10 +00004492 TI->getType());
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00004493 }
4494
Reid Spencer832254e2007-02-02 02:16:23 +00004495 // Only handle binary operators here.
4496 if (!isa<BinaryOperator>(TI))
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00004497 return 0;
4498
4499 // Figure out if the operations have any operands in common.
4500 Value *MatchOp, *OtherOpT, *OtherOpF;
4501 bool MatchIsOpZero;
4502 if (TI->getOperand(0) == FI->getOperand(0)) {
4503 MatchOp = TI->getOperand(0);
4504 OtherOpT = TI->getOperand(1);
4505 OtherOpF = FI->getOperand(1);
4506 MatchIsOpZero = true;
4507 } else if (TI->getOperand(1) == FI->getOperand(1)) {
4508 MatchOp = TI->getOperand(1);
4509 OtherOpT = TI->getOperand(0);
4510 OtherOpF = FI->getOperand(0);
4511 MatchIsOpZero = false;
4512 } else if (!TI->isCommutative()) {
4513 return 0;
4514 } else if (TI->getOperand(0) == FI->getOperand(1)) {
4515 MatchOp = TI->getOperand(0);
4516 OtherOpT = TI->getOperand(1);
4517 OtherOpF = FI->getOperand(0);
4518 MatchIsOpZero = true;
4519 } else if (TI->getOperand(1) == FI->getOperand(0)) {
4520 MatchOp = TI->getOperand(1);
4521 OtherOpT = TI->getOperand(0);
4522 OtherOpF = FI->getOperand(1);
4523 MatchIsOpZero = true;
4524 } else {
4525 return 0;
4526 }
4527
4528 // If we reach here, they do have operations in common.
Gabor Greif051a9502008-04-06 20:25:17 +00004529 SelectInst *NewSI = SelectInst::Create(SI.getCondition(), OtherOpT,
4530 OtherOpF, SI.getName()+".v");
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00004531 InsertNewInstBefore(NewSI, SI);
4532
4533 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
4534 if (MatchIsOpZero)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004535 return BinaryOperator::Create(BO->getOpcode(), MatchOp, NewSI);
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00004536 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004537 return BinaryOperator::Create(BO->getOpcode(), NewSI, MatchOp);
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00004538 }
Torok Edwinc23197a2009-07-14 16:55:14 +00004539 llvm_unreachable("Shouldn't get here");
Reid Spencera07cb7d2007-02-02 14:41:37 +00004540 return 0;
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00004541}
4542
Evan Chengde621922009-03-31 20:42:45 +00004543static bool isSelect01(Constant *C1, Constant *C2) {
4544 ConstantInt *C1I = dyn_cast<ConstantInt>(C1);
4545 if (!C1I)
4546 return false;
4547 ConstantInt *C2I = dyn_cast<ConstantInt>(C2);
4548 if (!C2I)
4549 return false;
4550 return (C1I->isZero() || C1I->isOne()) && (C2I->isZero() || C2I->isOne());
4551}
4552
4553/// FoldSelectIntoOp - Try fold the select into one of the operands to
4554/// facilitate further optimization.
4555Instruction *InstCombiner::FoldSelectIntoOp(SelectInst &SI, Value *TrueVal,
4556 Value *FalseVal) {
4557 // See the comment above GetSelectFoldableOperands for a description of the
4558 // transformation we are doing here.
4559 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal)) {
4560 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
4561 !isa<Constant>(FalseVal)) {
4562 if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
4563 unsigned OpToFold = 0;
4564 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
4565 OpToFold = 1;
4566 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
4567 OpToFold = 2;
4568 }
4569
4570 if (OpToFold) {
Chris Lattner4de84762010-01-04 07:02:48 +00004571 Constant *C = GetSelectFoldableConstant(TVI);
Evan Chengde621922009-03-31 20:42:45 +00004572 Value *OOp = TVI->getOperand(2-OpToFold);
4573 // Avoid creating select between 2 constants unless it's selecting
4574 // between 0 and 1.
4575 if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
4576 Instruction *NewSel = SelectInst::Create(SI.getCondition(), OOp, C);
4577 InsertNewInstBefore(NewSel, SI);
4578 NewSel->takeName(TVI);
4579 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
4580 return BinaryOperator::Create(BO->getOpcode(), FalseVal, NewSel);
Torok Edwinc23197a2009-07-14 16:55:14 +00004581 llvm_unreachable("Unknown instruction!!");
Evan Chengde621922009-03-31 20:42:45 +00004582 }
4583 }
4584 }
4585 }
4586 }
4587
4588 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal)) {
4589 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
4590 !isa<Constant>(TrueVal)) {
4591 if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
4592 unsigned OpToFold = 0;
4593 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
4594 OpToFold = 1;
4595 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
4596 OpToFold = 2;
4597 }
4598
4599 if (OpToFold) {
Chris Lattner4de84762010-01-04 07:02:48 +00004600 Constant *C = GetSelectFoldableConstant(FVI);
Evan Chengde621922009-03-31 20:42:45 +00004601 Value *OOp = FVI->getOperand(2-OpToFold);
4602 // Avoid creating select between 2 constants unless it's selecting
4603 // between 0 and 1.
4604 if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
4605 Instruction *NewSel = SelectInst::Create(SI.getCondition(), C, OOp);
4606 InsertNewInstBefore(NewSel, SI);
4607 NewSel->takeName(FVI);
4608 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
4609 return BinaryOperator::Create(BO->getOpcode(), TrueVal, NewSel);
Torok Edwinc23197a2009-07-14 16:55:14 +00004610 llvm_unreachable("Unknown instruction!!");
Evan Chengde621922009-03-31 20:42:45 +00004611 }
4612 }
4613 }
4614 }
4615 }
4616
4617 return 0;
4618}
4619
Dan Gohman81b28ce2008-09-16 18:46:06 +00004620/// visitSelectInstWithICmp - Visit a SelectInst that has an
4621/// ICmpInst as its first operand.
4622///
4623Instruction *InstCombiner::visitSelectInstWithICmp(SelectInst &SI,
4624 ICmpInst *ICI) {
4625 bool Changed = false;
4626 ICmpInst::Predicate Pred = ICI->getPredicate();
4627 Value *CmpLHS = ICI->getOperand(0);
4628 Value *CmpRHS = ICI->getOperand(1);
4629 Value *TrueVal = SI.getTrueValue();
4630 Value *FalseVal = SI.getFalseValue();
4631
4632 // Check cases where the comparison is with a constant that
4633 // can be adjusted to fit the min/max idiom. We may edit ICI in
4634 // place here, so make sure the select is the only user.
4635 if (ICI->hasOneUse())
Dan Gohman1975d032008-10-30 20:40:10 +00004636 if (ConstantInt *CI = dyn_cast<ConstantInt>(CmpRHS)) {
Dan Gohman81b28ce2008-09-16 18:46:06 +00004637 switch (Pred) {
4638 default: break;
4639 case ICmpInst::ICMP_ULT:
4640 case ICmpInst::ICMP_SLT: {
4641 // X < MIN ? T : F --> F
4642 if (CI->isMinValue(Pred == ICmpInst::ICMP_SLT))
4643 return ReplaceInstUsesWith(SI, FalseVal);
4644 // X < C ? X : C-1 --> X > C-1 ? C-1 : X
Dan Gohman186a6362009-08-12 16:04:34 +00004645 Constant *AdjustedRHS = SubOne(CI);
Dan Gohman81b28ce2008-09-16 18:46:06 +00004646 if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
4647 (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
4648 Pred = ICmpInst::getSwappedPredicate(Pred);
4649 CmpRHS = AdjustedRHS;
4650 std::swap(FalseVal, TrueVal);
4651 ICI->setPredicate(Pred);
4652 ICI->setOperand(1, CmpRHS);
4653 SI.setOperand(1, TrueVal);
4654 SI.setOperand(2, FalseVal);
4655 Changed = true;
4656 }
4657 break;
4658 }
4659 case ICmpInst::ICMP_UGT:
4660 case ICmpInst::ICMP_SGT: {
4661 // X > MAX ? T : F --> F
4662 if (CI->isMaxValue(Pred == ICmpInst::ICMP_SGT))
4663 return ReplaceInstUsesWith(SI, FalseVal);
4664 // X > C ? X : C+1 --> X < C+1 ? C+1 : X
Dan Gohman186a6362009-08-12 16:04:34 +00004665 Constant *AdjustedRHS = AddOne(CI);
Dan Gohman81b28ce2008-09-16 18:46:06 +00004666 if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
4667 (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
4668 Pred = ICmpInst::getSwappedPredicate(Pred);
4669 CmpRHS = AdjustedRHS;
4670 std::swap(FalseVal, TrueVal);
4671 ICI->setPredicate(Pred);
4672 ICI->setOperand(1, CmpRHS);
4673 SI.setOperand(1, TrueVal);
4674 SI.setOperand(2, FalseVal);
4675 Changed = true;
4676 }
4677 break;
4678 }
4679 }
4680
Dan Gohman1975d032008-10-30 20:40:10 +00004681 // (x <s 0) ? -1 : 0 -> ashr x, 31 -> all ones if signed
4682 // (x >s -1) ? -1 : 0 -> ashr x, 31 -> all ones if not signed
Chris Lattnercb504b92008-11-16 05:38:51 +00004683 CmpInst::Predicate Pred = CmpInst::BAD_ICMP_PREDICATE;
Dan Gohman4ae51262009-08-12 16:23:25 +00004684 if (match(TrueVal, m_ConstantInt<-1>()) &&
4685 match(FalseVal, m_ConstantInt<0>()))
Chris Lattnercb504b92008-11-16 05:38:51 +00004686 Pred = ICI->getPredicate();
Dan Gohman4ae51262009-08-12 16:23:25 +00004687 else if (match(TrueVal, m_ConstantInt<0>()) &&
4688 match(FalseVal, m_ConstantInt<-1>()))
Chris Lattnercb504b92008-11-16 05:38:51 +00004689 Pred = CmpInst::getInversePredicate(ICI->getPredicate());
4690
Dan Gohman1975d032008-10-30 20:40:10 +00004691 if (Pred != CmpInst::BAD_ICMP_PREDICATE) {
4692 // If we are just checking for a icmp eq of a single bit and zext'ing it
4693 // to an integer, then shift the bit to the appropriate place and then
4694 // cast to integer to avoid the comparison.
4695 const APInt &Op1CV = CI->getValue();
4696
4697 // sext (x <s 0) to i32 --> x>>s31 true if signbit set.
4698 // sext (x >s -1) to i32 --> (x>>s31)^-1 true if signbit clear.
4699 if ((Pred == ICmpInst::ICMP_SLT && Op1CV == 0) ||
Chris Lattnercb504b92008-11-16 05:38:51 +00004700 (Pred == ICmpInst::ICMP_SGT && Op1CV.isAllOnesValue())) {
Dan Gohman1975d032008-10-30 20:40:10 +00004701 Value *In = ICI->getOperand(0);
Owen Andersoneed707b2009-07-24 23:12:02 +00004702 Value *Sh = ConstantInt::get(In->getType(),
Dan Gohman6de29f82009-06-15 22:12:54 +00004703 In->getType()->getScalarSizeInBits()-1);
Dan Gohman1975d032008-10-30 20:40:10 +00004704 In = InsertNewInstBefore(BinaryOperator::CreateAShr(In, Sh,
Eric Christophera66297a2009-07-25 02:45:27 +00004705 In->getName()+".lobit"),
Dan Gohman1975d032008-10-30 20:40:10 +00004706 *ICI);
Dan Gohman21440ac2008-11-02 00:17:33 +00004707 if (In->getType() != SI.getType())
4708 In = CastInst::CreateIntegerCast(In, SI.getType(),
Dan Gohman1975d032008-10-30 20:40:10 +00004709 true/*SExt*/, "tmp", ICI);
4710
4711 if (Pred == ICmpInst::ICMP_SGT)
Dan Gohman4ae51262009-08-12 16:23:25 +00004712 In = InsertNewInstBefore(BinaryOperator::CreateNot(In,
Dan Gohman1975d032008-10-30 20:40:10 +00004713 In->getName()+".not"), *ICI);
4714
4715 return ReplaceInstUsesWith(SI, In);
4716 }
4717 }
4718 }
4719
Dan Gohman81b28ce2008-09-16 18:46:06 +00004720 if (CmpLHS == TrueVal && CmpRHS == FalseVal) {
4721 // Transform (X == Y) ? X : Y -> Y
4722 if (Pred == ICmpInst::ICMP_EQ)
4723 return ReplaceInstUsesWith(SI, FalseVal);
4724 // Transform (X != Y) ? X : Y -> X
4725 if (Pred == ICmpInst::ICMP_NE)
4726 return ReplaceInstUsesWith(SI, TrueVal);
4727 /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
4728
4729 } else if (CmpLHS == FalseVal && CmpRHS == TrueVal) {
4730 // Transform (X == Y) ? Y : X -> X
4731 if (Pred == ICmpInst::ICMP_EQ)
4732 return ReplaceInstUsesWith(SI, FalseVal);
4733 // Transform (X != Y) ? Y : X -> Y
4734 if (Pred == ICmpInst::ICMP_NE)
4735 return ReplaceInstUsesWith(SI, TrueVal);
4736 /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
4737 }
Dan Gohman81b28ce2008-09-16 18:46:06 +00004738 return Changed ? &SI : 0;
4739}
4740
Chris Lattnerc6df8f42009-09-27 20:18:49 +00004741
Chris Lattner7f239582009-10-22 00:17:26 +00004742/// CanSelectOperandBeMappingIntoPredBlock - SI is a select whose condition is a
4743/// PHI node (but the two may be in different blocks). See if the true/false
4744/// values (V) are live in all of the predecessor blocks of the PHI. For
4745/// example, cases like this cannot be mapped:
4746///
4747/// X = phi [ C1, BB1], [C2, BB2]
4748/// Y = add
4749/// Z = select X, Y, 0
4750///
4751/// because Y is not live in BB1/BB2.
4752///
4753static bool CanSelectOperandBeMappingIntoPredBlock(const Value *V,
4754 const SelectInst &SI) {
4755 // If the value is a non-instruction value like a constant or argument, it
4756 // can always be mapped.
4757 const Instruction *I = dyn_cast<Instruction>(V);
4758 if (I == 0) return true;
4759
4760 // If V is a PHI node defined in the same block as the condition PHI, we can
4761 // map the arguments.
4762 const PHINode *CondPHI = cast<PHINode>(SI.getCondition());
4763
4764 if (const PHINode *VP = dyn_cast<PHINode>(I))
4765 if (VP->getParent() == CondPHI->getParent())
4766 return true;
4767
4768 // Otherwise, if the PHI and select are defined in the same block and if V is
4769 // defined in a different block, then we can transform it.
4770 if (SI.getParent() == CondPHI->getParent() &&
4771 I->getParent() != CondPHI->getParent())
4772 return true;
4773
4774 // Otherwise we have a 'hard' case and we can't tell without doing more
4775 // detailed dominator based analysis, punt.
4776 return false;
4777}
Chris Lattnerc6df8f42009-09-27 20:18:49 +00004778
Chris Lattnerb109b5c2009-12-21 06:03:05 +00004779/// FoldSPFofSPF - We have an SPF (e.g. a min or max) of an SPF of the form:
4780/// SPF2(SPF1(A, B), C)
4781Instruction *InstCombiner::FoldSPFofSPF(Instruction *Inner,
4782 SelectPatternFlavor SPF1,
4783 Value *A, Value *B,
4784 Instruction &Outer,
4785 SelectPatternFlavor SPF2, Value *C) {
4786 if (C == A || C == B) {
4787 // MAX(MAX(A, B), B) -> MAX(A, B)
4788 // MIN(MIN(a, b), a) -> MIN(a, b)
4789 if (SPF1 == SPF2)
4790 return ReplaceInstUsesWith(Outer, Inner);
4791
4792 // MAX(MIN(a, b), a) -> a
4793 // MIN(MAX(a, b), a) -> a
Daniel Dunbareddfaaf2009-12-21 23:27:57 +00004794 if ((SPF1 == SPF_SMIN && SPF2 == SPF_SMAX) ||
4795 (SPF1 == SPF_SMAX && SPF2 == SPF_SMIN) ||
4796 (SPF1 == SPF_UMIN && SPF2 == SPF_UMAX) ||
4797 (SPF1 == SPF_UMAX && SPF2 == SPF_UMIN))
Chris Lattnerb109b5c2009-12-21 06:03:05 +00004798 return ReplaceInstUsesWith(Outer, C);
4799 }
4800
4801 // TODO: MIN(MIN(A, 23), 97)
4802 return 0;
4803}
4804
4805
4806
4807
Chris Lattner3d69f462004-03-12 05:52:32 +00004808Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
Chris Lattnerc32b30a2004-03-30 19:37:13 +00004809 Value *CondVal = SI.getCondition();
4810 Value *TrueVal = SI.getTrueValue();
4811 Value *FalseVal = SI.getFalseValue();
4812
4813 // select true, X, Y -> X
4814 // select false, X, Y -> Y
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004815 if (ConstantInt *C = dyn_cast<ConstantInt>(CondVal))
Reid Spencer579dca12007-01-12 04:24:46 +00004816 return ReplaceInstUsesWith(SI, C->getZExtValue() ? TrueVal : FalseVal);
Chris Lattnerc32b30a2004-03-30 19:37:13 +00004817
4818 // select C, X, X -> X
4819 if (TrueVal == FalseVal)
4820 return ReplaceInstUsesWith(SI, TrueVal);
4821
Chris Lattnere87597f2004-10-16 18:11:37 +00004822 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
4823 return ReplaceInstUsesWith(SI, FalseVal);
4824 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
4825 return ReplaceInstUsesWith(SI, TrueVal);
4826 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
4827 if (isa<Constant>(TrueVal))
4828 return ReplaceInstUsesWith(SI, TrueVal);
4829 else
4830 return ReplaceInstUsesWith(SI, FalseVal);
4831 }
4832
Chris Lattner4de84762010-01-04 07:02:48 +00004833 if (SI.getType() == Type::getInt1Ty(SI.getContext())) {
Reid Spencera54b7cb2007-01-12 07:05:14 +00004834 if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) {
Reid Spencer579dca12007-01-12 04:24:46 +00004835 if (C->getZExtValue()) {
Chris Lattner0c199a72004-04-08 04:43:23 +00004836 // Change: A = select B, true, C --> A = or B, C
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004837 return BinaryOperator::CreateOr(CondVal, FalseVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00004838 } else {
4839 // Change: A = select B, false, C --> A = and !B, C
4840 Value *NotCond =
Dan Gohman4ae51262009-08-12 16:23:25 +00004841 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Chris Lattner0c199a72004-04-08 04:43:23 +00004842 "not."+CondVal->getName()), SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004843 return BinaryOperator::CreateAnd(NotCond, FalseVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00004844 }
Reid Spencera54b7cb2007-01-12 07:05:14 +00004845 } else if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) {
Reid Spencer579dca12007-01-12 04:24:46 +00004846 if (C->getZExtValue() == false) {
Chris Lattner0c199a72004-04-08 04:43:23 +00004847 // Change: A = select B, C, false --> A = and B, C
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004848 return BinaryOperator::CreateAnd(CondVal, TrueVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00004849 } else {
4850 // Change: A = select B, C, true --> A = or !B, C
4851 Value *NotCond =
Dan Gohman4ae51262009-08-12 16:23:25 +00004852 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Chris Lattner0c199a72004-04-08 04:43:23 +00004853 "not."+CondVal->getName()), SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004854 return BinaryOperator::CreateOr(NotCond, TrueVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00004855 }
4856 }
Chris Lattnercfa59752007-11-25 21:27:53 +00004857
4858 // select a, b, a -> a&b
4859 // select a, a, b -> a|b
4860 if (CondVal == TrueVal)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004861 return BinaryOperator::CreateOr(CondVal, FalseVal);
Chris Lattnercfa59752007-11-25 21:27:53 +00004862 else if (CondVal == FalseVal)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004863 return BinaryOperator::CreateAnd(CondVal, TrueVal);
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004864 }
Chris Lattner0c199a72004-04-08 04:43:23 +00004865
Chris Lattner2eefe512004-04-09 19:05:30 +00004866 // Selecting between two integer constants?
4867 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
4868 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
Chris Lattnerba417832007-04-11 06:12:58 +00004869 // select C, 1, 0 -> zext C to int
Reid Spencer2ec619a2007-03-23 21:24:59 +00004870 if (FalseValC->isZero() && TrueValC->getValue() == 1) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004871 return CastInst::Create(Instruction::ZExt, CondVal, SI.getType());
Reid Spencer2ec619a2007-03-23 21:24:59 +00004872 } else if (TrueValC->isZero() && FalseValC->getValue() == 1) {
Chris Lattnerba417832007-04-11 06:12:58 +00004873 // select C, 0, 1 -> zext !C to int
Chris Lattner2eefe512004-04-09 19:05:30 +00004874 Value *NotCond =
Dan Gohman4ae51262009-08-12 16:23:25 +00004875 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Chris Lattner82e14fe2004-04-09 18:19:44 +00004876 "not."+CondVal->getName()), SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004877 return CastInst::Create(Instruction::ZExt, NotCond, SI.getType());
Chris Lattner82e14fe2004-04-09 18:19:44 +00004878 }
Chris Lattner457dd822004-06-09 07:59:58 +00004879
Reid Spencere4d87aa2006-12-23 06:05:41 +00004880 if (ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition())) {
Chris Lattnerb8456462006-09-20 04:44:59 +00004881 // If one of the constants is zero (we know they can't both be) and we
Chris Lattnerba417832007-04-11 06:12:58 +00004882 // have an icmp instruction with zero, and we have an 'and' with the
Chris Lattnerb8456462006-09-20 04:44:59 +00004883 // non-constant value, eliminate this whole mess. This corresponds to
4884 // cases like this: ((X & 27) ? 27 : 0)
Reid Spencer2ec619a2007-03-23 21:24:59 +00004885 if (TrueValC->isZero() || FalseValC->isZero())
Chris Lattner65b72ba2006-09-18 04:22:48 +00004886 if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
Chris Lattner457dd822004-06-09 07:59:58 +00004887 cast<Constant>(IC->getOperand(1))->isNullValue())
4888 if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
4889 if (ICA->getOpcode() == Instruction::And &&
Misha Brukmanfd939082005-04-21 23:48:37 +00004890 isa<ConstantInt>(ICA->getOperand(1)) &&
4891 (ICA->getOperand(1) == TrueValC ||
4892 ICA->getOperand(1) == FalseValC) &&
Chris Lattner457dd822004-06-09 07:59:58 +00004893 isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
4894 // Okay, now we know that everything is set up, we just don't
Reid Spencere4d87aa2006-12-23 06:05:41 +00004895 // know whether we have a icmp_ne or icmp_eq and whether the
4896 // true or false val is the zero.
Reid Spencer2ec619a2007-03-23 21:24:59 +00004897 bool ShouldNotVal = !TrueValC->isZero();
Reid Spencere4d87aa2006-12-23 06:05:41 +00004898 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
Chris Lattner457dd822004-06-09 07:59:58 +00004899 Value *V = ICA;
4900 if (ShouldNotVal)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004901 V = InsertNewInstBefore(BinaryOperator::Create(
Chris Lattner457dd822004-06-09 07:59:58 +00004902 Instruction::Xor, V, ICA->getOperand(1)), SI);
4903 return ReplaceInstUsesWith(SI, V);
4904 }
Chris Lattnerb8456462006-09-20 04:44:59 +00004905 }
Chris Lattnerc32b30a2004-03-30 19:37:13 +00004906 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00004907
4908 // See if we are selecting two values based on a comparison of the two values.
Reid Spencere4d87aa2006-12-23 06:05:41 +00004909 if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
4910 if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
Chris Lattnerd76956d2004-04-10 22:21:27 +00004911 // Transform (X == Y) ? X : Y -> Y
Dale Johannesen5a2174f2007-10-03 17:45:27 +00004912 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
4913 // This is not safe in general for floating point:
4914 // consider X== -0, Y== +0.
4915 // It becomes safe if either operand is a nonzero constant.
4916 ConstantFP *CFPt, *CFPf;
4917 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
4918 !CFPt->getValueAPF().isZero()) ||
4919 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
4920 !CFPf->getValueAPF().isZero()))
Chris Lattnerd76956d2004-04-10 22:21:27 +00004921 return ReplaceInstUsesWith(SI, FalseVal);
Dale Johannesen5a2174f2007-10-03 17:45:27 +00004922 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00004923 // Transform (X != Y) ? X : Y -> X
Reid Spencere4d87aa2006-12-23 06:05:41 +00004924 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
Chris Lattnerd76956d2004-04-10 22:21:27 +00004925 return ReplaceInstUsesWith(SI, TrueVal);
Dan Gohman81b28ce2008-09-16 18:46:06 +00004926 // NOTE: if we wanted to, this is where to detect MIN/MAX
Chris Lattnerd76956d2004-04-10 22:21:27 +00004927
Reid Spencere4d87aa2006-12-23 06:05:41 +00004928 } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
Chris Lattnerd76956d2004-04-10 22:21:27 +00004929 // Transform (X == Y) ? Y : X -> X
Dale Johannesen5a2174f2007-10-03 17:45:27 +00004930 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
4931 // This is not safe in general for floating point:
4932 // consider X== -0, Y== +0.
4933 // It becomes safe if either operand is a nonzero constant.
4934 ConstantFP *CFPt, *CFPf;
4935 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
4936 !CFPt->getValueAPF().isZero()) ||
4937 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
4938 !CFPf->getValueAPF().isZero()))
4939 return ReplaceInstUsesWith(SI, FalseVal);
4940 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00004941 // Transform (X != Y) ? Y : X -> Y
Reid Spencere4d87aa2006-12-23 06:05:41 +00004942 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
4943 return ReplaceInstUsesWith(SI, TrueVal);
Dan Gohman81b28ce2008-09-16 18:46:06 +00004944 // NOTE: if we wanted to, this is where to detect MIN/MAX
Reid Spencere4d87aa2006-12-23 06:05:41 +00004945 }
Dan Gohman81b28ce2008-09-16 18:46:06 +00004946 // NOTE: if we wanted to, this is where to detect ABS
Reid Spencere4d87aa2006-12-23 06:05:41 +00004947 }
4948
4949 // See if we are selecting two values based on a comparison of the two values.
Dan Gohman81b28ce2008-09-16 18:46:06 +00004950 if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal))
4951 if (Instruction *Result = visitSelectInstWithICmp(SI, ICI))
4952 return Result;
Misha Brukmanfd939082005-04-21 23:48:37 +00004953
Chris Lattner87875da2005-01-13 22:52:24 +00004954 if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
4955 if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
4956 if (TI->hasOneUse() && FI->hasOneUse()) {
Chris Lattner87875da2005-01-13 22:52:24 +00004957 Instruction *AddOp = 0, *SubOp = 0;
4958
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00004959 // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
4960 if (TI->getOpcode() == FI->getOpcode())
4961 if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
4962 return IV;
4963
4964 // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))). This is
4965 // even legal for FP.
Dan Gohmanae3a0be2009-06-04 22:49:04 +00004966 if ((TI->getOpcode() == Instruction::Sub &&
4967 FI->getOpcode() == Instruction::Add) ||
4968 (TI->getOpcode() == Instruction::FSub &&
4969 FI->getOpcode() == Instruction::FAdd)) {
Chris Lattner87875da2005-01-13 22:52:24 +00004970 AddOp = FI; SubOp = TI;
Dan Gohmanae3a0be2009-06-04 22:49:04 +00004971 } else if ((FI->getOpcode() == Instruction::Sub &&
4972 TI->getOpcode() == Instruction::Add) ||
4973 (FI->getOpcode() == Instruction::FSub &&
4974 TI->getOpcode() == Instruction::FAdd)) {
Chris Lattner87875da2005-01-13 22:52:24 +00004975 AddOp = TI; SubOp = FI;
4976 }
4977
4978 if (AddOp) {
4979 Value *OtherAddOp = 0;
4980 if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
4981 OtherAddOp = AddOp->getOperand(1);
4982 } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
4983 OtherAddOp = AddOp->getOperand(0);
4984 }
4985
4986 if (OtherAddOp) {
Chris Lattner97f37a42006-02-24 18:05:58 +00004987 // So at this point we know we have (Y -> OtherAddOp):
4988 // select C, (add X, Y), (sub X, Z)
4989 Value *NegVal; // Compute -Z
4990 if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00004991 NegVal = ConstantExpr::getNeg(C);
Chris Lattner97f37a42006-02-24 18:05:58 +00004992 } else {
4993 NegVal = InsertNewInstBefore(
Dan Gohman4ae51262009-08-12 16:23:25 +00004994 BinaryOperator::CreateNeg(SubOp->getOperand(1),
Owen Anderson0a5372e2009-07-13 04:09:18 +00004995 "tmp"), SI);
Chris Lattner87875da2005-01-13 22:52:24 +00004996 }
Chris Lattner97f37a42006-02-24 18:05:58 +00004997
4998 Value *NewTrueOp = OtherAddOp;
4999 Value *NewFalseOp = NegVal;
5000 if (AddOp != TI)
5001 std::swap(NewTrueOp, NewFalseOp);
5002 Instruction *NewSel =
Gabor Greifb1dbcd82008-05-15 10:04:30 +00005003 SelectInst::Create(CondVal, NewTrueOp,
5004 NewFalseOp, SI.getName() + ".p");
Chris Lattner97f37a42006-02-24 18:05:58 +00005005
5006 NewSel = InsertNewInstBefore(NewSel, SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005007 return BinaryOperator::CreateAdd(SubOp->getOperand(0), NewSel);
Chris Lattner87875da2005-01-13 22:52:24 +00005008 }
5009 }
5010 }
Misha Brukmanfd939082005-04-21 23:48:37 +00005011
Chris Lattnere576b912004-04-09 23:46:01 +00005012 // See if we can fold the select into one of our operands.
Chris Lattner42a75512007-01-15 02:27:26 +00005013 if (SI.getType()->isInteger()) {
Chris Lattnerb109b5c2009-12-21 06:03:05 +00005014 if (Instruction *FoldI = FoldSelectIntoOp(SI, TrueVal, FalseVal))
Evan Chengde621922009-03-31 20:42:45 +00005015 return FoldI;
Chris Lattnerb109b5c2009-12-21 06:03:05 +00005016
5017 // MAX(MAX(a, b), a) -> MAX(a, b)
5018 // MIN(MIN(a, b), a) -> MIN(a, b)
5019 // MAX(MIN(a, b), a) -> a
5020 // MIN(MAX(a, b), a) -> a
5021 Value *LHS, *RHS, *LHS2, *RHS2;
5022 if (SelectPatternFlavor SPF = MatchSelectPattern(&SI, LHS, RHS)) {
5023 if (SelectPatternFlavor SPF2 = MatchSelectPattern(LHS, LHS2, RHS2))
5024 if (Instruction *R = FoldSPFofSPF(cast<Instruction>(LHS),SPF2,LHS2,RHS2,
5025 SI, SPF, RHS))
5026 return R;
5027 if (SelectPatternFlavor SPF2 = MatchSelectPattern(RHS, LHS2, RHS2))
5028 if (Instruction *R = FoldSPFofSPF(cast<Instruction>(RHS),SPF2,LHS2,RHS2,
5029 SI, SPF, LHS))
5030 return R;
5031 }
5032
5033 // TODO.
5034 // ABS(-X) -> ABS(X)
5035 // ABS(ABS(X)) -> ABS(X)
Chris Lattnere576b912004-04-09 23:46:01 +00005036 }
Chris Lattnera1df33c2005-04-24 07:30:14 +00005037
Chris Lattner7f239582009-10-22 00:17:26 +00005038 // See if we can fold the select into a phi node if the condition is a select.
5039 if (isa<PHINode>(SI.getCondition()))
5040 // The true/false values have to be live in the PHI predecessor's blocks.
5041 if (CanSelectOperandBeMappingIntoPredBlock(TrueVal, SI) &&
5042 CanSelectOperandBeMappingIntoPredBlock(FalseVal, SI))
5043 if (Instruction *NV = FoldOpIntoPhi(SI))
5044 return NV;
Chris Lattner5d1704d2009-09-27 19:57:57 +00005045
Chris Lattnera1df33c2005-04-24 07:30:14 +00005046 if (BinaryOperator::isNot(CondVal)) {
5047 SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
5048 SI.setOperand(1, FalseVal);
5049 SI.setOperand(2, TrueVal);
5050 return &SI;
5051 }
5052
Chris Lattner3d69f462004-03-12 05:52:32 +00005053 return 0;
5054}
5055
Dan Gohmaneee962e2008-04-10 18:43:06 +00005056/// EnforceKnownAlignment - If the specified pointer points to an object that
5057/// we control, modify the object's alignment to PrefAlign. This isn't
5058/// often possible though. If alignment is important, a more reliable approach
5059/// is to simply align all global variables and allocation instructions to
5060/// their preferred alignment from the beginning.
5061///
5062static unsigned EnforceKnownAlignment(Value *V,
5063 unsigned Align, unsigned PrefAlign) {
Chris Lattnerf2369f22007-08-09 19:05:49 +00005064
Dan Gohmaneee962e2008-04-10 18:43:06 +00005065 User *U = dyn_cast<User>(V);
5066 if (!U) return Align;
5067
Dan Gohmanca178902009-07-17 20:47:02 +00005068 switch (Operator::getOpcode(U)) {
Dan Gohmaneee962e2008-04-10 18:43:06 +00005069 default: break;
5070 case Instruction::BitCast:
5071 return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
5072 case Instruction::GetElementPtr: {
Chris Lattner95a959d2006-03-06 20:18:44 +00005073 // If all indexes are zero, it is just the alignment of the base pointer.
5074 bool AllZeroOperands = true;
Gabor Greif52ed3632008-06-12 21:51:29 +00005075 for (User::op_iterator i = U->op_begin() + 1, e = U->op_end(); i != e; ++i)
Gabor Greif177dd3f2008-06-12 21:37:33 +00005076 if (!isa<Constant>(*i) ||
5077 !cast<Constant>(*i)->isNullValue()) {
Chris Lattner95a959d2006-03-06 20:18:44 +00005078 AllZeroOperands = false;
5079 break;
5080 }
Chris Lattnerf2369f22007-08-09 19:05:49 +00005081
5082 if (AllZeroOperands) {
5083 // Treat this like a bitcast.
Dan Gohmaneee962e2008-04-10 18:43:06 +00005084 return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
Chris Lattnerf2369f22007-08-09 19:05:49 +00005085 }
Dan Gohmaneee962e2008-04-10 18:43:06 +00005086 break;
Chris Lattner95a959d2006-03-06 20:18:44 +00005087 }
Dan Gohmaneee962e2008-04-10 18:43:06 +00005088 }
5089
5090 if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
5091 // If there is a large requested alignment and we can, bump up the alignment
5092 // of the global.
5093 if (!GV->isDeclaration()) {
Dan Gohmanecd0fb52009-02-16 23:02:21 +00005094 if (GV->getAlignment() >= PrefAlign)
5095 Align = GV->getAlignment();
5096 else {
5097 GV->setAlignment(PrefAlign);
5098 Align = PrefAlign;
5099 }
Dan Gohmaneee962e2008-04-10 18:43:06 +00005100 }
Chris Lattner42ebefa2009-09-27 21:42:46 +00005101 } else if (AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
5102 // If there is a requested alignment and if this is an alloca, round up.
5103 if (AI->getAlignment() >= PrefAlign)
5104 Align = AI->getAlignment();
5105 else {
5106 AI->setAlignment(PrefAlign);
5107 Align = PrefAlign;
Dan Gohmaneee962e2008-04-10 18:43:06 +00005108 }
5109 }
5110
5111 return Align;
5112}
5113
5114/// GetOrEnforceKnownAlignment - If the specified pointer has an alignment that
5115/// we can determine, return it, otherwise return 0. If PrefAlign is specified,
5116/// and it is more than the alignment of the ultimate object, see if we can
5117/// increase the alignment of the ultimate object, making this check succeed.
5118unsigned InstCombiner::GetOrEnforceKnownAlignment(Value *V,
5119 unsigned PrefAlign) {
5120 unsigned BitWidth = TD ? TD->getTypeSizeInBits(V->getType()) :
5121 sizeof(PrefAlign) * CHAR_BIT;
5122 APInt Mask = APInt::getAllOnesValue(BitWidth);
5123 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
5124 ComputeMaskedBits(V, Mask, KnownZero, KnownOne);
5125 unsigned TrailZ = KnownZero.countTrailingOnes();
5126 unsigned Align = 1u << std::min(BitWidth - 1, TrailZ);
5127
5128 if (PrefAlign > Align)
5129 Align = EnforceKnownAlignment(V, Align, PrefAlign);
5130
5131 // We don't need to make any adjustment.
5132 return Align;
Chris Lattner95a959d2006-03-06 20:18:44 +00005133}
5134
Chris Lattnerf497b022008-01-13 23:50:23 +00005135Instruction *InstCombiner::SimplifyMemTransfer(MemIntrinsic *MI) {
Dan Gohmaneee962e2008-04-10 18:43:06 +00005136 unsigned DstAlign = GetOrEnforceKnownAlignment(MI->getOperand(1));
Dan Gohmanbc989d42009-02-22 18:06:32 +00005137 unsigned SrcAlign = GetOrEnforceKnownAlignment(MI->getOperand(2));
Chris Lattnerf497b022008-01-13 23:50:23 +00005138 unsigned MinAlign = std::min(DstAlign, SrcAlign);
Chris Lattnerdfe964c2009-03-08 03:59:00 +00005139 unsigned CopyAlign = MI->getAlignment();
Chris Lattnerf497b022008-01-13 23:50:23 +00005140
5141 if (CopyAlign < MinAlign) {
Owen Andersoneed707b2009-07-24 23:12:02 +00005142 MI->setAlignment(ConstantInt::get(MI->getAlignmentType(),
Owen Andersona547b472009-07-09 18:36:20 +00005143 MinAlign, false));
Chris Lattnerf497b022008-01-13 23:50:23 +00005144 return MI;
5145 }
5146
5147 // If MemCpyInst length is 1/2/4/8 bytes then replace memcpy with
5148 // load/store.
5149 ConstantInt *MemOpLength = dyn_cast<ConstantInt>(MI->getOperand(3));
5150 if (MemOpLength == 0) return 0;
5151
Chris Lattner37ac6082008-01-14 00:28:35 +00005152 // Source and destination pointer types are always "i8*" for intrinsic. See
5153 // if the size is something we can handle with a single primitive load/store.
5154 // A single load+store correctly handles overlapping memory in the memmove
5155 // case.
Chris Lattnerf497b022008-01-13 23:50:23 +00005156 unsigned Size = MemOpLength->getZExtValue();
Chris Lattner69ea9d22008-04-30 06:39:11 +00005157 if (Size == 0) return MI; // Delete this mem transfer.
5158
5159 if (Size > 8 || (Size&(Size-1)))
Chris Lattner37ac6082008-01-14 00:28:35 +00005160 return 0; // If not 1/2/4/8 bytes, exit.
Chris Lattnerf497b022008-01-13 23:50:23 +00005161
Chris Lattner37ac6082008-01-14 00:28:35 +00005162 // Use an integer load+store unless we can find something better.
Owen Andersond672ecb2009-07-03 00:17:18 +00005163 Type *NewPtrTy =
Chris Lattner4de84762010-01-04 07:02:48 +00005164 PointerType::getUnqual(IntegerType::get(MI->getContext(), Size<<3));
Chris Lattner37ac6082008-01-14 00:28:35 +00005165
5166 // Memcpy forces the use of i8* for the source and destination. That means
5167 // that if you're using memcpy to move one double around, you'll get a cast
5168 // from double* to i8*. We'd much rather use a double load+store rather than
5169 // an i64 load+store, here because this improves the odds that the source or
5170 // dest address will be promotable. See if we can find a better type than the
5171 // integer datatype.
5172 if (Value *Op = getBitCastOperand(MI->getOperand(1))) {
5173 const Type *SrcETy = cast<PointerType>(Op->getType())->getElementType();
Dan Gohmance9fe9f2009-07-21 23:21:54 +00005174 if (TD && SrcETy->isSized() && TD->getTypeStoreSize(SrcETy) == Size) {
Chris Lattner37ac6082008-01-14 00:28:35 +00005175 // The SrcETy might be something like {{{double}}} or [1 x double]. Rip
5176 // down through these levels if so.
Dan Gohman8f8e2692008-05-23 01:52:21 +00005177 while (!SrcETy->isSingleValueType()) {
Chris Lattner37ac6082008-01-14 00:28:35 +00005178 if (const StructType *STy = dyn_cast<StructType>(SrcETy)) {
5179 if (STy->getNumElements() == 1)
5180 SrcETy = STy->getElementType(0);
5181 else
5182 break;
5183 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcETy)) {
5184 if (ATy->getNumElements() == 1)
5185 SrcETy = ATy->getElementType();
5186 else
5187 break;
5188 } else
5189 break;
5190 }
5191
Dan Gohman8f8e2692008-05-23 01:52:21 +00005192 if (SrcETy->isSingleValueType())
Owen Andersondebcb012009-07-29 22:17:13 +00005193 NewPtrTy = PointerType::getUnqual(SrcETy);
Chris Lattner37ac6082008-01-14 00:28:35 +00005194 }
5195 }
5196
5197
Chris Lattnerf497b022008-01-13 23:50:23 +00005198 // If the memcpy/memmove provides better alignment info than we can
5199 // infer, use it.
5200 SrcAlign = std::max(SrcAlign, CopyAlign);
5201 DstAlign = std::max(DstAlign, CopyAlign);
5202
Chris Lattner08142f22009-08-30 19:47:22 +00005203 Value *Src = Builder->CreateBitCast(MI->getOperand(2), NewPtrTy);
5204 Value *Dest = Builder->CreateBitCast(MI->getOperand(1), NewPtrTy);
Chris Lattner37ac6082008-01-14 00:28:35 +00005205 Instruction *L = new LoadInst(Src, "tmp", false, SrcAlign);
5206 InsertNewInstBefore(L, *MI);
5207 InsertNewInstBefore(new StoreInst(L, Dest, false, DstAlign), *MI);
5208
5209 // Set the size of the copy to 0, it will be deleted on the next iteration.
Owen Andersona7235ea2009-07-31 20:28:14 +00005210 MI->setOperand(3, Constant::getNullValue(MemOpLength->getType()));
Chris Lattner37ac6082008-01-14 00:28:35 +00005211 return MI;
Chris Lattnerf497b022008-01-13 23:50:23 +00005212}
Chris Lattner3d69f462004-03-12 05:52:32 +00005213
Chris Lattner69ea9d22008-04-30 06:39:11 +00005214Instruction *InstCombiner::SimplifyMemSet(MemSetInst *MI) {
5215 unsigned Alignment = GetOrEnforceKnownAlignment(MI->getDest());
Chris Lattnerdfe964c2009-03-08 03:59:00 +00005216 if (MI->getAlignment() < Alignment) {
Owen Andersoneed707b2009-07-24 23:12:02 +00005217 MI->setAlignment(ConstantInt::get(MI->getAlignmentType(),
Owen Andersona547b472009-07-09 18:36:20 +00005218 Alignment, false));
Chris Lattner69ea9d22008-04-30 06:39:11 +00005219 return MI;
5220 }
5221
5222 // Extract the length and alignment and fill if they are constant.
5223 ConstantInt *LenC = dyn_cast<ConstantInt>(MI->getLength());
5224 ConstantInt *FillC = dyn_cast<ConstantInt>(MI->getValue());
Chris Lattner4de84762010-01-04 07:02:48 +00005225 if (!LenC || !FillC || FillC->getType() != Type::getInt8Ty(MI->getContext()))
Chris Lattner69ea9d22008-04-30 06:39:11 +00005226 return 0;
5227 uint64_t Len = LenC->getZExtValue();
Chris Lattnerdfe964c2009-03-08 03:59:00 +00005228 Alignment = MI->getAlignment();
Chris Lattner69ea9d22008-04-30 06:39:11 +00005229
5230 // If the length is zero, this is a no-op
5231 if (Len == 0) return MI; // memset(d,c,0,a) -> noop
5232
5233 // memset(s,c,n) -> store s, c (for n=1,2,4,8)
5234 if (Len <= 8 && isPowerOf2_32((uint32_t)Len)) {
Chris Lattner4de84762010-01-04 07:02:48 +00005235 const Type *ITy = IntegerType::get(MI->getContext(), Len*8); // n=1 -> i8.
Chris Lattner69ea9d22008-04-30 06:39:11 +00005236
5237 Value *Dest = MI->getDest();
Chris Lattner08142f22009-08-30 19:47:22 +00005238 Dest = Builder->CreateBitCast(Dest, PointerType::getUnqual(ITy));
Chris Lattner69ea9d22008-04-30 06:39:11 +00005239
5240 // Alignment 0 is identity for alignment 1 for memset, but not store.
5241 if (Alignment == 0) Alignment = 1;
5242
5243 // Extract the fill value and store.
5244 uint64_t Fill = FillC->getZExtValue()*0x0101010101010101ULL;
Owen Andersoneed707b2009-07-24 23:12:02 +00005245 InsertNewInstBefore(new StoreInst(ConstantInt::get(ITy, Fill),
Owen Andersond672ecb2009-07-03 00:17:18 +00005246 Dest, false, Alignment), *MI);
Chris Lattner69ea9d22008-04-30 06:39:11 +00005247
5248 // Set the size of the copy to 0, it will be deleted on the next iteration.
Owen Andersona7235ea2009-07-31 20:28:14 +00005249 MI->setLength(Constant::getNullValue(LenC->getType()));
Chris Lattner69ea9d22008-04-30 06:39:11 +00005250 return MI;
5251 }
5252
5253 return 0;
5254}
5255
5256
Chris Lattner8b0ea312006-01-13 20:11:04 +00005257/// visitCallInst - CallInst simplification. This mostly only handles folding
5258/// of intrinsic instructions. For normal calls, it allows visitCallSite to do
5259/// the heavy lifting.
5260///
Chris Lattner9fe38862003-06-19 17:00:31 +00005261Instruction *InstCombiner::visitCallInst(CallInst &CI) {
Victor Hernandez66284e02009-10-24 04:23:03 +00005262 if (isFreeCall(&CI))
5263 return visitFree(CI);
5264
Chris Lattneraab6ec42009-05-13 17:39:14 +00005265 // If the caller function is nounwind, mark the call as nounwind, even if the
5266 // callee isn't.
5267 if (CI.getParent()->getParent()->doesNotThrow() &&
5268 !CI.doesNotThrow()) {
5269 CI.setDoesNotThrow();
5270 return &CI;
5271 }
5272
Chris Lattner8b0ea312006-01-13 20:11:04 +00005273 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
5274 if (!II) return visitCallSite(&CI);
5275
Chris Lattner7bcc0e72004-02-28 05:22:00 +00005276 // Intrinsics cannot occur in an invoke, so handle them here instead of in
5277 // visitCallSite.
Chris Lattner8b0ea312006-01-13 20:11:04 +00005278 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
Chris Lattner35b9e482004-10-12 04:52:52 +00005279 bool Changed = false;
5280
5281 // memmove/cpy/set of zero bytes is a noop.
5282 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
5283 if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
5284
Chris Lattner35b9e482004-10-12 04:52:52 +00005285 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
Reid Spencerb83eb642006-10-20 07:07:24 +00005286 if (CI->getZExtValue() == 1) {
Chris Lattner35b9e482004-10-12 04:52:52 +00005287 // Replace the instruction with just byte operations. We would
5288 // transform other cases to loads/stores, but we don't know if
5289 // alignment is sufficient.
5290 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +00005291 }
5292
Chris Lattner35b9e482004-10-12 04:52:52 +00005293 // If we have a memmove and the source operation is a constant global,
5294 // then the source and dest pointers can't alias, so we can change this
5295 // into a call to memcpy.
Chris Lattnerf497b022008-01-13 23:50:23 +00005296 if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI)) {
Chris Lattner35b9e482004-10-12 04:52:52 +00005297 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
5298 if (GVSrc->isConstant()) {
5299 Module *M = CI.getParent()->getParent()->getParent();
Chris Lattner824b9582008-11-21 16:42:48 +00005300 Intrinsic::ID MemCpyID = Intrinsic::memcpy;
5301 const Type *Tys[1];
5302 Tys[0] = CI.getOperand(3)->getType();
5303 CI.setOperand(0,
5304 Intrinsic::getDeclaration(M, MemCpyID, Tys, 1));
Chris Lattner35b9e482004-10-12 04:52:52 +00005305 Changed = true;
5306 }
Eli Friedman0c826d92009-12-17 21:07:31 +00005307 }
Chris Lattnera935db82008-05-28 05:30:41 +00005308
Eli Friedman0c826d92009-12-17 21:07:31 +00005309 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(MI)) {
Chris Lattnera935db82008-05-28 05:30:41 +00005310 // memmove(x,x,size) -> noop.
Eli Friedman0c826d92009-12-17 21:07:31 +00005311 if (MTI->getSource() == MTI->getDest())
Chris Lattnera935db82008-05-28 05:30:41 +00005312 return EraseInstFromFunction(CI);
Chris Lattner95a959d2006-03-06 20:18:44 +00005313 }
Chris Lattner35b9e482004-10-12 04:52:52 +00005314
Chris Lattner95a959d2006-03-06 20:18:44 +00005315 // If we can determine a pointer alignment that is bigger than currently
5316 // set, update the alignment.
Chris Lattner3ce5e882009-03-08 03:37:16 +00005317 if (isa<MemTransferInst>(MI)) {
Chris Lattnerf497b022008-01-13 23:50:23 +00005318 if (Instruction *I = SimplifyMemTransfer(MI))
5319 return I;
Chris Lattner69ea9d22008-04-30 06:39:11 +00005320 } else if (MemSetInst *MSI = dyn_cast<MemSetInst>(MI)) {
5321 if (Instruction *I = SimplifyMemSet(MSI))
5322 return I;
Chris Lattner95a959d2006-03-06 20:18:44 +00005323 }
5324
Chris Lattner8b0ea312006-01-13 20:11:04 +00005325 if (Changed) return II;
Chris Lattner0521e3c2008-06-18 04:33:20 +00005326 }
5327
5328 switch (II->getIntrinsicID()) {
5329 default: break;
5330 case Intrinsic::bswap:
5331 // bswap(bswap(x)) -> x
5332 if (IntrinsicInst *Operand = dyn_cast<IntrinsicInst>(II->getOperand(1)))
5333 if (Operand->getIntrinsicID() == Intrinsic::bswap)
5334 return ReplaceInstUsesWith(CI, Operand->getOperand(1));
Chris Lattnere33d4132010-01-01 18:34:40 +00005335
5336 // bswap(trunc(bswap(x))) -> trunc(lshr(x, c))
5337 if (TruncInst *TI = dyn_cast<TruncInst>(II->getOperand(1))) {
5338 if (IntrinsicInst *Operand = dyn_cast<IntrinsicInst>(TI->getOperand(0)))
5339 if (Operand->getIntrinsicID() == Intrinsic::bswap) {
5340 unsigned C = Operand->getType()->getPrimitiveSizeInBits() -
5341 TI->getType()->getPrimitiveSizeInBits();
5342 Value *CV = ConstantInt::get(Operand->getType(), C);
5343 Value *V = Builder->CreateLShr(Operand->getOperand(1), CV);
5344 return new TruncInst(V, TI->getType());
5345 }
5346 }
5347
Chris Lattner0521e3c2008-06-18 04:33:20 +00005348 break;
Chris Lattnerd27f9112010-01-01 01:52:15 +00005349 case Intrinsic::powi:
5350 if (ConstantInt *Power = dyn_cast<ConstantInt>(II->getOperand(2))) {
5351 // powi(x, 0) -> 1.0
5352 if (Power->isZero())
5353 return ReplaceInstUsesWith(CI, ConstantFP::get(CI.getType(), 1.0));
5354 // powi(x, 1) -> x
5355 if (Power->isOne())
5356 return ReplaceInstUsesWith(CI, II->getOperand(1));
5357 // powi(x, -1) -> 1/x
Chris Lattnerf9ead872010-01-01 01:54:08 +00005358 if (Power->isAllOnesValue())
5359 return BinaryOperator::CreateFDiv(ConstantFP::get(CI.getType(), 1.0),
5360 II->getOperand(1));
Chris Lattnerd27f9112010-01-01 01:52:15 +00005361 }
5362 break;
5363
Chris Lattner2bbac752009-11-26 21:42:47 +00005364 case Intrinsic::uadd_with_overflow: {
5365 Value *LHS = II->getOperand(1), *RHS = II->getOperand(2);
5366 const IntegerType *IT = cast<IntegerType>(II->getOperand(1)->getType());
5367 uint32_t BitWidth = IT->getBitWidth();
5368 APInt Mask = APInt::getSignBit(BitWidth);
Chris Lattner998e25a2009-11-26 22:08:06 +00005369 APInt LHSKnownZero(BitWidth, 0);
5370 APInt LHSKnownOne(BitWidth, 0);
Chris Lattner2bbac752009-11-26 21:42:47 +00005371 ComputeMaskedBits(LHS, Mask, LHSKnownZero, LHSKnownOne);
5372 bool LHSKnownNegative = LHSKnownOne[BitWidth - 1];
5373 bool LHSKnownPositive = LHSKnownZero[BitWidth - 1];
5374
5375 if (LHSKnownNegative || LHSKnownPositive) {
Chris Lattner998e25a2009-11-26 22:08:06 +00005376 APInt RHSKnownZero(BitWidth, 0);
5377 APInt RHSKnownOne(BitWidth, 0);
Chris Lattner2bbac752009-11-26 21:42:47 +00005378 ComputeMaskedBits(RHS, Mask, RHSKnownZero, RHSKnownOne);
5379 bool RHSKnownNegative = RHSKnownOne[BitWidth - 1];
5380 bool RHSKnownPositive = RHSKnownZero[BitWidth - 1];
5381 if (LHSKnownNegative && RHSKnownNegative) {
5382 // The sign bit is set in both cases: this MUST overflow.
5383 // Create a simple add instruction, and insert it into the struct.
5384 Instruction *Add = BinaryOperator::CreateAdd(LHS, RHS, "", &CI);
5385 Worklist.Add(Add);
Chris Lattnercd188e92009-11-29 02:57:29 +00005386 Constant *V[] = {
Chris Lattner4de84762010-01-04 07:02:48 +00005387 UndefValue::get(LHS->getType()),ConstantInt::getTrue(II->getContext())
Chris Lattnercd188e92009-11-29 02:57:29 +00005388 };
Chris Lattner4de84762010-01-04 07:02:48 +00005389 Constant *Struct = ConstantStruct::get(II->getContext(), V, 2, false);
Chris Lattner2bbac752009-11-26 21:42:47 +00005390 return InsertValueInst::Create(Struct, Add, 0);
5391 }
5392
5393 if (LHSKnownPositive && RHSKnownPositive) {
5394 // The sign bit is clear in both cases: this CANNOT overflow.
5395 // Create a simple add instruction, and insert it into the struct.
5396 Instruction *Add = BinaryOperator::CreateNUWAdd(LHS, RHS, "", &CI);
5397 Worklist.Add(Add);
Chris Lattnercd188e92009-11-29 02:57:29 +00005398 Constant *V[] = {
Chris Lattner4de84762010-01-04 07:02:48 +00005399 UndefValue::get(LHS->getType()),
5400 ConstantInt::getFalse(II->getContext())
Chris Lattnercd188e92009-11-29 02:57:29 +00005401 };
Chris Lattner4de84762010-01-04 07:02:48 +00005402 Constant *Struct = ConstantStruct::get(II->getContext(), V, 2, false);
Chris Lattner2bbac752009-11-26 21:42:47 +00005403 return InsertValueInst::Create(Struct, Add, 0);
5404 }
5405 }
5406 }
5407 // FALL THROUGH uadd into sadd
5408 case Intrinsic::sadd_with_overflow:
5409 // Canonicalize constants into the RHS.
5410 if (isa<Constant>(II->getOperand(1)) &&
5411 !isa<Constant>(II->getOperand(2))) {
5412 Value *LHS = II->getOperand(1);
5413 II->setOperand(1, II->getOperand(2));
5414 II->setOperand(2, LHS);
5415 return II;
5416 }
5417
5418 // X + undef -> undef
5419 if (isa<UndefValue>(II->getOperand(2)))
5420 return ReplaceInstUsesWith(CI, UndefValue::get(II->getType()));
5421
5422 if (ConstantInt *RHS = dyn_cast<ConstantInt>(II->getOperand(2))) {
5423 // X + 0 -> {X, false}
5424 if (RHS->isZero()) {
5425 Constant *V[] = {
Chris Lattnercd188e92009-11-29 02:57:29 +00005426 UndefValue::get(II->getOperand(0)->getType()),
Chris Lattner4de84762010-01-04 07:02:48 +00005427 ConstantInt::getFalse(II->getContext())
Chris Lattner2bbac752009-11-26 21:42:47 +00005428 };
Chris Lattner4de84762010-01-04 07:02:48 +00005429 Constant *Struct = ConstantStruct::get(II->getContext(), V, 2, false);
Chris Lattner2bbac752009-11-26 21:42:47 +00005430 return InsertValueInst::Create(Struct, II->getOperand(1), 0);
5431 }
5432 }
5433 break;
5434 case Intrinsic::usub_with_overflow:
5435 case Intrinsic::ssub_with_overflow:
5436 // undef - X -> undef
5437 // X - undef -> undef
5438 if (isa<UndefValue>(II->getOperand(1)) ||
5439 isa<UndefValue>(II->getOperand(2)))
5440 return ReplaceInstUsesWith(CI, UndefValue::get(II->getType()));
5441
5442 if (ConstantInt *RHS = dyn_cast<ConstantInt>(II->getOperand(2))) {
5443 // X - 0 -> {X, false}
5444 if (RHS->isZero()) {
5445 Constant *V[] = {
Chris Lattnercd188e92009-11-29 02:57:29 +00005446 UndefValue::get(II->getOperand(1)->getType()),
Chris Lattner4de84762010-01-04 07:02:48 +00005447 ConstantInt::getFalse(II->getContext())
Chris Lattner2bbac752009-11-26 21:42:47 +00005448 };
Chris Lattner4de84762010-01-04 07:02:48 +00005449 Constant *Struct = ConstantStruct::get(II->getContext(), V, 2, false);
Chris Lattner2bbac752009-11-26 21:42:47 +00005450 return InsertValueInst::Create(Struct, II->getOperand(1), 0);
5451 }
5452 }
5453 break;
5454 case Intrinsic::umul_with_overflow:
5455 case Intrinsic::smul_with_overflow:
5456 // Canonicalize constants into the RHS.
5457 if (isa<Constant>(II->getOperand(1)) &&
5458 !isa<Constant>(II->getOperand(2))) {
5459 Value *LHS = II->getOperand(1);
5460 II->setOperand(1, II->getOperand(2));
5461 II->setOperand(2, LHS);
5462 return II;
5463 }
5464
5465 // X * undef -> undef
5466 if (isa<UndefValue>(II->getOperand(2)))
5467 return ReplaceInstUsesWith(CI, UndefValue::get(II->getType()));
5468
5469 if (ConstantInt *RHSI = dyn_cast<ConstantInt>(II->getOperand(2))) {
5470 // X*0 -> {0, false}
5471 if (RHSI->isZero())
5472 return ReplaceInstUsesWith(CI, Constant::getNullValue(II->getType()));
5473
5474 // X * 1 -> {X, false}
5475 if (RHSI->equalsInt(1)) {
Chris Lattnercd188e92009-11-29 02:57:29 +00005476 Constant *V[] = {
5477 UndefValue::get(II->getOperand(1)->getType()),
Chris Lattner4de84762010-01-04 07:02:48 +00005478 ConstantInt::getFalse(II->getContext())
Chris Lattnercd188e92009-11-29 02:57:29 +00005479 };
Chris Lattner4de84762010-01-04 07:02:48 +00005480 Constant *Struct = ConstantStruct::get(II->getContext(), V, 2, false);
Chris Lattnercd188e92009-11-29 02:57:29 +00005481 return InsertValueInst::Create(Struct, II->getOperand(1), 0);
Chris Lattner2bbac752009-11-26 21:42:47 +00005482 }
5483 }
5484 break;
Chris Lattner0521e3c2008-06-18 04:33:20 +00005485 case Intrinsic::ppc_altivec_lvx:
5486 case Intrinsic::ppc_altivec_lvxl:
5487 case Intrinsic::x86_sse_loadu_ps:
5488 case Intrinsic::x86_sse2_loadu_pd:
5489 case Intrinsic::x86_sse2_loadu_dq:
5490 // Turn PPC lvx -> load if the pointer is known aligned.
5491 // Turn X86 loadups -> load if the pointer is known aligned.
5492 if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
Chris Lattner08142f22009-08-30 19:47:22 +00005493 Value *Ptr = Builder->CreateBitCast(II->getOperand(1),
5494 PointerType::getUnqual(II->getType()));
Chris Lattner0521e3c2008-06-18 04:33:20 +00005495 return new LoadInst(Ptr);
Chris Lattner867b99f2006-10-05 06:55:50 +00005496 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00005497 break;
5498 case Intrinsic::ppc_altivec_stvx:
5499 case Intrinsic::ppc_altivec_stvxl:
5500 // Turn stvx -> store if the pointer is known aligned.
5501 if (GetOrEnforceKnownAlignment(II->getOperand(2), 16) >= 16) {
5502 const Type *OpPtrTy =
Owen Andersondebcb012009-07-29 22:17:13 +00005503 PointerType::getUnqual(II->getOperand(1)->getType());
Chris Lattner08142f22009-08-30 19:47:22 +00005504 Value *Ptr = Builder->CreateBitCast(II->getOperand(2), OpPtrTy);
Chris Lattner0521e3c2008-06-18 04:33:20 +00005505 return new StoreInst(II->getOperand(1), Ptr);
5506 }
5507 break;
5508 case Intrinsic::x86_sse_storeu_ps:
5509 case Intrinsic::x86_sse2_storeu_pd:
5510 case Intrinsic::x86_sse2_storeu_dq:
Chris Lattner0521e3c2008-06-18 04:33:20 +00005511 // Turn X86 storeu -> store if the pointer is known aligned.
5512 if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
5513 const Type *OpPtrTy =
Owen Andersondebcb012009-07-29 22:17:13 +00005514 PointerType::getUnqual(II->getOperand(2)->getType());
Chris Lattner08142f22009-08-30 19:47:22 +00005515 Value *Ptr = Builder->CreateBitCast(II->getOperand(1), OpPtrTy);
Chris Lattner0521e3c2008-06-18 04:33:20 +00005516 return new StoreInst(II->getOperand(2), Ptr);
5517 }
5518 break;
5519
5520 case Intrinsic::x86_sse_cvttss2si: {
5521 // These intrinsics only demands the 0th element of its input vector. If
5522 // we can simplify the input based on that, do so now.
Evan Cheng388df622009-02-03 10:05:09 +00005523 unsigned VWidth =
5524 cast<VectorType>(II->getOperand(1)->getType())->getNumElements();
5525 APInt DemandedElts(VWidth, 1);
5526 APInt UndefElts(VWidth, 0);
5527 if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
Chris Lattner0521e3c2008-06-18 04:33:20 +00005528 UndefElts)) {
5529 II->setOperand(1, V);
5530 return II;
5531 }
5532 break;
5533 }
5534
5535 case Intrinsic::ppc_altivec_vperm:
5536 // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
5537 if (ConstantVector *Mask = dyn_cast<ConstantVector>(II->getOperand(3))) {
5538 assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
Chris Lattner867b99f2006-10-05 06:55:50 +00005539
Chris Lattner0521e3c2008-06-18 04:33:20 +00005540 // Check that all of the elements are integer constants or undefs.
5541 bool AllEltsOk = true;
5542 for (unsigned i = 0; i != 16; ++i) {
5543 if (!isa<ConstantInt>(Mask->getOperand(i)) &&
5544 !isa<UndefValue>(Mask->getOperand(i))) {
5545 AllEltsOk = false;
5546 break;
5547 }
5548 }
5549
5550 if (AllEltsOk) {
5551 // Cast the input vectors to byte vectors.
Chris Lattner08142f22009-08-30 19:47:22 +00005552 Value *Op0 = Builder->CreateBitCast(II->getOperand(1), Mask->getType());
5553 Value *Op1 = Builder->CreateBitCast(II->getOperand(2), Mask->getType());
Owen Anderson9e9a0d52009-07-30 23:03:37 +00005554 Value *Result = UndefValue::get(Op0->getType());
Chris Lattnere2ed0572006-04-06 19:19:17 +00005555
Chris Lattner0521e3c2008-06-18 04:33:20 +00005556 // Only extract each element once.
5557 Value *ExtractedElts[32];
5558 memset(ExtractedElts, 0, sizeof(ExtractedElts));
5559
Chris Lattnere2ed0572006-04-06 19:19:17 +00005560 for (unsigned i = 0; i != 16; ++i) {
Chris Lattner0521e3c2008-06-18 04:33:20 +00005561 if (isa<UndefValue>(Mask->getOperand(i)))
5562 continue;
5563 unsigned Idx=cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
5564 Idx &= 31; // Match the hardware behavior.
5565
5566 if (ExtractedElts[Idx] == 0) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +00005567 ExtractedElts[Idx] =
5568 Builder->CreateExtractElement(Idx < 16 ? Op0 : Op1,
Chris Lattner4de84762010-01-04 07:02:48 +00005569 ConstantInt::get(Type::getInt32Ty(II->getContext()),
5570 Idx&15, false), "tmp");
Chris Lattnere2ed0572006-04-06 19:19:17 +00005571 }
Chris Lattnere2ed0572006-04-06 19:19:17 +00005572
Chris Lattner0521e3c2008-06-18 04:33:20 +00005573 // Insert this value into the result vector.
Chris Lattnerf925cbd2009-08-30 18:50:58 +00005574 Result = Builder->CreateInsertElement(Result, ExtractedElts[Idx],
Chris Lattner4de84762010-01-04 07:02:48 +00005575 ConstantInt::get(Type::getInt32Ty(II->getContext()),
5576 i, false), "tmp");
Chris Lattnere2ed0572006-04-06 19:19:17 +00005577 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00005578 return CastInst::Create(Instruction::BitCast, Result, CI.getType());
Chris Lattnere2ed0572006-04-06 19:19:17 +00005579 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00005580 }
5581 break;
Chris Lattnere2ed0572006-04-06 19:19:17 +00005582
Chris Lattner0521e3c2008-06-18 04:33:20 +00005583 case Intrinsic::stackrestore: {
5584 // If the save is right next to the restore, remove the restore. This can
5585 // happen when variable allocas are DCE'd.
5586 if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
5587 if (SS->getIntrinsicID() == Intrinsic::stacksave) {
5588 BasicBlock::iterator BI = SS;
5589 if (&*++BI == II)
5590 return EraseInstFromFunction(CI);
Chris Lattnera728ddc2006-01-13 21:28:09 +00005591 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00005592 }
5593
5594 // Scan down this block to see if there is another stack restore in the
5595 // same block without an intervening call/alloca.
5596 BasicBlock::iterator BI = II;
5597 TerminatorInst *TI = II->getParent()->getTerminator();
5598 bool CannotRemove = false;
5599 for (++BI; &*BI != TI; ++BI) {
Victor Hernandez83d63912009-09-18 22:35:49 +00005600 if (isa<AllocaInst>(BI) || isMalloc(BI)) {
Chris Lattner0521e3c2008-06-18 04:33:20 +00005601 CannotRemove = true;
5602 break;
5603 }
Chris Lattneraa0bf522008-06-25 05:59:28 +00005604 if (CallInst *BCI = dyn_cast<CallInst>(BI)) {
5605 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(BCI)) {
5606 // If there is a stackrestore below this one, remove this one.
5607 if (II->getIntrinsicID() == Intrinsic::stackrestore)
5608 return EraseInstFromFunction(CI);
5609 // Otherwise, ignore the intrinsic.
5610 } else {
5611 // If we found a non-intrinsic call, we can't remove the stack
5612 // restore.
Chris Lattnerbf1d8a72008-02-18 06:12:38 +00005613 CannotRemove = true;
5614 break;
5615 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00005616 }
Chris Lattnera728ddc2006-01-13 21:28:09 +00005617 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00005618
5619 // If the stack restore is in a return/unwind block and if there are no
5620 // allocas or calls between the restore and the return, nuke the restore.
5621 if (!CannotRemove && (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)))
5622 return EraseInstFromFunction(CI);
5623 break;
5624 }
Chris Lattner35b9e482004-10-12 04:52:52 +00005625 }
5626
Chris Lattner8b0ea312006-01-13 20:11:04 +00005627 return visitCallSite(II);
Chris Lattner9fe38862003-06-19 17:00:31 +00005628}
5629
5630// InvokeInst simplification
5631//
5632Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
Chris Lattnera44d8a22003-10-07 22:32:43 +00005633 return visitCallSite(&II);
Chris Lattner9fe38862003-06-19 17:00:31 +00005634}
5635
Dale Johannesenda30ccb2008-04-25 21:16:07 +00005636/// isSafeToEliminateVarargsCast - If this cast does not affect the value
5637/// passed through the varargs area, we can eliminate the use of the cast.
Dale Johannesen1f530a52008-04-23 18:34:37 +00005638static bool isSafeToEliminateVarargsCast(const CallSite CS,
5639 const CastInst * const CI,
5640 const TargetData * const TD,
5641 const int ix) {
5642 if (!CI->isLosslessCast())
5643 return false;
5644
5645 // The size of ByVal arguments is derived from the type, so we
5646 // can't change to a type with a different size. If the size were
5647 // passed explicitly we could avoid this check.
Devang Patel05988662008-09-25 21:00:45 +00005648 if (!CS.paramHasAttr(ix, Attribute::ByVal))
Dale Johannesen1f530a52008-04-23 18:34:37 +00005649 return true;
5650
5651 const Type* SrcTy =
5652 cast<PointerType>(CI->getOperand(0)->getType())->getElementType();
5653 const Type* DstTy = cast<PointerType>(CI->getType())->getElementType();
5654 if (!SrcTy->isSized() || !DstTy->isSized())
5655 return false;
Dan Gohmance9fe9f2009-07-21 23:21:54 +00005656 if (!TD || TD->getTypeAllocSize(SrcTy) != TD->getTypeAllocSize(DstTy))
Dale Johannesen1f530a52008-04-23 18:34:37 +00005657 return false;
5658 return true;
5659}
5660
Chris Lattnera44d8a22003-10-07 22:32:43 +00005661// visitCallSite - Improvements for call and invoke instructions.
5662//
5663Instruction *InstCombiner::visitCallSite(CallSite CS) {
Chris Lattner6c266db2003-10-07 22:54:13 +00005664 bool Changed = false;
5665
5666 // If the callee is a constexpr cast of a function, attempt to move the cast
5667 // to the arguments of the call/invoke.
Chris Lattnera44d8a22003-10-07 22:32:43 +00005668 if (transformConstExprCastCall(CS)) return 0;
5669
Chris Lattner6c266db2003-10-07 22:54:13 +00005670 Value *Callee = CS.getCalledValue();
Chris Lattnere87597f2004-10-16 18:11:37 +00005671
Chris Lattner08b22ec2005-05-13 07:09:09 +00005672 if (Function *CalleeF = dyn_cast<Function>(Callee))
5673 if (CalleeF->getCallingConv() != CS.getCallingConv()) {
5674 Instruction *OldCall = CS.getInstruction();
5675 // If the call and callee calling conventions don't match, this call must
5676 // be unreachable, as the call is undefined.
Chris Lattner4de84762010-01-04 07:02:48 +00005677 new StoreInst(ConstantInt::getTrue(Callee->getContext()),
5678 UndefValue::get(Type::getInt1PtrTy(Callee->getContext())),
Owen Andersond672ecb2009-07-03 00:17:18 +00005679 OldCall);
Devang Patel228ebd02009-10-13 22:56:32 +00005680 // If OldCall dues not return void then replaceAllUsesWith undef.
5681 // This allows ValueHandlers and custom metadata to adjust itself.
Devang Patel9674d152009-10-14 17:29:00 +00005682 if (!OldCall->getType()->isVoidTy())
Devang Patel228ebd02009-10-13 22:56:32 +00005683 OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
Chris Lattner08b22ec2005-05-13 07:09:09 +00005684 if (isa<CallInst>(OldCall)) // Not worth removing an invoke here.
5685 return EraseInstFromFunction(*OldCall);
5686 return 0;
5687 }
5688
Chris Lattner17be6352004-10-18 02:59:09 +00005689 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
5690 // This instruction is not reachable, just remove it. We insert a store to
5691 // undef so that we know that this code is not reachable, despite the fact
5692 // that we can't modify the CFG here.
Chris Lattner4de84762010-01-04 07:02:48 +00005693 new StoreInst(ConstantInt::getTrue(Callee->getContext()),
5694 UndefValue::get(Type::getInt1PtrTy(Callee->getContext())),
Chris Lattner17be6352004-10-18 02:59:09 +00005695 CS.getInstruction());
5696
Devang Patel228ebd02009-10-13 22:56:32 +00005697 // If CS dues not return void then replaceAllUsesWith undef.
5698 // This allows ValueHandlers and custom metadata to adjust itself.
Devang Patel9674d152009-10-14 17:29:00 +00005699 if (!CS.getInstruction()->getType()->isVoidTy())
Devang Patel228ebd02009-10-13 22:56:32 +00005700 CS.getInstruction()->
5701 replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
Chris Lattner17be6352004-10-18 02:59:09 +00005702
5703 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
5704 // Don't break the CFG, insert a dummy cond branch.
Gabor Greif051a9502008-04-06 20:25:17 +00005705 BranchInst::Create(II->getNormalDest(), II->getUnwindDest(),
Chris Lattner4de84762010-01-04 07:02:48 +00005706 ConstantInt::getTrue(Callee->getContext()), II);
Chris Lattnere87597f2004-10-16 18:11:37 +00005707 }
Chris Lattner17be6352004-10-18 02:59:09 +00005708 return EraseInstFromFunction(*CS.getInstruction());
5709 }
Chris Lattnere87597f2004-10-16 18:11:37 +00005710
Duncan Sandscdb6d922007-09-17 10:26:40 +00005711 if (BitCastInst *BC = dyn_cast<BitCastInst>(Callee))
5712 if (IntrinsicInst *In = dyn_cast<IntrinsicInst>(BC->getOperand(0)))
5713 if (In->getIntrinsicID() == Intrinsic::init_trampoline)
5714 return transformCallThroughTrampoline(CS);
5715
Chris Lattner6c266db2003-10-07 22:54:13 +00005716 const PointerType *PTy = cast<PointerType>(Callee->getType());
5717 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
5718 if (FTy->isVarArg()) {
Dale Johannesen63e7eb42008-04-23 01:03:05 +00005719 int ix = FTy->getNumParams() + (isa<InvokeInst>(Callee) ? 3 : 1);
Chris Lattner6c266db2003-10-07 22:54:13 +00005720 // See if we can optimize any arguments passed through the varargs area of
5721 // the call.
5722 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
Dale Johannesen1f530a52008-04-23 18:34:37 +00005723 E = CS.arg_end(); I != E; ++I, ++ix) {
5724 CastInst *CI = dyn_cast<CastInst>(*I);
5725 if (CI && isSafeToEliminateVarargsCast(CS, CI, TD, ix)) {
5726 *I = CI->getOperand(0);
5727 Changed = true;
Chris Lattner6c266db2003-10-07 22:54:13 +00005728 }
Dale Johannesen1f530a52008-04-23 18:34:37 +00005729 }
Chris Lattner6c266db2003-10-07 22:54:13 +00005730 }
Misha Brukmanfd939082005-04-21 23:48:37 +00005731
Duncan Sandsf0c33542007-12-19 21:13:37 +00005732 if (isa<InlineAsm>(Callee) && !CS.doesNotThrow()) {
Duncan Sandsece2c042007-12-16 15:51:49 +00005733 // Inline asm calls cannot throw - mark them 'nounwind'.
Duncan Sandsf0c33542007-12-19 21:13:37 +00005734 CS.setDoesNotThrow();
Duncan Sandsece2c042007-12-16 15:51:49 +00005735 Changed = true;
5736 }
5737
Chris Lattner6c266db2003-10-07 22:54:13 +00005738 return Changed ? CS.getInstruction() : 0;
Chris Lattnera44d8a22003-10-07 22:32:43 +00005739}
5740
Chris Lattner9fe38862003-06-19 17:00:31 +00005741// transformConstExprCastCall - If the callee is a constexpr cast of a function,
5742// attempt to move the cast to the arguments of the call/invoke.
5743//
5744bool InstCombiner::transformConstExprCastCall(CallSite CS) {
5745 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
5746 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
Reid Spencer3da59db2006-11-27 01:05:10 +00005747 if (CE->getOpcode() != Instruction::BitCast ||
5748 !isa<Function>(CE->getOperand(0)))
Chris Lattner9fe38862003-06-19 17:00:31 +00005749 return false;
Reid Spencer8863f182004-07-18 00:38:32 +00005750 Function *Callee = cast<Function>(CE->getOperand(0));
Chris Lattner9fe38862003-06-19 17:00:31 +00005751 Instruction *Caller = CS.getInstruction();
Devang Patel05988662008-09-25 21:00:45 +00005752 const AttrListPtr &CallerPAL = CS.getAttributes();
Chris Lattner9fe38862003-06-19 17:00:31 +00005753
5754 // Okay, this is a cast from a function to a different type. Unless doing so
5755 // would cause a type conversion of one of our arguments, change this call to
5756 // be a direct call with arguments casted to the appropriate types.
5757 //
5758 const FunctionType *FT = Callee->getFunctionType();
5759 const Type *OldRetTy = Caller->getType();
Duncan Sandsf413cdf2008-06-01 07:38:42 +00005760 const Type *NewRetTy = FT->getReturnType();
Chris Lattner9fe38862003-06-19 17:00:31 +00005761
Duncan Sandsf413cdf2008-06-01 07:38:42 +00005762 if (isa<StructType>(NewRetTy))
Devang Patel75e6f022008-03-11 18:04:06 +00005763 return false; // TODO: Handle multiple return values.
5764
Chris Lattnerf78616b2004-01-14 06:06:08 +00005765 // Check to see if we are changing the return type...
Duncan Sandsf413cdf2008-06-01 07:38:42 +00005766 if (OldRetTy != NewRetTy) {
Bill Wendlinga6c31122008-05-14 22:45:20 +00005767 if (Callee->isDeclaration() &&
Duncan Sandsf413cdf2008-06-01 07:38:42 +00005768 // Conversion is ok if changing from one pointer type to another or from
5769 // a pointer to an integer of the same size.
Dan Gohmance9fe9f2009-07-21 23:21:54 +00005770 !((isa<PointerType>(OldRetTy) || !TD ||
Owen Anderson1d0be152009-08-13 21:58:54 +00005771 OldRetTy == TD->getIntPtrType(Caller->getContext())) &&
Dan Gohmance9fe9f2009-07-21 23:21:54 +00005772 (isa<PointerType>(NewRetTy) || !TD ||
Owen Anderson1d0be152009-08-13 21:58:54 +00005773 NewRetTy == TD->getIntPtrType(Caller->getContext()))))
Chris Lattnerec479922007-01-06 02:09:32 +00005774 return false; // Cannot transform this return value.
Chris Lattnerf78616b2004-01-14 06:06:08 +00005775
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00005776 if (!Caller->use_empty() &&
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00005777 // void -> non-void is handled specially
Devang Patel9674d152009-10-14 17:29:00 +00005778 !NewRetTy->isVoidTy() && !CastInst::isCastable(NewRetTy, OldRetTy))
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00005779 return false; // Cannot transform this return value.
5780
Chris Lattner58d74912008-03-12 17:45:29 +00005781 if (!CallerPAL.isEmpty() && !Caller->use_empty()) {
Devang Patel19c87462008-09-26 22:53:05 +00005782 Attributes RAttrs = CallerPAL.getRetAttributes();
Devang Patel05988662008-09-25 21:00:45 +00005783 if (RAttrs & Attribute::typeIncompatible(NewRetTy))
Duncan Sands6c3470e2008-01-07 17:16:06 +00005784 return false; // Attribute not compatible with transformed value.
5785 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +00005786
Chris Lattnerf78616b2004-01-14 06:06:08 +00005787 // If the callsite is an invoke instruction, and the return value is used by
5788 // a PHI node in a successor, we cannot change the return type of the call
5789 // because there is no place to put the cast instruction (without breaking
5790 // the critical edge). Bail out in this case.
5791 if (!Caller->use_empty())
5792 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
5793 for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
5794 UI != E; ++UI)
5795 if (PHINode *PN = dyn_cast<PHINode>(*UI))
5796 if (PN->getParent() == II->getNormalDest() ||
Chris Lattneraeb2a1d2004-02-08 21:44:31 +00005797 PN->getParent() == II->getUnwindDest())
Chris Lattnerf78616b2004-01-14 06:06:08 +00005798 return false;
5799 }
Chris Lattner9fe38862003-06-19 17:00:31 +00005800
5801 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
5802 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
Misha Brukmanfd939082005-04-21 23:48:37 +00005803
Chris Lattner9fe38862003-06-19 17:00:31 +00005804 CallSite::arg_iterator AI = CS.arg_begin();
5805 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
5806 const Type *ParamTy = FT->getParamType(i);
Andrew Lenharthb8e604c2006-06-28 01:01:52 +00005807 const Type *ActTy = (*AI)->getType();
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00005808
5809 if (!CastInst::isCastable(ActTy, ParamTy))
Duncan Sandsad9a9e12008-01-06 18:27:01 +00005810 return false; // Cannot transform this parameter value.
5811
Devang Patel19c87462008-09-26 22:53:05 +00005812 if (CallerPAL.getParamAttributes(i + 1)
5813 & Attribute::typeIncompatible(ParamTy))
Chris Lattner58d74912008-03-12 17:45:29 +00005814 return false; // Attribute not compatible with transformed value.
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00005815
Duncan Sandsf413cdf2008-06-01 07:38:42 +00005816 // Converting from one pointer type to another or between a pointer and an
5817 // integer of the same size is safe even if we do not have a body.
Chris Lattnerec479922007-01-06 02:09:32 +00005818 bool isConvertible = ActTy == ParamTy ||
Owen Anderson1d0be152009-08-13 21:58:54 +00005819 (TD && ((isa<PointerType>(ParamTy) ||
5820 ParamTy == TD->getIntPtrType(Caller->getContext())) &&
5821 (isa<PointerType>(ActTy) ||
5822 ActTy == TD->getIntPtrType(Caller->getContext()))));
Reid Spencer5cbf9852007-01-30 20:08:39 +00005823 if (Callee->isDeclaration() && !isConvertible) return false;
Chris Lattner9fe38862003-06-19 17:00:31 +00005824 }
5825
5826 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
Reid Spencer5cbf9852007-01-30 20:08:39 +00005827 Callee->isDeclaration())
Chris Lattner58d74912008-03-12 17:45:29 +00005828 return false; // Do not delete arguments unless we have a function body.
Chris Lattner9fe38862003-06-19 17:00:31 +00005829
Chris Lattner58d74912008-03-12 17:45:29 +00005830 if (FT->getNumParams() < NumActualArgs && FT->isVarArg() &&
5831 !CallerPAL.isEmpty())
Duncan Sandsad9a9e12008-01-06 18:27:01 +00005832 // In this case we have more arguments than the new function type, but we
Duncan Sandse1e520f2008-01-13 08:02:44 +00005833 // won't be dropping them. Check that these extra arguments have attributes
5834 // that are compatible with being a vararg call argument.
Chris Lattner58d74912008-03-12 17:45:29 +00005835 for (unsigned i = CallerPAL.getNumSlots(); i; --i) {
5836 if (CallerPAL.getSlot(i - 1).Index <= FT->getNumParams())
Duncan Sandse1e520f2008-01-13 08:02:44 +00005837 break;
Devang Pateleaf42ab2008-09-23 23:03:40 +00005838 Attributes PAttrs = CallerPAL.getSlot(i - 1).Attrs;
Devang Patel05988662008-09-25 21:00:45 +00005839 if (PAttrs & Attribute::VarArgsIncompatible)
Duncan Sandse1e520f2008-01-13 08:02:44 +00005840 return false;
5841 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +00005842
Chris Lattner9fe38862003-06-19 17:00:31 +00005843 // Okay, we decided that this is a safe thing to do: go ahead and start
5844 // inserting cast instructions as necessary...
5845 std::vector<Value*> Args;
5846 Args.reserve(NumActualArgs);
Devang Patel05988662008-09-25 21:00:45 +00005847 SmallVector<AttributeWithIndex, 8> attrVec;
Duncan Sandsad9a9e12008-01-06 18:27:01 +00005848 attrVec.reserve(NumCommonArgs);
5849
5850 // Get any return attributes.
Devang Patel19c87462008-09-26 22:53:05 +00005851 Attributes RAttrs = CallerPAL.getRetAttributes();
Duncan Sandsad9a9e12008-01-06 18:27:01 +00005852
5853 // If the return value is not being used, the type may not be compatible
5854 // with the existing attributes. Wipe out any problematic attributes.
Devang Patel05988662008-09-25 21:00:45 +00005855 RAttrs &= ~Attribute::typeIncompatible(NewRetTy);
Duncan Sandsad9a9e12008-01-06 18:27:01 +00005856
5857 // Add the new return attributes.
5858 if (RAttrs)
Devang Patel05988662008-09-25 21:00:45 +00005859 attrVec.push_back(AttributeWithIndex::get(0, RAttrs));
Chris Lattner9fe38862003-06-19 17:00:31 +00005860
5861 AI = CS.arg_begin();
5862 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
5863 const Type *ParamTy = FT->getParamType(i);
5864 if ((*AI)->getType() == ParamTy) {
5865 Args.push_back(*AI);
5866 } else {
Reid Spencer8a903db2006-12-18 08:47:13 +00005867 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
Reid Spencerc5b206b2006-12-31 05:48:39 +00005868 false, ParamTy, false);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00005869 Args.push_back(Builder->CreateCast(opcode, *AI, ParamTy, "tmp"));
Chris Lattner9fe38862003-06-19 17:00:31 +00005870 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +00005871
5872 // Add any parameter attributes.
Devang Patel19c87462008-09-26 22:53:05 +00005873 if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
Devang Patel05988662008-09-25 21:00:45 +00005874 attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
Chris Lattner9fe38862003-06-19 17:00:31 +00005875 }
5876
5877 // If the function takes more arguments than the call was taking, add them
Chris Lattnerf925cbd2009-08-30 18:50:58 +00005878 // now.
Chris Lattner9fe38862003-06-19 17:00:31 +00005879 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
Owen Andersona7235ea2009-07-31 20:28:14 +00005880 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
Chris Lattner9fe38862003-06-19 17:00:31 +00005881
Chris Lattnerf925cbd2009-08-30 18:50:58 +00005882 // If we are removing arguments to the function, emit an obnoxious warning.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00005883 if (FT->getNumParams() < NumActualArgs) {
Chris Lattner9fe38862003-06-19 17:00:31 +00005884 if (!FT->isVarArg()) {
Daniel Dunbarce63ffb2009-07-25 00:23:56 +00005885 errs() << "WARNING: While resolving call to function '"
5886 << Callee->getName() << "' arguments were dropped!\n";
Chris Lattner9fe38862003-06-19 17:00:31 +00005887 } else {
Chris Lattnerf925cbd2009-08-30 18:50:58 +00005888 // Add all of the arguments in their promoted form to the arg list.
Chris Lattner9fe38862003-06-19 17:00:31 +00005889 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
5890 const Type *PTy = getPromotedType((*AI)->getType());
5891 if (PTy != (*AI)->getType()) {
5892 // Must promote to pass through va_arg area!
Chris Lattnerf925cbd2009-08-30 18:50:58 +00005893 Instruction::CastOps opcode =
5894 CastInst::getCastOpcode(*AI, false, PTy, false);
5895 Args.push_back(Builder->CreateCast(opcode, *AI, PTy, "tmp"));
Chris Lattner9fe38862003-06-19 17:00:31 +00005896 } else {
5897 Args.push_back(*AI);
5898 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +00005899
Duncan Sandse1e520f2008-01-13 08:02:44 +00005900 // Add any parameter attributes.
Devang Patel19c87462008-09-26 22:53:05 +00005901 if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
Devang Patel05988662008-09-25 21:00:45 +00005902 attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
Duncan Sandse1e520f2008-01-13 08:02:44 +00005903 }
Chris Lattner9fe38862003-06-19 17:00:31 +00005904 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00005905 }
Chris Lattner9fe38862003-06-19 17:00:31 +00005906
Devang Patel19c87462008-09-26 22:53:05 +00005907 if (Attributes FnAttrs = CallerPAL.getFnAttributes())
5908 attrVec.push_back(AttributeWithIndex::get(~0, FnAttrs));
5909
Devang Patel9674d152009-10-14 17:29:00 +00005910 if (NewRetTy->isVoidTy())
Chris Lattner6934a042007-02-11 01:23:03 +00005911 Caller->setName(""); // Void type should not have a name.
Chris Lattner9fe38862003-06-19 17:00:31 +00005912
Eric Christophera66297a2009-07-25 02:45:27 +00005913 const AttrListPtr &NewCallerPAL = AttrListPtr::get(attrVec.begin(),
5914 attrVec.end());
Duncan Sandsad9a9e12008-01-06 18:27:01 +00005915
Chris Lattner9fe38862003-06-19 17:00:31 +00005916 Instruction *NC;
5917 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Gabor Greif051a9502008-04-06 20:25:17 +00005918 NC = InvokeInst::Create(Callee, II->getNormalDest(), II->getUnwindDest(),
Gabor Greifb1dbcd82008-05-15 10:04:30 +00005919 Args.begin(), Args.end(),
5920 Caller->getName(), Caller);
Reid Spencered3fa852007-07-30 19:53:57 +00005921 cast<InvokeInst>(NC)->setCallingConv(II->getCallingConv());
Devang Patel05988662008-09-25 21:00:45 +00005922 cast<InvokeInst>(NC)->setAttributes(NewCallerPAL);
Chris Lattner9fe38862003-06-19 17:00:31 +00005923 } else {
Gabor Greif051a9502008-04-06 20:25:17 +00005924 NC = CallInst::Create(Callee, Args.begin(), Args.end(),
5925 Caller->getName(), Caller);
Duncan Sandsdc024672007-11-27 13:23:08 +00005926 CallInst *CI = cast<CallInst>(Caller);
5927 if (CI->isTailCall())
Chris Lattnera9e92112005-05-06 06:48:21 +00005928 cast<CallInst>(NC)->setTailCall();
Duncan Sandsdc024672007-11-27 13:23:08 +00005929 cast<CallInst>(NC)->setCallingConv(CI->getCallingConv());
Devang Patel05988662008-09-25 21:00:45 +00005930 cast<CallInst>(NC)->setAttributes(NewCallerPAL);
Chris Lattner9fe38862003-06-19 17:00:31 +00005931 }
5932
Chris Lattner6934a042007-02-11 01:23:03 +00005933 // Insert a cast of the return type as necessary.
Chris Lattner9fe38862003-06-19 17:00:31 +00005934 Value *NV = NC;
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00005935 if (OldRetTy != NV->getType() && !Caller->use_empty()) {
Devang Patel9674d152009-10-14 17:29:00 +00005936 if (!NV->getType()->isVoidTy()) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00005937 Instruction::CastOps opcode = CastInst::getCastOpcode(NC, false,
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00005938 OldRetTy, false);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005939 NV = NC = CastInst::Create(opcode, NC, OldRetTy, "tmp");
Chris Lattnerbb609042003-10-30 00:46:41 +00005940
5941 // If this is an invoke instruction, we should insert it after the first
5942 // non-phi, instruction in the normal successor block.
5943 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Dan Gohman02dea8b2008-05-23 21:05:58 +00005944 BasicBlock::iterator I = II->getNormalDest()->getFirstNonPHI();
Chris Lattnerbb609042003-10-30 00:46:41 +00005945 InsertNewInstBefore(NC, *I);
5946 } else {
5947 // Otherwise, it's a call, just insert cast right after the call instr
5948 InsertNewInstBefore(NC, *Caller);
5949 }
Chris Lattnere5ecdb52009-08-30 06:22:51 +00005950 Worklist.AddUsersToWorkList(*Caller);
Chris Lattner9fe38862003-06-19 17:00:31 +00005951 } else {
Owen Anderson9e9a0d52009-07-30 23:03:37 +00005952 NV = UndefValue::get(Caller->getType());
Chris Lattner9fe38862003-06-19 17:00:31 +00005953 }
5954 }
5955
Devang Patel1bf5ebc2009-10-13 21:41:20 +00005956
Chris Lattner931f8f32009-08-31 05:17:58 +00005957 if (!Caller->use_empty())
Chris Lattner9fe38862003-06-19 17:00:31 +00005958 Caller->replaceAllUsesWith(NV);
Chris Lattner931f8f32009-08-31 05:17:58 +00005959
5960 EraseInstFromFunction(*Caller);
Chris Lattner9fe38862003-06-19 17:00:31 +00005961 return true;
5962}
5963
Duncan Sandscdb6d922007-09-17 10:26:40 +00005964// transformCallThroughTrampoline - Turn a call to a function created by the
5965// init_trampoline intrinsic into a direct call to the underlying function.
5966//
5967Instruction *InstCombiner::transformCallThroughTrampoline(CallSite CS) {
5968 Value *Callee = CS.getCalledValue();
5969 const PointerType *PTy = cast<PointerType>(Callee->getType());
5970 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
Devang Patel05988662008-09-25 21:00:45 +00005971 const AttrListPtr &Attrs = CS.getAttributes();
Duncan Sandsb0c9b932008-01-14 19:52:09 +00005972
5973 // If the call already has the 'nest' attribute somewhere then give up -
5974 // otherwise 'nest' would occur twice after splicing in the chain.
Devang Patel05988662008-09-25 21:00:45 +00005975 if (Attrs.hasAttrSomewhere(Attribute::Nest))
Duncan Sandsb0c9b932008-01-14 19:52:09 +00005976 return 0;
Duncan Sandscdb6d922007-09-17 10:26:40 +00005977
5978 IntrinsicInst *Tramp =
5979 cast<IntrinsicInst>(cast<BitCastInst>(Callee)->getOperand(0));
5980
Anton Korobeynikov0b12ecf2008-05-07 22:54:15 +00005981 Function *NestF = cast<Function>(Tramp->getOperand(2)->stripPointerCasts());
Duncan Sandscdb6d922007-09-17 10:26:40 +00005982 const PointerType *NestFPTy = cast<PointerType>(NestF->getType());
5983 const FunctionType *NestFTy = cast<FunctionType>(NestFPTy->getElementType());
5984
Devang Patel05988662008-09-25 21:00:45 +00005985 const AttrListPtr &NestAttrs = NestF->getAttributes();
Chris Lattner58d74912008-03-12 17:45:29 +00005986 if (!NestAttrs.isEmpty()) {
Duncan Sandscdb6d922007-09-17 10:26:40 +00005987 unsigned NestIdx = 1;
5988 const Type *NestTy = 0;
Devang Patel05988662008-09-25 21:00:45 +00005989 Attributes NestAttr = Attribute::None;
Duncan Sandscdb6d922007-09-17 10:26:40 +00005990
5991 // Look for a parameter marked with the 'nest' attribute.
5992 for (FunctionType::param_iterator I = NestFTy->param_begin(),
5993 E = NestFTy->param_end(); I != E; ++NestIdx, ++I)
Devang Patel05988662008-09-25 21:00:45 +00005994 if (NestAttrs.paramHasAttr(NestIdx, Attribute::Nest)) {
Duncan Sandscdb6d922007-09-17 10:26:40 +00005995 // Record the parameter type and any other attributes.
5996 NestTy = *I;
Devang Patel19c87462008-09-26 22:53:05 +00005997 NestAttr = NestAttrs.getParamAttributes(NestIdx);
Duncan Sandscdb6d922007-09-17 10:26:40 +00005998 break;
5999 }
6000
6001 if (NestTy) {
6002 Instruction *Caller = CS.getInstruction();
6003 std::vector<Value*> NewArgs;
6004 NewArgs.reserve(unsigned(CS.arg_end()-CS.arg_begin())+1);
6005
Devang Patel05988662008-09-25 21:00:45 +00006006 SmallVector<AttributeWithIndex, 8> NewAttrs;
Chris Lattner58d74912008-03-12 17:45:29 +00006007 NewAttrs.reserve(Attrs.getNumSlots() + 1);
Duncan Sandsb0c9b932008-01-14 19:52:09 +00006008
Duncan Sandscdb6d922007-09-17 10:26:40 +00006009 // Insert the nest argument into the call argument list, which may
Duncan Sandsb0c9b932008-01-14 19:52:09 +00006010 // mean appending it. Likewise for attributes.
6011
Devang Patel19c87462008-09-26 22:53:05 +00006012 // Add any result attributes.
6013 if (Attributes Attr = Attrs.getRetAttributes())
Devang Patel05988662008-09-25 21:00:45 +00006014 NewAttrs.push_back(AttributeWithIndex::get(0, Attr));
Duncan Sandsb0c9b932008-01-14 19:52:09 +00006015
Duncan Sandscdb6d922007-09-17 10:26:40 +00006016 {
6017 unsigned Idx = 1;
6018 CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
6019 do {
6020 if (Idx == NestIdx) {
Duncan Sandsb0c9b932008-01-14 19:52:09 +00006021 // Add the chain argument and attributes.
Duncan Sandscdb6d922007-09-17 10:26:40 +00006022 Value *NestVal = Tramp->getOperand(3);
6023 if (NestVal->getType() != NestTy)
6024 NestVal = new BitCastInst(NestVal, NestTy, "nest", Caller);
6025 NewArgs.push_back(NestVal);
Devang Patel05988662008-09-25 21:00:45 +00006026 NewAttrs.push_back(AttributeWithIndex::get(NestIdx, NestAttr));
Duncan Sandscdb6d922007-09-17 10:26:40 +00006027 }
6028
6029 if (I == E)
6030 break;
6031
Duncan Sandsb0c9b932008-01-14 19:52:09 +00006032 // Add the original argument and attributes.
Duncan Sandscdb6d922007-09-17 10:26:40 +00006033 NewArgs.push_back(*I);
Devang Patel19c87462008-09-26 22:53:05 +00006034 if (Attributes Attr = Attrs.getParamAttributes(Idx))
Duncan Sandsb0c9b932008-01-14 19:52:09 +00006035 NewAttrs.push_back
Devang Patel05988662008-09-25 21:00:45 +00006036 (AttributeWithIndex::get(Idx + (Idx >= NestIdx), Attr));
Duncan Sandscdb6d922007-09-17 10:26:40 +00006037
6038 ++Idx, ++I;
6039 } while (1);
6040 }
6041
Devang Patel19c87462008-09-26 22:53:05 +00006042 // Add any function attributes.
6043 if (Attributes Attr = Attrs.getFnAttributes())
6044 NewAttrs.push_back(AttributeWithIndex::get(~0, Attr));
6045
Duncan Sandscdb6d922007-09-17 10:26:40 +00006046 // The trampoline may have been bitcast to a bogus type (FTy).
6047 // Handle this by synthesizing a new function type, equal to FTy
Duncan Sandsb0c9b932008-01-14 19:52:09 +00006048 // with the chain parameter inserted.
Duncan Sandscdb6d922007-09-17 10:26:40 +00006049
Duncan Sandscdb6d922007-09-17 10:26:40 +00006050 std::vector<const Type*> NewTypes;
Duncan Sandscdb6d922007-09-17 10:26:40 +00006051 NewTypes.reserve(FTy->getNumParams()+1);
6052
Duncan Sandscdb6d922007-09-17 10:26:40 +00006053 // Insert the chain's type into the list of parameter types, which may
Duncan Sandsb0c9b932008-01-14 19:52:09 +00006054 // mean appending it.
Duncan Sandscdb6d922007-09-17 10:26:40 +00006055 {
6056 unsigned Idx = 1;
6057 FunctionType::param_iterator I = FTy->param_begin(),
6058 E = FTy->param_end();
6059
6060 do {
Duncan Sandsb0c9b932008-01-14 19:52:09 +00006061 if (Idx == NestIdx)
6062 // Add the chain's type.
Duncan Sandscdb6d922007-09-17 10:26:40 +00006063 NewTypes.push_back(NestTy);
Duncan Sandscdb6d922007-09-17 10:26:40 +00006064
6065 if (I == E)
6066 break;
6067
Duncan Sandsb0c9b932008-01-14 19:52:09 +00006068 // Add the original type.
Duncan Sandscdb6d922007-09-17 10:26:40 +00006069 NewTypes.push_back(*I);
Duncan Sandscdb6d922007-09-17 10:26:40 +00006070
6071 ++Idx, ++I;
6072 } while (1);
6073 }
6074
6075 // Replace the trampoline call with a direct call. Let the generic
6076 // code sort out any function type mismatches.
Owen Andersondebcb012009-07-29 22:17:13 +00006077 FunctionType *NewFTy = FunctionType::get(FTy->getReturnType(), NewTypes,
Owen Andersond672ecb2009-07-03 00:17:18 +00006078 FTy->isVarArg());
6079 Constant *NewCallee =
Owen Andersondebcb012009-07-29 22:17:13 +00006080 NestF->getType() == PointerType::getUnqual(NewFTy) ?
Owen Andersonbaf3c402009-07-29 18:55:55 +00006081 NestF : ConstantExpr::getBitCast(NestF,
Owen Andersondebcb012009-07-29 22:17:13 +00006082 PointerType::getUnqual(NewFTy));
Eric Christophera66297a2009-07-25 02:45:27 +00006083 const AttrListPtr &NewPAL = AttrListPtr::get(NewAttrs.begin(),
6084 NewAttrs.end());
Duncan Sandscdb6d922007-09-17 10:26:40 +00006085
6086 Instruction *NewCaller;
6087 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Gabor Greif051a9502008-04-06 20:25:17 +00006088 NewCaller = InvokeInst::Create(NewCallee,
6089 II->getNormalDest(), II->getUnwindDest(),
6090 NewArgs.begin(), NewArgs.end(),
6091 Caller->getName(), Caller);
Duncan Sandscdb6d922007-09-17 10:26:40 +00006092 cast<InvokeInst>(NewCaller)->setCallingConv(II->getCallingConv());
Devang Patel05988662008-09-25 21:00:45 +00006093 cast<InvokeInst>(NewCaller)->setAttributes(NewPAL);
Duncan Sandscdb6d922007-09-17 10:26:40 +00006094 } else {
Gabor Greif051a9502008-04-06 20:25:17 +00006095 NewCaller = CallInst::Create(NewCallee, NewArgs.begin(), NewArgs.end(),
6096 Caller->getName(), Caller);
Duncan Sandscdb6d922007-09-17 10:26:40 +00006097 if (cast<CallInst>(Caller)->isTailCall())
6098 cast<CallInst>(NewCaller)->setTailCall();
6099 cast<CallInst>(NewCaller)->
6100 setCallingConv(cast<CallInst>(Caller)->getCallingConv());
Devang Patel05988662008-09-25 21:00:45 +00006101 cast<CallInst>(NewCaller)->setAttributes(NewPAL);
Duncan Sandscdb6d922007-09-17 10:26:40 +00006102 }
Devang Patel9674d152009-10-14 17:29:00 +00006103 if (!Caller->getType()->isVoidTy())
Duncan Sandscdb6d922007-09-17 10:26:40 +00006104 Caller->replaceAllUsesWith(NewCaller);
6105 Caller->eraseFromParent();
Chris Lattner7a1e9242009-08-30 06:13:40 +00006106 Worklist.Remove(Caller);
Duncan Sandscdb6d922007-09-17 10:26:40 +00006107 return 0;
6108 }
6109 }
6110
6111 // Replace the trampoline call with a direct call. Since there is no 'nest'
6112 // parameter, there is no need to adjust the argument list. Let the generic
6113 // code sort out any function type mismatches.
6114 Constant *NewCallee =
Owen Andersond672ecb2009-07-03 00:17:18 +00006115 NestF->getType() == PTy ? NestF :
Owen Andersonbaf3c402009-07-29 18:55:55 +00006116 ConstantExpr::getBitCast(NestF, PTy);
Duncan Sandscdb6d922007-09-17 10:26:40 +00006117 CS.setCalledFunction(NewCallee);
6118 return CS.getInstruction();
6119}
6120
Reid Spencere4d87aa2006-12-23 06:05:41 +00006121
Chris Lattner473945d2002-05-06 18:06:38 +00006122
Chris Lattner7e708292002-06-25 16:13:24 +00006123Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
Chris Lattnerc514c1f2009-11-27 00:29:05 +00006124 SmallVector<Value*, 8> Ops(GEP.op_begin(), GEP.op_end());
6125
6126 if (Value *V = SimplifyGEPInst(&Ops[0], Ops.size(), TD))
6127 return ReplaceInstUsesWith(GEP, V);
6128
Chris Lattner620ce142004-05-07 22:09:22 +00006129 Value *PtrOp = GEP.getOperand(0);
Chris Lattnerc6bd1952004-02-22 05:25:17 +00006130
Chris Lattnere87597f2004-10-16 18:11:37 +00006131 if (isa<UndefValue>(GEP.getOperand(0)))
Owen Anderson9e9a0d52009-07-30 23:03:37 +00006132 return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00006133
Chris Lattner28977af2004-04-05 01:30:19 +00006134 // Eliminate unneeded casts for indices.
Chris Lattnerccf4b342009-08-30 04:49:01 +00006135 if (TD) {
6136 bool MadeChange = false;
6137 unsigned PtrSize = TD->getPointerSizeInBits();
6138
6139 gep_type_iterator GTI = gep_type_begin(GEP);
6140 for (User::op_iterator I = GEP.op_begin() + 1, E = GEP.op_end();
6141 I != E; ++I, ++GTI) {
6142 if (!isa<SequentialType>(*GTI)) continue;
6143
Chris Lattnercb69a4e2004-04-07 18:38:20 +00006144 // If we are using a wider index than needed for this platform, shrink it
Chris Lattnerccf4b342009-08-30 04:49:01 +00006145 // to what we need. If narrower, sign-extend it to what we need. This
6146 // explicit cast can make subsequent optimizations more obvious.
6147 unsigned OpBits = cast<IntegerType>((*I)->getType())->getBitWidth();
Chris Lattnerccf4b342009-08-30 04:49:01 +00006148 if (OpBits == PtrSize)
6149 continue;
6150
Chris Lattner2345d1d2009-08-30 20:01:10 +00006151 *I = Builder->CreateIntCast(*I, TD->getIntPtrType(GEP.getContext()),true);
Chris Lattnerccf4b342009-08-30 04:49:01 +00006152 MadeChange = true;
Chris Lattner28977af2004-04-05 01:30:19 +00006153 }
Chris Lattnerccf4b342009-08-30 04:49:01 +00006154 if (MadeChange) return &GEP;
Chris Lattnerdb9654e2007-03-25 20:43:09 +00006155 }
Chris Lattner28977af2004-04-05 01:30:19 +00006156
Chris Lattner90ac28c2002-08-02 19:29:35 +00006157 // Combine Indices - If the source pointer to this getelementptr instruction
6158 // is a getelementptr instruction, combine the indices of the two
6159 // getelementptr instructions into a single instruction.
6160 //
Dan Gohmand6aa02d2009-07-28 01:40:03 +00006161 if (GEPOperator *Src = dyn_cast<GEPOperator>(PtrOp)) {
Chris Lattner620ce142004-05-07 22:09:22 +00006162 // Note that if our source is a gep chain itself that we wait for that
6163 // chain to be resolved before we perform this transformation. This
6164 // avoids us creating a TON of code in some cases.
6165 //
Chris Lattnerf9b91bb2009-08-30 05:08:50 +00006166 if (GetElementPtrInst *SrcGEP =
6167 dyn_cast<GetElementPtrInst>(Src->getOperand(0)))
6168 if (SrcGEP->getNumOperands() == 2)
6169 return 0; // Wait until our source is folded to completion.
Chris Lattner620ce142004-05-07 22:09:22 +00006170
Chris Lattner72588fc2007-02-15 22:48:32 +00006171 SmallVector<Value*, 8> Indices;
Chris Lattner620ce142004-05-07 22:09:22 +00006172
6173 // Find out whether the last index in the source GEP is a sequential idx.
6174 bool EndsWithSequential = false;
Chris Lattnerab984842009-08-30 05:30:55 +00006175 for (gep_type_iterator I = gep_type_begin(*Src), E = gep_type_end(*Src);
6176 I != E; ++I)
Chris Lattnerbe97b4e2004-05-08 22:41:42 +00006177 EndsWithSequential = !isa<StructType>(*I);
Misha Brukmanfd939082005-04-21 23:48:37 +00006178
Chris Lattner90ac28c2002-08-02 19:29:35 +00006179 // Can we combine the two pointer arithmetics offsets?
Chris Lattner620ce142004-05-07 22:09:22 +00006180 if (EndsWithSequential) {
Chris Lattnerdecd0812003-03-05 22:33:14 +00006181 // Replace: gep (gep %P, long B), long A, ...
6182 // With: T = long A+B; gep %P, T, ...
6183 //
Chris Lattnerf9b91bb2009-08-30 05:08:50 +00006184 Value *Sum;
6185 Value *SO1 = Src->getOperand(Src->getNumOperands()-1);
6186 Value *GO1 = GEP.getOperand(1);
Owen Andersona7235ea2009-07-31 20:28:14 +00006187 if (SO1 == Constant::getNullValue(SO1->getType())) {
Chris Lattner28977af2004-04-05 01:30:19 +00006188 Sum = GO1;
Owen Andersona7235ea2009-07-31 20:28:14 +00006189 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
Chris Lattner28977af2004-04-05 01:30:19 +00006190 Sum = SO1;
6191 } else {
Chris Lattnerab984842009-08-30 05:30:55 +00006192 // If they aren't the same type, then the input hasn't been processed
6193 // by the loop above yet (which canonicalizes sequential index types to
6194 // intptr_t). Just avoid transforming this until the input has been
6195 // normalized.
6196 if (SO1->getType() != GO1->getType())
6197 return 0;
Chris Lattnerf925cbd2009-08-30 18:50:58 +00006198 Sum = Builder->CreateAdd(SO1, GO1, PtrOp->getName()+".sum");
Chris Lattner28977af2004-04-05 01:30:19 +00006199 }
Chris Lattner620ce142004-05-07 22:09:22 +00006200
Chris Lattnerab984842009-08-30 05:30:55 +00006201 // Update the GEP in place if possible.
Chris Lattnerf9b91bb2009-08-30 05:08:50 +00006202 if (Src->getNumOperands() == 2) {
6203 GEP.setOperand(0, Src->getOperand(0));
Chris Lattner620ce142004-05-07 22:09:22 +00006204 GEP.setOperand(1, Sum);
6205 return &GEP;
Chris Lattner620ce142004-05-07 22:09:22 +00006206 }
Chris Lattnerab984842009-08-30 05:30:55 +00006207 Indices.append(Src->op_begin()+1, Src->op_end()-1);
Chris Lattnerccf4b342009-08-30 04:49:01 +00006208 Indices.push_back(Sum);
Chris Lattnerab984842009-08-30 05:30:55 +00006209 Indices.append(GEP.op_begin()+2, GEP.op_end());
Misha Brukmanfd939082005-04-21 23:48:37 +00006210 } else if (isa<Constant>(*GEP.idx_begin()) &&
Chris Lattner28977af2004-04-05 01:30:19 +00006211 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
Chris Lattnerf9b91bb2009-08-30 05:08:50 +00006212 Src->getNumOperands() != 1) {
Chris Lattner90ac28c2002-08-02 19:29:35 +00006213 // Otherwise we can do the fold if the first index of the GEP is a zero
Chris Lattnerab984842009-08-30 05:30:55 +00006214 Indices.append(Src->op_begin()+1, Src->op_end());
6215 Indices.append(GEP.idx_begin()+1, GEP.idx_end());
Chris Lattner90ac28c2002-08-02 19:29:35 +00006216 }
6217
Dan Gohmanf8dbee72009-09-07 23:54:19 +00006218 if (!Indices.empty())
6219 return (cast<GEPOperator>(&GEP)->isInBounds() &&
6220 Src->isInBounds()) ?
6221 GetElementPtrInst::CreateInBounds(Src->getOperand(0), Indices.begin(),
6222 Indices.end(), GEP.getName()) :
Chris Lattnerf9b91bb2009-08-30 05:08:50 +00006223 GetElementPtrInst::Create(Src->getOperand(0), Indices.begin(),
Chris Lattnerccf4b342009-08-30 04:49:01 +00006224 Indices.end(), GEP.getName());
Chris Lattner6e24d832009-08-30 05:00:50 +00006225 }
6226
Chris Lattnerf9b91bb2009-08-30 05:08:50 +00006227 // Handle gep(bitcast x) and gep(gep x, 0, 0, 0).
6228 if (Value *X = getBitCastOperand(PtrOp)) {
Chris Lattner6e24d832009-08-30 05:00:50 +00006229 assert(isa<PointerType>(X->getType()) && "Must be cast from pointer");
Chris Lattner963f4ba2009-08-30 20:36:46 +00006230
Chris Lattner2de23192009-08-30 20:38:21 +00006231 // If the input bitcast is actually "bitcast(bitcast(x))", then we don't
6232 // want to change the gep until the bitcasts are eliminated.
6233 if (getBitCastOperand(X)) {
6234 Worklist.AddValue(PtrOp);
6235 return 0;
6236 }
6237
Chris Lattnerc514c1f2009-11-27 00:29:05 +00006238 bool HasZeroPointerIndex = false;
6239 if (ConstantInt *C = dyn_cast<ConstantInt>(GEP.getOperand(1)))
6240 HasZeroPointerIndex = C->isZero();
6241
Chris Lattner963f4ba2009-08-30 20:36:46 +00006242 // Transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ...
6243 // into : GEP [10 x i8]* X, i32 0, ...
6244 //
6245 // Likewise, transform: GEP (bitcast i8* X to [0 x i8]*), i32 0, ...
6246 // into : GEP i8* X, ...
6247 //
6248 // This occurs when the program declares an array extern like "int X[];"
Chris Lattner6e24d832009-08-30 05:00:50 +00006249 if (HasZeroPointerIndex) {
Chris Lattnereed48272005-09-13 00:40:14 +00006250 const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
6251 const PointerType *XTy = cast<PointerType>(X->getType());
Duncan Sands5b7cfb02009-03-02 09:18:21 +00006252 if (const ArrayType *CATy =
6253 dyn_cast<ArrayType>(CPTy->getElementType())) {
6254 // GEP (bitcast i8* X to [0 x i8]*), i32 0, ... ?
6255 if (CATy->getElementType() == XTy->getElementType()) {
6256 // -> GEP i8* X, ...
6257 SmallVector<Value*, 8> Indices(GEP.idx_begin()+1, GEP.idx_end());
Dan Gohmanf8dbee72009-09-07 23:54:19 +00006258 return cast<GEPOperator>(&GEP)->isInBounds() ?
6259 GetElementPtrInst::CreateInBounds(X, Indices.begin(), Indices.end(),
6260 GEP.getName()) :
Dan Gohmand6aa02d2009-07-28 01:40:03 +00006261 GetElementPtrInst::Create(X, Indices.begin(), Indices.end(),
6262 GEP.getName());
Chris Lattner963f4ba2009-08-30 20:36:46 +00006263 }
6264
6265 if (const ArrayType *XATy = dyn_cast<ArrayType>(XTy->getElementType())){
Duncan Sands5b7cfb02009-03-02 09:18:21 +00006266 // GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ... ?
Chris Lattnereed48272005-09-13 00:40:14 +00006267 if (CATy->getElementType() == XATy->getElementType()) {
Duncan Sands5b7cfb02009-03-02 09:18:21 +00006268 // -> GEP [10 x i8]* X, i32 0, ...
Chris Lattnereed48272005-09-13 00:40:14 +00006269 // At this point, we know that the cast source type is a pointer
6270 // to an array of the same type as the destination pointer
6271 // array. Because the array type is never stepped over (there
6272 // is a leading zero) we can fold the cast into this GEP.
6273 GEP.setOperand(0, X);
6274 return &GEP;
6275 }
Duncan Sands5b7cfb02009-03-02 09:18:21 +00006276 }
6277 }
Chris Lattnereed48272005-09-13 00:40:14 +00006278 } else if (GEP.getNumOperands() == 2) {
6279 // Transform things like:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +00006280 // %t = getelementptr i32* bitcast ([2 x i32]* %str to i32*), i32 %V
6281 // into: %t1 = getelementptr [2 x i32]* %str, i32 0, i32 %V; bitcast
Chris Lattnereed48272005-09-13 00:40:14 +00006282 const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
6283 const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
Dan Gohmance9fe9f2009-07-21 23:21:54 +00006284 if (TD && isa<ArrayType>(SrcElTy) &&
Duncan Sands777d2302009-05-09 07:06:46 +00006285 TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
6286 TD->getTypeAllocSize(ResElTy)) {
David Greeneb8f74792007-09-04 15:46:09 +00006287 Value *Idx[2];
Chris Lattner4de84762010-01-04 07:02:48 +00006288 Idx[0] = Constant::getNullValue(Type::getInt32Ty(GEP.getContext()));
David Greeneb8f74792007-09-04 15:46:09 +00006289 Idx[1] = GEP.getOperand(1);
Dan Gohmanf8dbee72009-09-07 23:54:19 +00006290 Value *NewGEP = cast<GEPOperator>(&GEP)->isInBounds() ?
6291 Builder->CreateInBoundsGEP(X, Idx, Idx + 2, GEP.getName()) :
Chris Lattnerf925cbd2009-08-30 18:50:58 +00006292 Builder->CreateGEP(X, Idx, Idx + 2, GEP.getName());
Reid Spencer3da59db2006-11-27 01:05:10 +00006293 // V and GEP are both pointer types --> BitCast
Chris Lattnerf925cbd2009-08-30 18:50:58 +00006294 return new BitCastInst(NewGEP, GEP.getType());
Chris Lattnerc6bd1952004-02-22 05:25:17 +00006295 }
Chris Lattner7835cdd2005-09-13 18:36:04 +00006296
6297 // Transform things like:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +00006298 // getelementptr i8* bitcast ([100 x double]* X to i8*), i32 %tmp
Chris Lattner7835cdd2005-09-13 18:36:04 +00006299 // (where tmp = 8*tmp2) into:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +00006300 // getelementptr [100 x double]* %arr, i32 0, i32 %tmp2; bitcast
Chris Lattner7835cdd2005-09-13 18:36:04 +00006301
Chris Lattner4de84762010-01-04 07:02:48 +00006302 if (TD && isa<ArrayType>(SrcElTy) &&
6303 ResElTy == Type::getInt8Ty(GEP.getContext())) {
Chris Lattner7835cdd2005-09-13 18:36:04 +00006304 uint64_t ArrayEltSize =
Duncan Sands777d2302009-05-09 07:06:46 +00006305 TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType());
Chris Lattner7835cdd2005-09-13 18:36:04 +00006306
6307 // Check to see if "tmp" is a scale by a multiple of ArrayEltSize. We
6308 // allow either a mul, shift, or constant here.
6309 Value *NewIdx = 0;
6310 ConstantInt *Scale = 0;
6311 if (ArrayEltSize == 1) {
6312 NewIdx = GEP.getOperand(1);
Chris Lattnerab984842009-08-30 05:30:55 +00006313 Scale = ConstantInt::get(cast<IntegerType>(NewIdx->getType()), 1);
Chris Lattner7835cdd2005-09-13 18:36:04 +00006314 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
Owen Andersoneed707b2009-07-24 23:12:02 +00006315 NewIdx = ConstantInt::get(CI->getType(), 1);
Chris Lattner7835cdd2005-09-13 18:36:04 +00006316 Scale = CI;
6317 } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
6318 if (Inst->getOpcode() == Instruction::Shl &&
6319 isa<ConstantInt>(Inst->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00006320 ConstantInt *ShAmt = cast<ConstantInt>(Inst->getOperand(1));
6321 uint32_t ShAmtVal = ShAmt->getLimitedValue(64);
Owen Andersoneed707b2009-07-24 23:12:02 +00006322 Scale = ConstantInt::get(cast<IntegerType>(Inst->getType()),
Dan Gohman6de29f82009-06-15 22:12:54 +00006323 1ULL << ShAmtVal);
Chris Lattner7835cdd2005-09-13 18:36:04 +00006324 NewIdx = Inst->getOperand(0);
6325 } else if (Inst->getOpcode() == Instruction::Mul &&
6326 isa<ConstantInt>(Inst->getOperand(1))) {
6327 Scale = cast<ConstantInt>(Inst->getOperand(1));
6328 NewIdx = Inst->getOperand(0);
6329 }
6330 }
Wojciech Matyjewiczed223252007-12-12 15:21:32 +00006331
Chris Lattner7835cdd2005-09-13 18:36:04 +00006332 // If the index will be to exactly the right offset with the scale taken
Wojciech Matyjewiczed223252007-12-12 15:21:32 +00006333 // out, perform the transformation. Note, we don't know whether Scale is
6334 // signed or not. We'll use unsigned version of division/modulo
6335 // operation after making sure Scale doesn't have the sign bit set.
Chris Lattner58b1ac72009-02-25 18:20:01 +00006336 if (ArrayEltSize && Scale && Scale->getSExtValue() >= 0LL &&
Wojciech Matyjewiczed223252007-12-12 15:21:32 +00006337 Scale->getZExtValue() % ArrayEltSize == 0) {
Owen Andersoneed707b2009-07-24 23:12:02 +00006338 Scale = ConstantInt::get(Scale->getType(),
Wojciech Matyjewiczed223252007-12-12 15:21:32 +00006339 Scale->getZExtValue() / ArrayEltSize);
Reid Spencerb83eb642006-10-20 07:07:24 +00006340 if (Scale->getZExtValue() != 1) {
Chris Lattner878daed2009-08-30 05:56:44 +00006341 Constant *C = ConstantExpr::getIntegerCast(Scale, NewIdx->getType(),
6342 false /*ZExt*/);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00006343 NewIdx = Builder->CreateMul(NewIdx, C, "idxscale");
Chris Lattner7835cdd2005-09-13 18:36:04 +00006344 }
6345
6346 // Insert the new GEP instruction.
David Greeneb8f74792007-09-04 15:46:09 +00006347 Value *Idx[2];
Chris Lattner4de84762010-01-04 07:02:48 +00006348 Idx[0] = Constant::getNullValue(Type::getInt32Ty(GEP.getContext()));
David Greeneb8f74792007-09-04 15:46:09 +00006349 Idx[1] = NewIdx;
Dan Gohmanf8dbee72009-09-07 23:54:19 +00006350 Value *NewGEP = cast<GEPOperator>(&GEP)->isInBounds() ?
6351 Builder->CreateInBoundsGEP(X, Idx, Idx + 2, GEP.getName()) :
6352 Builder->CreateGEP(X, Idx, Idx + 2, GEP.getName());
Reid Spencer3da59db2006-11-27 01:05:10 +00006353 // The NewGEP must be pointer typed, so must the old one -> BitCast
6354 return new BitCastInst(NewGEP, GEP.getType());
Chris Lattner7835cdd2005-09-13 18:36:04 +00006355 }
6356 }
Chris Lattnerc6bd1952004-02-22 05:25:17 +00006357 }
Chris Lattner8a2a3112001-12-14 16:52:21 +00006358 }
Chris Lattner58407792009-01-09 04:53:57 +00006359
Chris Lattner46cd5a12009-01-09 05:44:56 +00006360 /// See if we can simplify:
Chris Lattner873ff012009-08-30 05:55:36 +00006361 /// X = bitcast A* to B*
Chris Lattner46cd5a12009-01-09 05:44:56 +00006362 /// Y = gep X, <...constant indices...>
6363 /// into a gep of the original struct. This is important for SROA and alias
6364 /// analysis of unions. If "A" is also a bitcast, wait for A/X to be merged.
Chris Lattner58407792009-01-09 04:53:57 +00006365 if (BitCastInst *BCI = dyn_cast<BitCastInst>(PtrOp)) {
Dan Gohmance9fe9f2009-07-21 23:21:54 +00006366 if (TD &&
6367 !isa<BitCastInst>(BCI->getOperand(0)) && GEP.hasAllConstantIndices()) {
Chris Lattner46cd5a12009-01-09 05:44:56 +00006368 // Determine how much the GEP moves the pointer. We are guaranteed to get
6369 // a constant back from EmitGEPOffset.
Chris Lattner02446fc2010-01-04 07:37:31 +00006370 ConstantInt *OffsetV = cast<ConstantInt>(EmitGEPOffset(&GEP));
Chris Lattner46cd5a12009-01-09 05:44:56 +00006371 int64_t Offset = OffsetV->getSExtValue();
6372
6373 // If this GEP instruction doesn't move the pointer, just replace the GEP
6374 // with a bitcast of the real input to the dest type.
6375 if (Offset == 0) {
6376 // If the bitcast is of an allocation, and the allocation will be
6377 // converted to match the type of the cast, don't touch this.
Victor Hernandez7b929da2009-10-23 21:09:37 +00006378 if (isa<AllocaInst>(BCI->getOperand(0)) ||
Victor Hernandez83d63912009-09-18 22:35:49 +00006379 isMalloc(BCI->getOperand(0))) {
Chris Lattner46cd5a12009-01-09 05:44:56 +00006380 // See if the bitcast simplifies, if so, don't nuke this GEP yet.
6381 if (Instruction *I = visitBitCast(*BCI)) {
6382 if (I != BCI) {
6383 I->takeName(BCI);
6384 BCI->getParent()->getInstList().insert(BCI, I);
6385 ReplaceInstUsesWith(*BCI, I);
6386 }
6387 return &GEP;
Chris Lattner58407792009-01-09 04:53:57 +00006388 }
Chris Lattner58407792009-01-09 04:53:57 +00006389 }
Chris Lattner46cd5a12009-01-09 05:44:56 +00006390 return new BitCastInst(BCI->getOperand(0), GEP.getType());
Chris Lattner58407792009-01-09 04:53:57 +00006391 }
Chris Lattner46cd5a12009-01-09 05:44:56 +00006392
6393 // Otherwise, if the offset is non-zero, we need to find out if there is a
6394 // field at Offset in 'A's type. If so, we can pull the cast through the
6395 // GEP.
6396 SmallVector<Value*, 8> NewIndices;
6397 const Type *InTy =
6398 cast<PointerType>(BCI->getOperand(0)->getType())->getElementType();
Chris Lattner80f43d32010-01-04 07:53:58 +00006399 if (FindElementAtOffset(InTy, Offset, NewIndices)) {
Dan Gohmanf8dbee72009-09-07 23:54:19 +00006400 Value *NGEP = cast<GEPOperator>(&GEP)->isInBounds() ?
6401 Builder->CreateInBoundsGEP(BCI->getOperand(0), NewIndices.begin(),
6402 NewIndices.end()) :
6403 Builder->CreateGEP(BCI->getOperand(0), NewIndices.begin(),
6404 NewIndices.end());
Chris Lattnerf925cbd2009-08-30 18:50:58 +00006405
6406 if (NGEP->getType() == GEP.getType())
6407 return ReplaceInstUsesWith(GEP, NGEP);
Chris Lattner46cd5a12009-01-09 05:44:56 +00006408 NGEP->takeName(&GEP);
6409 return new BitCastInst(NGEP, GEP.getType());
6410 }
Chris Lattner58407792009-01-09 04:53:57 +00006411 }
6412 }
6413
Chris Lattner8a2a3112001-12-14 16:52:21 +00006414 return 0;
6415}
6416
Victor Hernandez66284e02009-10-24 04:23:03 +00006417Instruction *InstCombiner::visitFree(Instruction &FI) {
6418 Value *Op = FI.getOperand(1);
6419
6420 // free undef -> unreachable.
6421 if (isa<UndefValue>(Op)) {
6422 // Insert a new store to null because we cannot modify the CFG here.
Chris Lattner4de84762010-01-04 07:02:48 +00006423 new StoreInst(ConstantInt::getTrue(FI.getContext()),
6424 UndefValue::get(Type::getInt1PtrTy(FI.getContext())), &FI);
Victor Hernandez66284e02009-10-24 04:23:03 +00006425 return EraseInstFromFunction(FI);
6426 }
6427
6428 // If we have 'free null' delete the instruction. This can happen in stl code
6429 // when lots of inlining happens.
6430 if (isa<ConstantPointerNull>(Op))
6431 return EraseInstFromFunction(FI);
6432
Victor Hernandez046e78c2009-10-26 23:43:48 +00006433 // If we have a malloc call whose only use is a free call, delete both.
Dan Gohman7f712a12009-10-27 00:11:02 +00006434 if (isMalloc(Op)) {
Victor Hernandez66284e02009-10-24 04:23:03 +00006435 if (CallInst* CI = extractMallocCallFromBitCast(Op)) {
6436 if (Op->hasOneUse() && CI->hasOneUse()) {
6437 EraseInstFromFunction(FI);
6438 EraseInstFromFunction(*CI);
6439 return EraseInstFromFunction(*cast<Instruction>(Op));
6440 }
6441 } else {
6442 // Op is a call to malloc
6443 if (Op->hasOneUse()) {
6444 EraseInstFromFunction(FI);
6445 return EraseInstFromFunction(*cast<Instruction>(Op));
6446 }
6447 }
Dan Gohman7f712a12009-10-27 00:11:02 +00006448 }
Victor Hernandez66284e02009-10-24 04:23:03 +00006449
6450 return 0;
6451}
Chris Lattner67b1e1b2003-12-07 01:24:23 +00006452
Chris Lattner3284d1f2007-04-15 00:07:55 +00006453
Chris Lattner2f503e62005-01-31 05:36:43 +00006454
Chris Lattnerc4d10eb2003-06-04 04:46:00 +00006455Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
6456 // Change br (not X), label True, label False to: br X, label False, True
Reid Spencer4b828e62005-06-18 17:37:34 +00006457 Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +00006458 BasicBlock *TrueDest;
6459 BasicBlock *FalseDest;
Dan Gohman4ae51262009-08-12 16:23:25 +00006460 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
Chris Lattneracd1f0f2004-07-30 07:50:03 +00006461 !isa<Constant>(X)) {
6462 // Swap Destinations and condition...
6463 BI.setCondition(X);
6464 BI.setSuccessor(0, FalseDest);
6465 BI.setSuccessor(1, TrueDest);
6466 return &BI;
6467 }
6468
Reid Spencere4d87aa2006-12-23 06:05:41 +00006469 // Cannonicalize fcmp_one -> fcmp_oeq
6470 FCmpInst::Predicate FPred; Value *Y;
6471 if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)),
Chris Lattner7a1e9242009-08-30 06:13:40 +00006472 TrueDest, FalseDest)) &&
6473 BI.getCondition()->hasOneUse())
6474 if (FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
6475 FPred == FCmpInst::FCMP_OGE) {
6476 FCmpInst *Cond = cast<FCmpInst>(BI.getCondition());
6477 Cond->setPredicate(FCmpInst::getInversePredicate(FPred));
6478
6479 // Swap Destinations and condition.
Reid Spencere4d87aa2006-12-23 06:05:41 +00006480 BI.setSuccessor(0, FalseDest);
6481 BI.setSuccessor(1, TrueDest);
Chris Lattner7a1e9242009-08-30 06:13:40 +00006482 Worklist.Add(Cond);
Reid Spencere4d87aa2006-12-23 06:05:41 +00006483 return &BI;
6484 }
6485
6486 // Cannonicalize icmp_ne -> icmp_eq
6487 ICmpInst::Predicate IPred;
6488 if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
Chris Lattner7a1e9242009-08-30 06:13:40 +00006489 TrueDest, FalseDest)) &&
6490 BI.getCondition()->hasOneUse())
6491 if (IPred == ICmpInst::ICMP_NE || IPred == ICmpInst::ICMP_ULE ||
6492 IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
6493 IPred == ICmpInst::ICMP_SGE) {
6494 ICmpInst *Cond = cast<ICmpInst>(BI.getCondition());
6495 Cond->setPredicate(ICmpInst::getInversePredicate(IPred));
6496 // Swap Destinations and condition.
Chris Lattner40f5d702003-06-04 05:10:11 +00006497 BI.setSuccessor(0, FalseDest);
6498 BI.setSuccessor(1, TrueDest);
Chris Lattner7a1e9242009-08-30 06:13:40 +00006499 Worklist.Add(Cond);
Chris Lattner40f5d702003-06-04 05:10:11 +00006500 return &BI;
6501 }
Misha Brukmanfd939082005-04-21 23:48:37 +00006502
Chris Lattnerc4d10eb2003-06-04 04:46:00 +00006503 return 0;
6504}
Chris Lattner0864acf2002-11-04 16:18:53 +00006505
Chris Lattner46238a62004-07-03 00:26:11 +00006506Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
6507 Value *Cond = SI.getCondition();
6508 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
6509 if (I->getOpcode() == Instruction::Add)
6510 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
6511 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
6512 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
Owen Andersond672ecb2009-07-03 00:17:18 +00006513 SI.setOperand(i,
Owen Andersonbaf3c402009-07-29 18:55:55 +00006514 ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
Chris Lattner46238a62004-07-03 00:26:11 +00006515 AddRHS));
6516 SI.setOperand(0, I->getOperand(0));
Chris Lattner7a1e9242009-08-30 06:13:40 +00006517 Worklist.Add(I);
Chris Lattner46238a62004-07-03 00:26:11 +00006518 return &SI;
6519 }
6520 }
6521 return 0;
6522}
6523
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +00006524Instruction *InstCombiner::visitExtractValueInst(ExtractValueInst &EV) {
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +00006525 Value *Agg = EV.getAggregateOperand();
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +00006526
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +00006527 if (!EV.hasIndices())
6528 return ReplaceInstUsesWith(EV, Agg);
6529
6530 if (Constant *C = dyn_cast<Constant>(Agg)) {
6531 if (isa<UndefValue>(C))
Owen Anderson9e9a0d52009-07-30 23:03:37 +00006532 return ReplaceInstUsesWith(EV, UndefValue::get(EV.getType()));
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +00006533
6534 if (isa<ConstantAggregateZero>(C))
Owen Andersona7235ea2009-07-31 20:28:14 +00006535 return ReplaceInstUsesWith(EV, Constant::getNullValue(EV.getType()));
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +00006536
6537 if (isa<ConstantArray>(C) || isa<ConstantStruct>(C)) {
6538 // Extract the element indexed by the first index out of the constant
6539 Value *V = C->getOperand(*EV.idx_begin());
6540 if (EV.getNumIndices() > 1)
6541 // Extract the remaining indices out of the constant indexed by the
6542 // first index
6543 return ExtractValueInst::Create(V, EV.idx_begin() + 1, EV.idx_end());
6544 else
6545 return ReplaceInstUsesWith(EV, V);
6546 }
6547 return 0; // Can't handle other constants
6548 }
6549 if (InsertValueInst *IV = dyn_cast<InsertValueInst>(Agg)) {
6550 // We're extracting from an insertvalue instruction, compare the indices
6551 const unsigned *exti, *exte, *insi, *inse;
6552 for (exti = EV.idx_begin(), insi = IV->idx_begin(),
6553 exte = EV.idx_end(), inse = IV->idx_end();
6554 exti != exte && insi != inse;
6555 ++exti, ++insi) {
6556 if (*insi != *exti)
6557 // The insert and extract both reference distinctly different elements.
6558 // This means the extract is not influenced by the insert, and we can
6559 // replace the aggregate operand of the extract with the aggregate
6560 // operand of the insert. i.e., replace
6561 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
6562 // %E = extractvalue { i32, { i32 } } %I, 0
6563 // with
6564 // %E = extractvalue { i32, { i32 } } %A, 0
6565 return ExtractValueInst::Create(IV->getAggregateOperand(),
6566 EV.idx_begin(), EV.idx_end());
6567 }
6568 if (exti == exte && insi == inse)
6569 // Both iterators are at the end: Index lists are identical. Replace
6570 // %B = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
6571 // %C = extractvalue { i32, { i32 } } %B, 1, 0
6572 // with "i32 42"
6573 return ReplaceInstUsesWith(EV, IV->getInsertedValueOperand());
6574 if (exti == exte) {
6575 // The extract list is a prefix of the insert list. i.e. replace
6576 // %I = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
6577 // %E = extractvalue { i32, { i32 } } %I, 1
6578 // with
6579 // %X = extractvalue { i32, { i32 } } %A, 1
6580 // %E = insertvalue { i32 } %X, i32 42, 0
6581 // by switching the order of the insert and extract (though the
6582 // insertvalue should be left in, since it may have other uses).
Chris Lattnerf925cbd2009-08-30 18:50:58 +00006583 Value *NewEV = Builder->CreateExtractValue(IV->getAggregateOperand(),
6584 EV.idx_begin(), EV.idx_end());
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +00006585 return InsertValueInst::Create(NewEV, IV->getInsertedValueOperand(),
6586 insi, inse);
6587 }
6588 if (insi == inse)
6589 // The insert list is a prefix of the extract list
6590 // We can simply remove the common indices from the extract and make it
6591 // operate on the inserted value instead of the insertvalue result.
6592 // i.e., replace
6593 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
6594 // %E = extractvalue { i32, { i32 } } %I, 1, 0
6595 // with
6596 // %E extractvalue { i32 } { i32 42 }, 0
6597 return ExtractValueInst::Create(IV->getInsertedValueOperand(),
6598 exti, exte);
6599 }
Chris Lattner7e606e22009-11-09 07:07:56 +00006600 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Agg)) {
6601 // We're extracting from an intrinsic, see if we're the only user, which
6602 // allows us to simplify multiple result intrinsics to simpler things that
6603 // just get one value..
6604 if (II->hasOneUse()) {
6605 // Check if we're grabbing the overflow bit or the result of a 'with
6606 // overflow' intrinsic. If it's the latter we can remove the intrinsic
6607 // and replace it with a traditional binary instruction.
6608 switch (II->getIntrinsicID()) {
6609 case Intrinsic::uadd_with_overflow:
6610 case Intrinsic::sadd_with_overflow:
6611 if (*EV.idx_begin() == 0) { // Normal result.
6612 Value *LHS = II->getOperand(1), *RHS = II->getOperand(2);
6613 II->replaceAllUsesWith(UndefValue::get(II->getType()));
6614 EraseInstFromFunction(*II);
6615 return BinaryOperator::CreateAdd(LHS, RHS);
6616 }
6617 break;
6618 case Intrinsic::usub_with_overflow:
6619 case Intrinsic::ssub_with_overflow:
6620 if (*EV.idx_begin() == 0) { // Normal result.
6621 Value *LHS = II->getOperand(1), *RHS = II->getOperand(2);
6622 II->replaceAllUsesWith(UndefValue::get(II->getType()));
6623 EraseInstFromFunction(*II);
6624 return BinaryOperator::CreateSub(LHS, RHS);
6625 }
6626 break;
6627 case Intrinsic::umul_with_overflow:
6628 case Intrinsic::smul_with_overflow:
6629 if (*EV.idx_begin() == 0) { // Normal result.
6630 Value *LHS = II->getOperand(1), *RHS = II->getOperand(2);
6631 II->replaceAllUsesWith(UndefValue::get(II->getType()));
6632 EraseInstFromFunction(*II);
6633 return BinaryOperator::CreateMul(LHS, RHS);
6634 }
6635 break;
6636 default:
6637 break;
6638 }
6639 }
6640 }
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +00006641 // Can't simplify extracts from other values. Note that nested extracts are
6642 // already simplified implicitely by the above (extract ( extract (insert) )
6643 // will be translated into extract ( insert ( extract ) ) first and then just
6644 // the value inserted, if appropriate).
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +00006645 return 0;
6646}
6647
Chris Lattnera844fc4c2006-04-10 22:45:52 +00006648
Robert Bocchino1d7456d2006-01-13 22:48:06 +00006649
Chris Lattnerea1c4542004-12-08 23:43:58 +00006650
6651/// TryToSinkInstruction - Try to move the specified instruction from its
6652/// current block into the beginning of DestBlock, which can only happen if it's
6653/// safe to move the instruction past all of the instructions between it and the
6654/// end of its block.
6655static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
6656 assert(I->hasOneUse() && "Invariants didn't hold!");
6657
Chris Lattner108e9022005-10-27 17:13:11 +00006658 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
Duncan Sands7af1c782009-05-06 06:49:50 +00006659 if (isa<PHINode>(I) || I->mayHaveSideEffects() || isa<TerminatorInst>(I))
Chris Lattnerbfc538c2008-05-09 15:07:33 +00006660 return false;
Misha Brukmanfd939082005-04-21 23:48:37 +00006661
Chris Lattnerea1c4542004-12-08 23:43:58 +00006662 // Do not sink alloca instructions out of the entry block.
Dan Gohmanecb7a772007-03-22 16:38:57 +00006663 if (isa<AllocaInst>(I) && I->getParent() ==
6664 &DestBlock->getParent()->getEntryBlock())
Chris Lattnerea1c4542004-12-08 23:43:58 +00006665 return false;
6666
Chris Lattner96a52a62004-12-09 07:14:34 +00006667 // We can only sink load instructions if there is nothing between the load and
6668 // the end of block that could change the value.
Chris Lattner2539e332008-05-08 17:37:37 +00006669 if (I->mayReadFromMemory()) {
6670 for (BasicBlock::iterator Scan = I, E = I->getParent()->end();
Chris Lattner96a52a62004-12-09 07:14:34 +00006671 Scan != E; ++Scan)
6672 if (Scan->mayWriteToMemory())
6673 return false;
Chris Lattner96a52a62004-12-09 07:14:34 +00006674 }
Chris Lattnerea1c4542004-12-08 23:43:58 +00006675
Dan Gohman02dea8b2008-05-23 21:05:58 +00006676 BasicBlock::iterator InsertPos = DestBlock->getFirstNonPHI();
Chris Lattnerea1c4542004-12-08 23:43:58 +00006677
Chris Lattner4bc5f802005-08-08 19:11:57 +00006678 I->moveBefore(InsertPos);
Chris Lattnerea1c4542004-12-08 23:43:58 +00006679 ++NumSunkInst;
6680 return true;
6681}
6682
Chris Lattnerf4f5a772006-05-10 19:00:36 +00006683
6684/// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
6685/// all reachable code to the worklist.
6686///
6687/// This has a couple of tricks to make the code faster and more powerful. In
6688/// particular, we constant fold and DCE instructions as we go, to avoid adding
6689/// them to the worklist (this significantly speeds up instcombine on code where
6690/// many instructions are dead or constant). Additionally, if we find a branch
6691/// whose condition is a known constant, we only visit the reachable successors.
6692///
Chris Lattner2ee743b2009-10-15 04:59:28 +00006693static bool AddReachableCodeToWorklist(BasicBlock *BB,
Chris Lattner1f87a582007-02-15 19:41:52 +00006694 SmallPtrSet<BasicBlock*, 64> &Visited,
Chris Lattnerdbab3862007-03-02 21:28:56 +00006695 InstCombiner &IC,
Chris Lattner8c8c66a2006-05-11 17:11:52 +00006696 const TargetData *TD) {
Chris Lattner2ee743b2009-10-15 04:59:28 +00006697 bool MadeIRChange = false;
Chris Lattner2806dff2008-08-15 04:03:01 +00006698 SmallVector<BasicBlock*, 256> Worklist;
Chris Lattner2c7718a2007-03-23 19:17:18 +00006699 Worklist.push_back(BB);
Chris Lattner67f7d542009-10-12 03:58:40 +00006700
6701 std::vector<Instruction*> InstrsForInstCombineWorklist;
6702 InstrsForInstCombineWorklist.reserve(128);
Chris Lattnerf4f5a772006-05-10 19:00:36 +00006703
Chris Lattner2ee743b2009-10-15 04:59:28 +00006704 SmallPtrSet<ConstantExpr*, 64> FoldedConstants;
6705
Chris Lattner2c7718a2007-03-23 19:17:18 +00006706 while (!Worklist.empty()) {
6707 BB = Worklist.back();
6708 Worklist.pop_back();
6709
6710 // We have now visited this block! If we've already been here, ignore it.
6711 if (!Visited.insert(BB)) continue;
Devang Patel7fe1dec2008-11-19 18:56:50 +00006712
Chris Lattner2c7718a2007-03-23 19:17:18 +00006713 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
6714 Instruction *Inst = BBI++;
Chris Lattnerf4f5a772006-05-10 19:00:36 +00006715
Chris Lattner2c7718a2007-03-23 19:17:18 +00006716 // DCE instruction if trivially dead.
6717 if (isInstructionTriviallyDead(Inst)) {
6718 ++NumDeadInst;
Chris Lattnerbdff5482009-08-23 04:37:46 +00006719 DEBUG(errs() << "IC: DCE: " << *Inst << '\n');
Chris Lattner2c7718a2007-03-23 19:17:18 +00006720 Inst->eraseFromParent();
6721 continue;
6722 }
6723
6724 // ConstantProp instruction if trivially constant.
Chris Lattnere2cc1ad2009-10-15 04:13:44 +00006725 if (!Inst->use_empty() && isa<Constant>(Inst->getOperand(0)))
Chris Lattner7b550cc2009-11-06 04:27:31 +00006726 if (Constant *C = ConstantFoldInstruction(Inst, TD)) {
Chris Lattnere2cc1ad2009-10-15 04:13:44 +00006727 DEBUG(errs() << "IC: ConstFold to: " << *C << " from: "
6728 << *Inst << '\n');
6729 Inst->replaceAllUsesWith(C);
6730 ++NumConstProp;
6731 Inst->eraseFromParent();
6732 continue;
6733 }
Chris Lattner2ee743b2009-10-15 04:59:28 +00006734
6735
6736
6737 if (TD) {
6738 // See if we can constant fold its operands.
6739 for (User::op_iterator i = Inst->op_begin(), e = Inst->op_end();
6740 i != e; ++i) {
6741 ConstantExpr *CE = dyn_cast<ConstantExpr>(i);
6742 if (CE == 0) continue;
6743
6744 // If we already folded this constant, don't try again.
6745 if (!FoldedConstants.insert(CE))
6746 continue;
6747
Chris Lattner7b550cc2009-11-06 04:27:31 +00006748 Constant *NewC = ConstantFoldConstantExpression(CE, TD);
Chris Lattner2ee743b2009-10-15 04:59:28 +00006749 if (NewC && NewC != CE) {
6750 *i = NewC;
6751 MadeIRChange = true;
6752 }
6753 }
6754 }
6755
Devang Patel7fe1dec2008-11-19 18:56:50 +00006756
Chris Lattner67f7d542009-10-12 03:58:40 +00006757 InstrsForInstCombineWorklist.push_back(Inst);
Chris Lattnerf4f5a772006-05-10 19:00:36 +00006758 }
Chris Lattner2c7718a2007-03-23 19:17:18 +00006759
6760 // Recursively visit successors. If this is a branch or switch on a
6761 // constant, only visit the reachable successor.
6762 TerminatorInst *TI = BB->getTerminator();
6763 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
6764 if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
6765 bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
Nick Lewycky91436992008-03-09 08:50:23 +00006766 BasicBlock *ReachableBB = BI->getSuccessor(!CondVal);
Nick Lewycky280a6e62008-04-25 16:53:59 +00006767 Worklist.push_back(ReachableBB);
Chris Lattner2c7718a2007-03-23 19:17:18 +00006768 continue;
6769 }
6770 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
6771 if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
6772 // See if this is an explicit destination.
6773 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
6774 if (SI->getCaseValue(i) == Cond) {
Nick Lewycky91436992008-03-09 08:50:23 +00006775 BasicBlock *ReachableBB = SI->getSuccessor(i);
Nick Lewycky280a6e62008-04-25 16:53:59 +00006776 Worklist.push_back(ReachableBB);
Chris Lattner2c7718a2007-03-23 19:17:18 +00006777 continue;
6778 }
6779
6780 // Otherwise it is the default destination.
6781 Worklist.push_back(SI->getSuccessor(0));
6782 continue;
6783 }
6784 }
6785
6786 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
6787 Worklist.push_back(TI->getSuccessor(i));
Chris Lattnerf4f5a772006-05-10 19:00:36 +00006788 }
Chris Lattner67f7d542009-10-12 03:58:40 +00006789
6790 // Once we've found all of the instructions to add to instcombine's worklist,
6791 // add them in reverse order. This way instcombine will visit from the top
6792 // of the function down. This jives well with the way that it adds all uses
6793 // of instructions to the worklist after doing a transformation, thus avoiding
6794 // some N^2 behavior in pathological cases.
6795 IC.Worklist.AddInitialGroup(&InstrsForInstCombineWorklist[0],
6796 InstrsForInstCombineWorklist.size());
Chris Lattner2ee743b2009-10-15 04:59:28 +00006797
6798 return MadeIRChange;
Chris Lattnerf4f5a772006-05-10 19:00:36 +00006799}
6800
Chris Lattnerec9c3582007-03-03 02:04:50 +00006801bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) {
Chris Lattnerb0b822c2009-08-31 06:57:37 +00006802 MadeIRChange = false;
Chris Lattnerec9c3582007-03-03 02:04:50 +00006803
Daniel Dunbarce63ffb2009-07-25 00:23:56 +00006804 DEBUG(errs() << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
6805 << F.getNameStr() << "\n");
Chris Lattner8a2a3112001-12-14 16:52:21 +00006806
Chris Lattnerb3d59702005-07-07 20:40:38 +00006807 {
Chris Lattnerf4f5a772006-05-10 19:00:36 +00006808 // Do a depth-first traversal of the function, populate the worklist with
6809 // the reachable instructions. Ignore blocks that are not reachable. Keep
6810 // track of which blocks we visit.
Chris Lattner1f87a582007-02-15 19:41:52 +00006811 SmallPtrSet<BasicBlock*, 64> Visited;
Chris Lattner2ee743b2009-10-15 04:59:28 +00006812 MadeIRChange |= AddReachableCodeToWorklist(F.begin(), Visited, *this, TD);
Jeff Cohen00b168892005-07-27 06:12:32 +00006813
Chris Lattnerb3d59702005-07-07 20:40:38 +00006814 // Do a quick scan over the function. If we find any blocks that are
6815 // unreachable, remove any instructions inside of them. This prevents
6816 // the instcombine code from having to deal with some bad special cases.
6817 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
6818 if (!Visited.count(BB)) {
6819 Instruction *Term = BB->getTerminator();
6820 while (Term != BB->begin()) { // Remove instrs bottom-up
6821 BasicBlock::iterator I = Term; --I;
Chris Lattner6ffe5512004-04-27 15:13:33 +00006822
Chris Lattnerbdff5482009-08-23 04:37:46 +00006823 DEBUG(errs() << "IC: DCE: " << *I << '\n');
Dale Johannesenff278b12009-03-10 21:19:49 +00006824 // A debug intrinsic shouldn't force another iteration if we weren't
6825 // going to do one without it.
6826 if (!isa<DbgInfoIntrinsic>(I)) {
6827 ++NumDeadInst;
Chris Lattnerb0b822c2009-08-31 06:57:37 +00006828 MadeIRChange = true;
Dale Johannesenff278b12009-03-10 21:19:49 +00006829 }
Devang Patel228ebd02009-10-13 22:56:32 +00006830
Devang Patel228ebd02009-10-13 22:56:32 +00006831 // If I is not void type then replaceAllUsesWith undef.
6832 // This allows ValueHandlers and custom metadata to adjust itself.
Devang Patel9674d152009-10-14 17:29:00 +00006833 if (!I->getType()->isVoidTy())
Devang Patel228ebd02009-10-13 22:56:32 +00006834 I->replaceAllUsesWith(UndefValue::get(I->getType()));
Chris Lattnerb3d59702005-07-07 20:40:38 +00006835 I->eraseFromParent();
6836 }
6837 }
6838 }
Chris Lattner8a2a3112001-12-14 16:52:21 +00006839
Chris Lattner873ff012009-08-30 05:55:36 +00006840 while (!Worklist.isEmpty()) {
6841 Instruction *I = Worklist.RemoveOne();
Chris Lattnerdbab3862007-03-02 21:28:56 +00006842 if (I == 0) continue; // skip null values.
Chris Lattner8a2a3112001-12-14 16:52:21 +00006843
Chris Lattner8c8c66a2006-05-11 17:11:52 +00006844 // Check to see if we can DCE the instruction.
Chris Lattner62b14df2002-09-02 04:59:56 +00006845 if (isInstructionTriviallyDead(I)) {
Chris Lattnerbdff5482009-08-23 04:37:46 +00006846 DEBUG(errs() << "IC: DCE: " << *I << '\n');
Chris Lattner7a1e9242009-08-30 06:13:40 +00006847 EraseInstFromFunction(*I);
6848 ++NumDeadInst;
Chris Lattnerb0b822c2009-08-31 06:57:37 +00006849 MadeIRChange = true;
Chris Lattner4bb7c022003-10-06 17:11:01 +00006850 continue;
6851 }
Chris Lattner62b14df2002-09-02 04:59:56 +00006852
Chris Lattner8c8c66a2006-05-11 17:11:52 +00006853 // Instruction isn't dead, see if we can constant propagate it.
Chris Lattnere2cc1ad2009-10-15 04:13:44 +00006854 if (!I->use_empty() && isa<Constant>(I->getOperand(0)))
Chris Lattner7b550cc2009-11-06 04:27:31 +00006855 if (Constant *C = ConstantFoldInstruction(I, TD)) {
Chris Lattnere2cc1ad2009-10-15 04:13:44 +00006856 DEBUG(errs() << "IC: ConstFold to: " << *C << " from: " << *I << '\n');
Chris Lattnerad5fec12005-01-28 19:32:01 +00006857
Chris Lattnere2cc1ad2009-10-15 04:13:44 +00006858 // Add operands to the worklist.
6859 ReplaceInstUsesWith(*I, C);
6860 ++NumConstProp;
6861 EraseInstFromFunction(*I);
6862 MadeIRChange = true;
6863 continue;
6864 }
Chris Lattner4bb7c022003-10-06 17:11:01 +00006865
Chris Lattnerea1c4542004-12-08 23:43:58 +00006866 // See if we can trivially sink this instruction to a successor basic block.
Dan Gohmanfc74abf2008-07-23 00:34:11 +00006867 if (I->hasOneUse()) {
Chris Lattnerea1c4542004-12-08 23:43:58 +00006868 BasicBlock *BB = I->getParent();
Chris Lattner8db2cd12009-10-14 15:21:58 +00006869 Instruction *UserInst = cast<Instruction>(I->use_back());
6870 BasicBlock *UserParent;
6871
6872 // Get the block the use occurs in.
6873 if (PHINode *PN = dyn_cast<PHINode>(UserInst))
6874 UserParent = PN->getIncomingBlock(I->use_begin().getUse());
6875 else
6876 UserParent = UserInst->getParent();
6877
Chris Lattnerea1c4542004-12-08 23:43:58 +00006878 if (UserParent != BB) {
6879 bool UserIsSuccessor = false;
6880 // See if the user is one of our successors.
6881 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
6882 if (*SI == UserParent) {
6883 UserIsSuccessor = true;
6884 break;
6885 }
6886
6887 // If the user is one of our immediate successors, and if that successor
6888 // only has us as a predecessors (we'd have to split the critical edge
6889 // otherwise), we can keep going.
Chris Lattner8db2cd12009-10-14 15:21:58 +00006890 if (UserIsSuccessor && UserParent->getSinglePredecessor())
Chris Lattnerea1c4542004-12-08 23:43:58 +00006891 // Okay, the CFG is simple enough, try to sink this instruction.
Chris Lattnerb0b822c2009-08-31 06:57:37 +00006892 MadeIRChange |= TryToSinkInstruction(I, UserParent);
Chris Lattnerea1c4542004-12-08 23:43:58 +00006893 }
6894 }
6895
Chris Lattner74381062009-08-30 07:44:24 +00006896 // Now that we have an instruction, try combining it to simplify it.
6897 Builder->SetInsertPoint(I->getParent(), I);
6898
Reid Spencera9b81012007-03-26 17:44:01 +00006899#ifndef NDEBUG
6900 std::string OrigI;
6901#endif
Chris Lattnerbdff5482009-08-23 04:37:46 +00006902 DEBUG(raw_string_ostream SS(OrigI); I->print(SS); OrigI = SS.str(););
Jeffrey Yasskin43069632009-10-08 00:12:24 +00006903 DEBUG(errs() << "IC: Visiting: " << OrigI << '\n');
6904
Chris Lattner90ac28c2002-08-02 19:29:35 +00006905 if (Instruction *Result = visit(*I)) {
Chris Lattner3dec1f22002-05-10 15:38:35 +00006906 ++NumCombined;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00006907 // Should we replace the old instruction with a new one?
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +00006908 if (Result != I) {
Chris Lattnerbdff5482009-08-23 04:37:46 +00006909 DEBUG(errs() << "IC: Old = " << *I << '\n'
6910 << " New = " << *Result << '\n');
Chris Lattner0cea42a2004-03-13 23:54:27 +00006911
Chris Lattnerf523d062004-06-09 05:08:07 +00006912 // Everything uses the new instruction now.
6913 I->replaceAllUsesWith(Result);
6914
6915 // Push the new instruction and any users onto the worklist.
Chris Lattner7a1e9242009-08-30 06:13:40 +00006916 Worklist.Add(Result);
Chris Lattnere5ecdb52009-08-30 06:22:51 +00006917 Worklist.AddUsersToWorkList(*Result);
Chris Lattner4bb7c022003-10-06 17:11:01 +00006918
Chris Lattner6934a042007-02-11 01:23:03 +00006919 // Move the name to the new instruction first.
6920 Result->takeName(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +00006921
6922 // Insert the new instruction into the basic block...
6923 BasicBlock *InstParent = I->getParent();
Chris Lattnerbac32862004-11-14 19:13:23 +00006924 BasicBlock::iterator InsertPos = I;
6925
6926 if (!isa<PHINode>(Result)) // If combining a PHI, don't insert
6927 while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
6928 ++InsertPos;
6929
6930 InstParent->getInstList().insert(InsertPos, Result);
Chris Lattner4bb7c022003-10-06 17:11:01 +00006931
Chris Lattner7a1e9242009-08-30 06:13:40 +00006932 EraseInstFromFunction(*I);
Chris Lattner7e708292002-06-25 16:13:24 +00006933 } else {
Evan Chengc7baf682007-03-27 16:44:48 +00006934#ifndef NDEBUG
Chris Lattnerbdff5482009-08-23 04:37:46 +00006935 DEBUG(errs() << "IC: Mod = " << OrigI << '\n'
6936 << " New = " << *I << '\n');
Evan Chengc7baf682007-03-27 16:44:48 +00006937#endif
Chris Lattner0cea42a2004-03-13 23:54:27 +00006938
Chris Lattner90ac28c2002-08-02 19:29:35 +00006939 // If the instruction was modified, it's possible that it is now dead.
6940 // if so, remove it.
Chris Lattner00d51312004-05-01 23:27:23 +00006941 if (isInstructionTriviallyDead(I)) {
Chris Lattner7a1e9242009-08-30 06:13:40 +00006942 EraseInstFromFunction(*I);
Chris Lattnerf523d062004-06-09 05:08:07 +00006943 } else {
Chris Lattner7a1e9242009-08-30 06:13:40 +00006944 Worklist.Add(I);
Chris Lattnere5ecdb52009-08-30 06:22:51 +00006945 Worklist.AddUsersToWorkList(*I);
Chris Lattner90ac28c2002-08-02 19:29:35 +00006946 }
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +00006947 }
Chris Lattnerb0b822c2009-08-31 06:57:37 +00006948 MadeIRChange = true;
Chris Lattner8a2a3112001-12-14 16:52:21 +00006949 }
6950 }
6951
Chris Lattner873ff012009-08-30 05:55:36 +00006952 Worklist.Zap();
Chris Lattnerb0b822c2009-08-31 06:57:37 +00006953 return MadeIRChange;
Chris Lattnerbd0ef772002-02-26 21:46:54 +00006954}
6955
Chris Lattnerec9c3582007-03-03 02:04:50 +00006956
6957bool InstCombiner::runOnFunction(Function &F) {
Chris Lattnerf964f322007-03-04 04:27:24 +00006958 MustPreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
Chris Lattnere2cc1ad2009-10-15 04:13:44 +00006959 TD = getAnalysisIfAvailable<TargetData>();
6960
Chris Lattner74381062009-08-30 07:44:24 +00006961
6962 /// Builder - This is an IRBuilder that automatically inserts new
6963 /// instructions into the worklist when they are created.
Chris Lattnere2cc1ad2009-10-15 04:13:44 +00006964 IRBuilder<true, TargetFolder, InstCombineIRInserter>
Chris Lattnerf55eeb92009-11-06 05:59:53 +00006965 TheBuilder(F.getContext(), TargetFolder(TD),
Chris Lattner74381062009-08-30 07:44:24 +00006966 InstCombineIRInserter(Worklist));
6967 Builder = &TheBuilder;
6968
Chris Lattnerec9c3582007-03-03 02:04:50 +00006969 bool EverMadeChange = false;
6970
6971 // Iterate while there is work to do.
6972 unsigned Iteration = 0;
Bill Wendlinga6c31122008-05-14 22:45:20 +00006973 while (DoOneIteration(F, Iteration++))
Chris Lattnerec9c3582007-03-03 02:04:50 +00006974 EverMadeChange = true;
Chris Lattner74381062009-08-30 07:44:24 +00006975
6976 Builder = 0;
Chris Lattnerec9c3582007-03-03 02:04:50 +00006977 return EverMadeChange;
6978}
6979
Brian Gaeke96d4bf72004-07-27 17:43:21 +00006980FunctionPass *llvm::createInstructionCombiningPass() {
Chris Lattnerdd841ae2002-04-18 17:39:14 +00006981 return new InstCombiner();
Chris Lattnerbd0ef772002-02-26 21:46:54 +00006982}