blob: a0bd43ab701e01376588ef0f104be276f8d03a08 [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");
67STATISTIC(NumDeadStore, "Number of dead stores eliminated");
68STATISTIC(NumSunkInst , "Number of instructions sunk");
Chris Lattnera92f6962002-10-01 22:38:41 +000069
Chris Lattnerdd841ae2002-04-18 17:39:14 +000070
Dan Gohman844731a2008-05-13 00:00:25 +000071char InstCombiner::ID = 0;
72static RegisterPass<InstCombiner>
73X("instcombine", "Combine redundant instructions");
74
Chris Lattnere0b4b722010-01-04 07:17:19 +000075void InstCombiner::getAnalysisUsage(AnalysisUsage &AU) const {
76 AU.addPreservedID(LCSSAID);
77 AU.setPreservesCFG();
78}
79
80
Chris Lattnerc8802d22003-03-11 00:12:48 +000081// isOnlyUse - Return true if this instruction will be deleted if we stop using
82// it.
83static bool isOnlyUse(Value *V) {
Chris Lattnerfd059242003-10-15 16:48:29 +000084 return V->hasOneUse() || isa<Constant>(V);
Chris Lattnerc8802d22003-03-11 00:12:48 +000085}
86
Chris Lattner4cb170c2004-02-23 06:38:22 +000087// getPromotedType - Return the specified type promoted as it would be to pass
88// though a va_arg area...
89static const Type *getPromotedType(const Type *Ty) {
Reid Spencera54b7cb2007-01-12 07:05:14 +000090 if (const IntegerType* ITy = dyn_cast<IntegerType>(Ty)) {
91 if (ITy->getBitWidth() < 32)
Owen Anderson1d0be152009-08-13 21:58:54 +000092 return Type::getInt32Ty(Ty->getContext());
Chris Lattner2b7e0ad2007-05-23 01:17:04 +000093 }
Reid Spencera54b7cb2007-01-12 07:05:14 +000094 return Ty;
Chris Lattner4cb170c2004-02-23 06:38:22 +000095}
96
Chris Lattnerc22d4d12009-11-10 07:23:37 +000097/// ShouldChangeType - Return true if it is desirable to convert a computation
98/// from 'From' to 'To'. We don't want to convert from a legal to an illegal
99/// type for example, or from a smaller to a larger illegal type.
100static bool ShouldChangeType(const Type *From, const Type *To,
101 const TargetData *TD) {
102 assert(isa<IntegerType>(From) && isa<IntegerType>(To));
103
104 // If we don't have TD, we don't know if the source/dest are legal.
105 if (!TD) return false;
106
107 unsigned FromWidth = From->getPrimitiveSizeInBits();
108 unsigned ToWidth = To->getPrimitiveSizeInBits();
109 bool FromLegal = TD->isLegalInteger(FromWidth);
110 bool ToLegal = TD->isLegalInteger(ToWidth);
111
112 // If this is a legal integer from type, and the result would be an illegal
113 // type, don't do the transformation.
114 if (FromLegal && !ToLegal)
115 return false;
116
117 // Otherwise, if both are illegal, do not increase the size of the result. We
118 // do allow things like i160 -> i64, but not i64 -> i160.
119 if (!FromLegal && !ToLegal && ToWidth > FromWidth)
120 return false;
121
122 return true;
123}
124
Matthijs Kooijman7e6d9b92008-10-13 15:17:01 +0000125/// getBitCastOperand - If the specified operand is a CastInst, a constant
126/// expression bitcast, or a GetElementPtrInst with all zero indices, return the
127/// operand value, otherwise return null.
Reid Spencer3da59db2006-11-27 01:05:10 +0000128static Value *getBitCastOperand(Value *V) {
Dan Gohman016de812009-07-17 23:55:56 +0000129 if (Operator *O = dyn_cast<Operator>(V)) {
130 if (O->getOpcode() == Instruction::BitCast)
131 return O->getOperand(0);
132 if (GEPOperator *GEP = dyn_cast<GEPOperator>(V))
133 if (GEP->hasAllZeroIndices())
134 return GEP->getPointerOperand();
Matthijs Kooijman7e6d9b92008-10-13 15:17:01 +0000135 }
Chris Lattnereed48272005-09-13 00:40:14 +0000136 return 0;
137}
138
Reid Spencer3da59db2006-11-27 01:05:10 +0000139/// This function is a wrapper around CastInst::isEliminableCastPair. It
140/// simply extracts arguments and returns what that function returns.
Reid Spencer3da59db2006-11-27 01:05:10 +0000141static Instruction::CastOps
142isEliminableCastPair(
143 const CastInst *CI, ///< The first cast instruction
144 unsigned opcode, ///< The opcode of the second cast instruction
145 const Type *DstTy, ///< The target type for the second cast instruction
146 TargetData *TD ///< The target data for pointer size
147) {
Dan Gohmance9fe9f2009-07-21 23:21:54 +0000148
Reid Spencer3da59db2006-11-27 01:05:10 +0000149 const Type *SrcTy = CI->getOperand(0)->getType(); // A from above
150 const Type *MidTy = CI->getType(); // B from above
Chris Lattner33a61132006-05-06 09:00:16 +0000151
Reid Spencer3da59db2006-11-27 01:05:10 +0000152 // Get the opcodes of the two Cast instructions
153 Instruction::CastOps firstOp = Instruction::CastOps(CI->getOpcode());
154 Instruction::CastOps secondOp = Instruction::CastOps(opcode);
Chris Lattner33a61132006-05-06 09:00:16 +0000155
Chris Lattnera0e69692009-03-24 18:35:40 +0000156 unsigned Res = CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy,
Dan Gohmance9fe9f2009-07-21 23:21:54 +0000157 DstTy,
Owen Anderson1d0be152009-08-13 21:58:54 +0000158 TD ? TD->getIntPtrType(CI->getContext()) : 0);
Chris Lattnera0e69692009-03-24 18:35:40 +0000159
160 // We don't want to form an inttoptr or ptrtoint that converts to an integer
161 // type that differs from the pointer size.
Owen Anderson1d0be152009-08-13 21:58:54 +0000162 if ((Res == Instruction::IntToPtr &&
Dan Gohman5e9bb732009-08-19 23:38:22 +0000163 (!TD || SrcTy != TD->getIntPtrType(CI->getContext()))) ||
Owen Anderson1d0be152009-08-13 21:58:54 +0000164 (Res == Instruction::PtrToInt &&
Dan Gohman5e9bb732009-08-19 23:38:22 +0000165 (!TD || DstTy != TD->getIntPtrType(CI->getContext()))))
Chris Lattnera0e69692009-03-24 18:35:40 +0000166 Res = 0;
167
168 return Instruction::CastOps(Res);
Chris Lattner33a61132006-05-06 09:00:16 +0000169}
170
171/// ValueRequiresCast - Return true if the cast from "V to Ty" actually results
172/// in any code being generated. It does not require codegen if V is simple
173/// enough or if the cast can be folded into other casts.
Reid Spencere4d87aa2006-12-23 06:05:41 +0000174static bool ValueRequiresCast(Instruction::CastOps opcode, const Value *V,
175 const Type *Ty, TargetData *TD) {
Chris Lattner33a61132006-05-06 09:00:16 +0000176 if (V->getType() == Ty || isa<Constant>(V)) return false;
177
Chris Lattner01575b72006-05-25 23:24:33 +0000178 // If this is another cast that can be eliminated, it isn't codegen either.
Chris Lattner33a61132006-05-06 09:00:16 +0000179 if (const CastInst *CI = dyn_cast<CastInst>(V))
Dan Gohmance9fe9f2009-07-21 23:21:54 +0000180 if (isEliminableCastPair(CI, opcode, Ty, TD))
Chris Lattner33a61132006-05-06 09:00:16 +0000181 return false;
182 return true;
183}
184
Chris Lattner4f98c562003-03-10 21:43:22 +0000185// SimplifyCommutative - This performs a few simplifications for commutative
186// operators:
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000187//
Chris Lattner4f98c562003-03-10 21:43:22 +0000188// 1. Order operands such that they are listed from right (least complex) to
189// left (most complex). This puts constants before unary operators before
190// binary operators.
191//
Chris Lattnerc8802d22003-03-11 00:12:48 +0000192// 2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
193// 3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattner4f98c562003-03-10 21:43:22 +0000194//
Chris Lattnerc8802d22003-03-11 00:12:48 +0000195bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +0000196 bool Changed = false;
Dan Gohman14ef4f02009-08-29 23:39:38 +0000197 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
Chris Lattner4f98c562003-03-10 21:43:22 +0000198 Changed = !I.swapOperands();
Misha Brukmanfd939082005-04-21 23:48:37 +0000199
Chris Lattner4f98c562003-03-10 21:43:22 +0000200 if (!I.isAssociative()) return Changed;
201 Instruction::BinaryOps Opcode = I.getOpcode();
Chris Lattnerc8802d22003-03-11 00:12:48 +0000202 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
203 if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
204 if (isa<Constant>(I.getOperand(1))) {
Owen Andersonbaf3c402009-07-29 18:55:55 +0000205 Constant *Folded = ConstantExpr::get(I.getOpcode(),
Chris Lattner2a9c8472003-05-27 16:40:51 +0000206 cast<Constant>(I.getOperand(1)),
207 cast<Constant>(Op->getOperand(1)));
Chris Lattnerc8802d22003-03-11 00:12:48 +0000208 I.setOperand(0, Op->getOperand(0));
209 I.setOperand(1, Folded);
210 return true;
211 } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
212 if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
213 isOnlyUse(Op) && isOnlyUse(Op1)) {
214 Constant *C1 = cast<Constant>(Op->getOperand(1));
215 Constant *C2 = cast<Constant>(Op1->getOperand(1));
216
217 // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Owen Andersonbaf3c402009-07-29 18:55:55 +0000218 Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000219 Instruction *New = BinaryOperator::Create(Opcode, Op->getOperand(0),
Chris Lattnerc8802d22003-03-11 00:12:48 +0000220 Op1->getOperand(0),
221 Op1->getName(), &I);
Chris Lattner7a1e9242009-08-30 06:13:40 +0000222 Worklist.Add(New);
Chris Lattnerc8802d22003-03-11 00:12:48 +0000223 I.setOperand(0, New);
224 I.setOperand(1, Folded);
225 return true;
Misha Brukmanfd939082005-04-21 23:48:37 +0000226 }
Chris Lattner4f98c562003-03-10 21:43:22 +0000227 }
Chris Lattner4f98c562003-03-10 21:43:22 +0000228 return Changed;
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000229}
Chris Lattner8a2a3112001-12-14 16:52:21 +0000230
Chris Lattner8d969642003-03-10 23:06:50 +0000231// dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
232// if the LHS is a constant zero (which is the 'negate' form).
Chris Lattnerb35dde12002-05-06 16:49:18 +0000233//
Chris Lattner02446fc2010-01-04 07:37:31 +0000234Value *InstCombiner::dyn_castNegVal(Value *V) const {
Owen Andersonfa82b6e2009-07-13 22:18:28 +0000235 if (BinaryOperator::isNeg(V))
Chris Lattnera1df33c2005-04-24 07:30:14 +0000236 return BinaryOperator::getNegArgument(V);
Chris Lattner8d969642003-03-10 23:06:50 +0000237
Chris Lattner0ce85802004-12-14 20:08:06 +0000238 // Constants can be considered to be negated values if they can be folded.
239 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
Owen Andersonbaf3c402009-07-29 18:55:55 +0000240 return ConstantExpr::getNeg(C);
Nick Lewycky18b3da62008-05-23 04:54:45 +0000241
242 if (ConstantVector *C = dyn_cast<ConstantVector>(V))
243 if (C->getType()->getElementType()->isInteger())
Owen Andersonbaf3c402009-07-29 18:55:55 +0000244 return ConstantExpr::getNeg(C);
Nick Lewycky18b3da62008-05-23 04:54:45 +0000245
Chris Lattner8d969642003-03-10 23:06:50 +0000246 return 0;
Chris Lattnerb35dde12002-05-06 16:49:18 +0000247}
248
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000249// dyn_castFNegVal - Given a 'fsub' instruction, return the RHS of the
250// instruction if the LHS is a constant negative zero (which is the 'negate'
251// form).
252//
Dan Gohman186a6362009-08-12 16:04:34 +0000253static inline Value *dyn_castFNegVal(Value *V) {
Owen Andersonfa82b6e2009-07-13 22:18:28 +0000254 if (BinaryOperator::isFNeg(V))
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000255 return BinaryOperator::getFNegArgument(V);
256
257 // Constants can be considered to be negated values if they can be folded.
258 if (ConstantFP *C = dyn_cast<ConstantFP>(V))
Owen Andersonbaf3c402009-07-29 18:55:55 +0000259 return ConstantExpr::getFNeg(C);
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000260
261 if (ConstantVector *C = dyn_cast<ConstantVector>(V))
262 if (C->getType()->getElementType()->isFloatingPoint())
Owen Andersonbaf3c402009-07-29 18:55:55 +0000263 return ConstantExpr::getFNeg(C);
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000264
265 return 0;
266}
267
Chris Lattnerb109b5c2009-12-21 06:03:05 +0000268/// MatchSelectPattern - Pattern match integer [SU]MIN, [SU]MAX, and ABS idioms,
269/// returning the kind and providing the out parameter results if we
270/// successfully match.
271static SelectPatternFlavor
272MatchSelectPattern(Value *V, Value *&LHS, Value *&RHS) {
273 SelectInst *SI = dyn_cast<SelectInst>(V);
274 if (SI == 0) return SPF_UNKNOWN;
275
276 ICmpInst *ICI = dyn_cast<ICmpInst>(SI->getCondition());
277 if (ICI == 0) return SPF_UNKNOWN;
278
279 LHS = ICI->getOperand(0);
280 RHS = ICI->getOperand(1);
281
282 // (icmp X, Y) ? X : Y
283 if (SI->getTrueValue() == ICI->getOperand(0) &&
284 SI->getFalseValue() == ICI->getOperand(1)) {
285 switch (ICI->getPredicate()) {
286 default: return SPF_UNKNOWN; // Equality.
287 case ICmpInst::ICMP_UGT:
288 case ICmpInst::ICMP_UGE: return SPF_UMAX;
289 case ICmpInst::ICMP_SGT:
290 case ICmpInst::ICMP_SGE: return SPF_SMAX;
291 case ICmpInst::ICMP_ULT:
292 case ICmpInst::ICMP_ULE: return SPF_UMIN;
293 case ICmpInst::ICMP_SLT:
294 case ICmpInst::ICMP_SLE: return SPF_SMIN;
295 }
296 }
297
298 // (icmp X, Y) ? Y : X
299 if (SI->getTrueValue() == ICI->getOperand(1) &&
300 SI->getFalseValue() == ICI->getOperand(0)) {
301 switch (ICI->getPredicate()) {
302 default: return SPF_UNKNOWN; // Equality.
303 case ICmpInst::ICMP_UGT:
304 case ICmpInst::ICMP_UGE: return SPF_UMIN;
305 case ICmpInst::ICMP_SGT:
306 case ICmpInst::ICMP_SGE: return SPF_SMIN;
307 case ICmpInst::ICMP_ULT:
308 case ICmpInst::ICMP_ULE: return SPF_UMAX;
309 case ICmpInst::ICMP_SLT:
310 case ICmpInst::ICMP_SLE: return SPF_SMAX;
311 }
312 }
313
314 // TODO: (X > 4) ? X : 5 --> (X >= 5) ? X : 5 --> MAX(X, 5)
315
316 return SPF_UNKNOWN;
317}
318
Chris Lattner48b59ec2009-10-26 15:40:07 +0000319/// isFreeToInvert - Return true if the specified value is free to invert (apply
320/// ~ to). This happens in cases where the ~ can be eliminated.
321static inline bool isFreeToInvert(Value *V) {
322 // ~(~(X)) -> X.
Evan Cheng85def162009-10-26 03:51:32 +0000323 if (BinaryOperator::isNot(V))
Chris Lattner48b59ec2009-10-26 15:40:07 +0000324 return true;
325
326 // Constants can be considered to be not'ed values.
327 if (isa<ConstantInt>(V))
328 return true;
329
330 // Compares can be inverted if they have a single use.
331 if (CmpInst *CI = dyn_cast<CmpInst>(V))
332 return CI->hasOneUse();
333
334 return false;
335}
336
337static inline Value *dyn_castNotVal(Value *V) {
338 // If this is not(not(x)) don't return that this is a not: we want the two
339 // not's to be folded first.
340 if (BinaryOperator::isNot(V)) {
341 Value *Operand = BinaryOperator::getNotArgument(V);
342 if (!isFreeToInvert(Operand))
343 return Operand;
344 }
Chris Lattner8d969642003-03-10 23:06:50 +0000345
346 // Constants can be considered to be not'ed values...
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000347 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
Dan Gohman186a6362009-08-12 16:04:34 +0000348 return ConstantInt::get(C->getType(), ~C->getValue());
Chris Lattner8d969642003-03-10 23:06:50 +0000349 return 0;
350}
351
Chris Lattner48b59ec2009-10-26 15:40:07 +0000352
353
Chris Lattnerc8802d22003-03-11 00:12:48 +0000354// dyn_castFoldableMul - If this value is a multiply that can be folded into
355// other computations (because it has a constant operand), return the
Chris Lattner50af16a2004-11-13 19:50:12 +0000356// non-constant operand of the multiply, and set CST to point to the multiplier.
357// Otherwise, return null.
Chris Lattnerc8802d22003-03-11 00:12:48 +0000358//
Dan Gohman186a6362009-08-12 16:04:34 +0000359static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST) {
Chris Lattner42a75512007-01-15 02:27:26 +0000360 if (V->hasOneUse() && V->getType()->isInteger())
Chris Lattner50af16a2004-11-13 19:50:12 +0000361 if (Instruction *I = dyn_cast<Instruction>(V)) {
Chris Lattnerc8802d22003-03-11 00:12:48 +0000362 if (I->getOpcode() == Instruction::Mul)
Chris Lattner50e60c72004-11-15 05:54:07 +0000363 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
Chris Lattnerc8802d22003-03-11 00:12:48 +0000364 return I->getOperand(0);
Chris Lattner50af16a2004-11-13 19:50:12 +0000365 if (I->getOpcode() == Instruction::Shl)
Chris Lattner50e60c72004-11-15 05:54:07 +0000366 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
Chris Lattner50af16a2004-11-13 19:50:12 +0000367 // The multiplier is really 1 << CST.
Zhou Sheng97b52c22007-03-29 01:57:21 +0000368 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +0000369 uint32_t CSTVal = CST->getLimitedValue(BitWidth);
Dan Gohman186a6362009-08-12 16:04:34 +0000370 CST = ConstantInt::get(V->getType()->getContext(),
371 APInt(BitWidth, 1).shl(CSTVal));
Chris Lattner50af16a2004-11-13 19:50:12 +0000372 return I->getOperand(0);
373 }
374 }
Chris Lattnerc8802d22003-03-11 00:12:48 +0000375 return 0;
Chris Lattnera2881962003-02-18 19:28:33 +0000376}
Chris Lattneraf2930e2002-08-14 17:51:49 +0000377
Reid Spencer7177c3a2007-03-25 05:33:51 +0000378/// AddOne - Add one to a ConstantInt
Dan Gohman186a6362009-08-12 16:04:34 +0000379static Constant *AddOne(Constant *C) {
Chris Lattner02446fc2010-01-04 07:37:31 +0000380 return ConstantExpr::getAdd(C, ConstantInt::get(C->getType(), 1));
Chris Lattner955f3312004-09-28 21:48:02 +0000381}
Reid Spencer7177c3a2007-03-25 05:33:51 +0000382/// SubOne - Subtract one from a ConstantInt
Dan Gohman186a6362009-08-12 16:04:34 +0000383static Constant *SubOne(ConstantInt *C) {
Chris Lattner02446fc2010-01-04 07:37:31 +0000384 return ConstantExpr::getSub(C, ConstantInt::get(C->getType(), 1));
Chris Lattner955f3312004-09-28 21:48:02 +0000385}
Nick Lewyckye0cfecf2008-02-18 22:48:05 +0000386/// MultiplyOverflows - True if the multiply can not be expressed in an int
387/// this size.
Dan Gohman186a6362009-08-12 16:04:34 +0000388static bool MultiplyOverflows(ConstantInt *C1, ConstantInt *C2, bool sign) {
Nick Lewyckye0cfecf2008-02-18 22:48:05 +0000389 uint32_t W = C1->getBitWidth();
390 APInt LHSExt = C1->getValue(), RHSExt = C2->getValue();
391 if (sign) {
392 LHSExt.sext(W * 2);
393 RHSExt.sext(W * 2);
394 } else {
395 LHSExt.zext(W * 2);
396 RHSExt.zext(W * 2);
397 }
398
399 APInt MulExt = LHSExt * RHSExt;
400
Chris Lattnerb109b5c2009-12-21 06:03:05 +0000401 if (!sign)
Nick Lewyckye0cfecf2008-02-18 22:48:05 +0000402 return MulExt.ugt(APInt::getLowBitsSet(W * 2, W));
Chris Lattnerb109b5c2009-12-21 06:03:05 +0000403
404 APInt Min = APInt::getSignedMinValue(W).sext(W * 2);
405 APInt Max = APInt::getSignedMaxValue(W).sext(W * 2);
406 return MulExt.slt(Min) || MulExt.sgt(Max);
Nick Lewyckye0cfecf2008-02-18 22:48:05 +0000407}
Chris Lattner955f3312004-09-28 21:48:02 +0000408
Reid Spencere7816b52007-03-08 01:52:58 +0000409
Dan Gohman45b4e482008-05-19 22:14:15 +0000410
Chris Lattner564a7272003-08-13 19:01:45 +0000411/// AssociativeOpt - Perform an optimization on an associative operator. This
412/// function is designed to check a chain of associative operators for a
413/// potential to apply a certain optimization. Since the optimization may be
414/// applicable if the expression was reassociated, this checks the chain, then
415/// reassociates the expression as necessary to expose the optimization
416/// opportunity. This makes use of a special Functor, which must define
417/// 'shouldApply' and 'apply' methods.
418///
419template<typename Functor>
Dan Gohman186a6362009-08-12 16:04:34 +0000420static Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
Chris Lattner564a7272003-08-13 19:01:45 +0000421 unsigned Opcode = Root.getOpcode();
422 Value *LHS = Root.getOperand(0);
423
424 // Quick check, see if the immediate LHS matches...
425 if (F.shouldApply(LHS))
426 return F.apply(Root);
427
428 // Otherwise, if the LHS is not of the same opcode as the root, return.
429 Instruction *LHSI = dyn_cast<Instruction>(LHS);
Chris Lattnerfd059242003-10-15 16:48:29 +0000430 while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
Chris Lattner564a7272003-08-13 19:01:45 +0000431 // Should we apply this transform to the RHS?
432 bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
433
434 // If not to the RHS, check to see if we should apply to the LHS...
435 if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
436 cast<BinaryOperator>(LHSI)->swapOperands(); // Make the LHS the RHS
437 ShouldApply = true;
438 }
439
440 // If the functor wants to apply the optimization to the RHS of LHSI,
441 // reassociate the expression from ((? op A) op B) to (? op (A op B))
442 if (ShouldApply) {
Chris Lattner564a7272003-08-13 19:01:45 +0000443 // Now all of the instructions are in the current basic block, go ahead
444 // and perform the reassociation.
445 Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
446
447 // First move the selected RHS to the LHS of the root...
448 Root.setOperand(0, LHSI->getOperand(1));
449
450 // Make what used to be the LHS of the root be the user of the root...
451 Value *ExtraOperand = TmpLHSI->getOperand(1);
Chris Lattner65725312004-04-16 18:08:07 +0000452 if (&Root == TmpLHSI) {
Owen Andersona7235ea2009-07-31 20:28:14 +0000453 Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
Chris Lattner15a76c02004-04-05 02:10:19 +0000454 return 0;
455 }
Chris Lattner65725312004-04-16 18:08:07 +0000456 Root.replaceAllUsesWith(TmpLHSI); // Users now use TmpLHSI
Chris Lattner564a7272003-08-13 19:01:45 +0000457 TmpLHSI->setOperand(1, &Root); // TmpLHSI now uses the root
Chris Lattner65725312004-04-16 18:08:07 +0000458 BasicBlock::iterator ARI = &Root; ++ARI;
Dan Gohmand02d9172008-06-19 17:47:47 +0000459 TmpLHSI->moveBefore(ARI); // Move TmpLHSI to after Root
Chris Lattner65725312004-04-16 18:08:07 +0000460 ARI = Root;
Chris Lattner564a7272003-08-13 19:01:45 +0000461
462 // Now propagate the ExtraOperand down the chain of instructions until we
463 // get to LHSI.
464 while (TmpLHSI != LHSI) {
465 Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
Chris Lattner65725312004-04-16 18:08:07 +0000466 // Move the instruction to immediately before the chain we are
467 // constructing to avoid breaking dominance properties.
Dan Gohmand02d9172008-06-19 17:47:47 +0000468 NextLHSI->moveBefore(ARI);
Chris Lattner65725312004-04-16 18:08:07 +0000469 ARI = NextLHSI;
470
Chris Lattner564a7272003-08-13 19:01:45 +0000471 Value *NextOp = NextLHSI->getOperand(1);
472 NextLHSI->setOperand(1, ExtraOperand);
473 TmpLHSI = NextLHSI;
474 ExtraOperand = NextOp;
475 }
Misha Brukmanfd939082005-04-21 23:48:37 +0000476
Chris Lattner564a7272003-08-13 19:01:45 +0000477 // Now that the instructions are reassociated, have the functor perform
478 // the transformation...
479 return F.apply(Root);
480 }
Misha Brukmanfd939082005-04-21 23:48:37 +0000481
Chris Lattner564a7272003-08-13 19:01:45 +0000482 LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
483 }
484 return 0;
485}
486
Dan Gohman844731a2008-05-13 00:00:25 +0000487namespace {
Chris Lattner564a7272003-08-13 19:01:45 +0000488
Nick Lewycky02d639f2008-05-23 04:34:58 +0000489// AddRHS - Implements: X + X --> X << 1
Chris Lattner564a7272003-08-13 19:01:45 +0000490struct AddRHS {
491 Value *RHS;
Dan Gohman4ae51262009-08-12 16:23:25 +0000492 explicit AddRHS(Value *rhs) : RHS(rhs) {}
Chris Lattner564a7272003-08-13 19:01:45 +0000493 bool shouldApply(Value *LHS) const { return LHS == RHS; }
494 Instruction *apply(BinaryOperator &Add) const {
Nick Lewycky02d639f2008-05-23 04:34:58 +0000495 return BinaryOperator::CreateShl(Add.getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +0000496 ConstantInt::get(Add.getType(), 1));
Chris Lattner564a7272003-08-13 19:01:45 +0000497 }
498};
499
500// AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
501// iff C1&C2 == 0
502struct AddMaskingAnd {
503 Constant *C2;
Dan Gohman4ae51262009-08-12 16:23:25 +0000504 explicit AddMaskingAnd(Constant *c) : C2(c) {}
Chris Lattner564a7272003-08-13 19:01:45 +0000505 bool shouldApply(Value *LHS) const {
Chris Lattneracd1f0f2004-07-30 07:50:03 +0000506 ConstantInt *C1;
Dan Gohman4ae51262009-08-12 16:23:25 +0000507 return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
Owen Andersonbaf3c402009-07-29 18:55:55 +0000508 ConstantExpr::getAnd(C1, C2)->isNullValue();
Chris Lattner564a7272003-08-13 19:01:45 +0000509 }
510 Instruction *apply(BinaryOperator &Add) const {
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000511 return BinaryOperator::CreateOr(Add.getOperand(0), Add.getOperand(1));
Chris Lattner564a7272003-08-13 19:01:45 +0000512 }
513};
514
Dan Gohman844731a2008-05-13 00:00:25 +0000515}
516
Chris Lattner6e7ba452005-01-01 16:22:27 +0000517static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
Chris Lattner2eefe512004-04-09 19:05:30 +0000518 InstCombiner *IC) {
Chris Lattner08142f22009-08-30 19:47:22 +0000519 if (CastInst *CI = dyn_cast<CastInst>(&I))
Chris Lattner2345d1d2009-08-30 20:01:10 +0000520 return IC->Builder->CreateCast(CI->getOpcode(), SO, I.getType());
Chris Lattner6e7ba452005-01-01 16:22:27 +0000521
Chris Lattner2eefe512004-04-09 19:05:30 +0000522 // Figure out if the constant is the left or the right argument.
Chris Lattner6e7ba452005-01-01 16:22:27 +0000523 bool ConstIsRHS = isa<Constant>(I.getOperand(1));
524 Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
Chris Lattner564a7272003-08-13 19:01:45 +0000525
Chris Lattner2eefe512004-04-09 19:05:30 +0000526 if (Constant *SOC = dyn_cast<Constant>(SO)) {
527 if (ConstIsRHS)
Owen Andersonbaf3c402009-07-29 18:55:55 +0000528 return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
529 return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
Chris Lattner2eefe512004-04-09 19:05:30 +0000530 }
531
532 Value *Op0 = SO, *Op1 = ConstOperand;
533 if (!ConstIsRHS)
534 std::swap(Op0, Op1);
Chris Lattner74381062009-08-30 07:44:24 +0000535
Chris Lattner6e7ba452005-01-01 16:22:27 +0000536 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
Chris Lattner74381062009-08-30 07:44:24 +0000537 return IC->Builder->CreateBinOp(BO->getOpcode(), Op0, Op1,
538 SO->getName()+".op");
539 if (ICmpInst *CI = dyn_cast<ICmpInst>(&I))
540 return IC->Builder->CreateICmp(CI->getPredicate(), Op0, Op1,
541 SO->getName()+".cmp");
542 if (FCmpInst *CI = dyn_cast<FCmpInst>(&I))
543 return IC->Builder->CreateICmp(CI->getPredicate(), Op0, Op1,
544 SO->getName()+".cmp");
545 llvm_unreachable("Unknown binary instruction type!");
Chris Lattner6e7ba452005-01-01 16:22:27 +0000546}
547
548// FoldOpIntoSelect - Given an instruction with a select as one operand and a
549// constant as the other operand, try to fold the binary operator into the
550// select arguments. This also works for Cast instructions, which obviously do
551// not have a second operand.
552static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
553 InstCombiner *IC) {
554 // Don't modify shared select instructions
555 if (!SI->hasOneUse()) return 0;
556 Value *TV = SI->getOperand(1);
557 Value *FV = SI->getOperand(2);
558
559 if (isa<Constant>(TV) || isa<Constant>(FV)) {
Chris Lattner956db272005-04-21 05:43:13 +0000560 // Bool selects with constant operands can be folded to logical ops.
Chris Lattner4de84762010-01-04 07:02:48 +0000561 if (SI->getType() == Type::getInt1Ty(SI->getContext())) return 0;
Chris Lattner956db272005-04-21 05:43:13 +0000562
Chris Lattner6e7ba452005-01-01 16:22:27 +0000563 Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
564 Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
565
Gabor Greif051a9502008-04-06 20:25:17 +0000566 return SelectInst::Create(SI->getCondition(), SelectTrueVal,
567 SelectFalseVal);
Chris Lattner6e7ba452005-01-01 16:22:27 +0000568 }
569 return 0;
Chris Lattner2eefe512004-04-09 19:05:30 +0000570}
571
Chris Lattner4e998b22004-09-29 05:07:12 +0000572
Chris Lattner5d1704d2009-09-27 19:57:57 +0000573/// FoldOpIntoPhi - Given a binary operator, cast instruction, or select which
574/// has a PHI node as operand #0, see if we can fold the instruction into the
575/// PHI (which is only possible if all operands to the PHI are constants).
Chris Lattner213cd612009-09-27 20:46:36 +0000576///
577/// If AllowAggressive is true, FoldOpIntoPhi will allow certain transforms
578/// that would normally be unprofitable because they strongly encourage jump
579/// threading.
580Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I,
581 bool AllowAggressive) {
582 AllowAggressive = false;
Chris Lattner4e998b22004-09-29 05:07:12 +0000583 PHINode *PN = cast<PHINode>(I.getOperand(0));
Chris Lattnerbac32862004-11-14 19:13:23 +0000584 unsigned NumPHIValues = PN->getNumIncomingValues();
Chris Lattner213cd612009-09-27 20:46:36 +0000585 if (NumPHIValues == 0 ||
586 // We normally only transform phis with a single use, unless we're trying
587 // hard to make jump threading happen.
588 (!PN->hasOneUse() && !AllowAggressive))
589 return 0;
590
591
Chris Lattner5d1704d2009-09-27 19:57:57 +0000592 // Check to see if all of the operands of the PHI are simple constants
593 // (constantint/constantfp/undef). If there is one non-constant value,
Chris Lattnerc6df8f42009-09-27 20:18:49 +0000594 // remember the BB it is in. If there is more than one or if *it* is a PHI,
595 // bail out. We don't do arbitrary constant expressions here because moving
596 // their computation can be expensive without a cost model.
Chris Lattner2a86f3b2006-09-09 22:02:56 +0000597 BasicBlock *NonConstBB = 0;
598 for (unsigned i = 0; i != NumPHIValues; ++i)
Chris Lattner5d1704d2009-09-27 19:57:57 +0000599 if (!isa<Constant>(PN->getIncomingValue(i)) ||
600 isa<ConstantExpr>(PN->getIncomingValue(i))) {
Chris Lattner2a86f3b2006-09-09 22:02:56 +0000601 if (NonConstBB) return 0; // More than one non-const value.
Chris Lattnerb3036682007-02-24 01:03:45 +0000602 if (isa<PHINode>(PN->getIncomingValue(i))) return 0; // Itself a phi.
Chris Lattner2a86f3b2006-09-09 22:02:56 +0000603 NonConstBB = PN->getIncomingBlock(i);
604
605 // If the incoming non-constant value is in I's block, we have an infinite
606 // loop.
607 if (NonConstBB == I.getParent())
608 return 0;
609 }
610
611 // If there is exactly one non-constant value, we can insert a copy of the
612 // operation in that block. However, if this is a critical edge, we would be
613 // inserting the computation one some other paths (e.g. inside a loop). Only
614 // do this if the pred block is unconditionally branching into the phi block.
Chris Lattner213cd612009-09-27 20:46:36 +0000615 if (NonConstBB != 0 && !AllowAggressive) {
Chris Lattner2a86f3b2006-09-09 22:02:56 +0000616 BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
617 if (!BI || !BI->isUnconditional()) return 0;
618 }
Chris Lattner4e998b22004-09-29 05:07:12 +0000619
620 // Okay, we can do the transformation: create the new PHI node.
Gabor Greif051a9502008-04-06 20:25:17 +0000621 PHINode *NewPN = PHINode::Create(I.getType(), "");
Chris Lattner55517062005-01-29 00:39:08 +0000622 NewPN->reserveOperandSpace(PN->getNumOperands()/2);
Chris Lattner857eb572009-10-21 23:41:58 +0000623 InsertNewInstBefore(NewPN, *PN);
624 NewPN->takeName(PN);
Chris Lattner4e998b22004-09-29 05:07:12 +0000625
626 // Next, add all of the operands to the PHI.
Chris Lattner5d1704d2009-09-27 19:57:57 +0000627 if (SelectInst *SI = dyn_cast<SelectInst>(&I)) {
628 // We only currently try to fold the condition of a select when it is a phi,
629 // not the true/false values.
Chris Lattnerc6df8f42009-09-27 20:18:49 +0000630 Value *TrueV = SI->getTrueValue();
631 Value *FalseV = SI->getFalseValue();
Chris Lattner3ddfb212009-09-28 06:49:44 +0000632 BasicBlock *PhiTransBB = PN->getParent();
Chris Lattner5d1704d2009-09-27 19:57:57 +0000633 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattnerc6df8f42009-09-27 20:18:49 +0000634 BasicBlock *ThisBB = PN->getIncomingBlock(i);
Chris Lattner3ddfb212009-09-28 06:49:44 +0000635 Value *TrueVInPred = TrueV->DoPHITranslation(PhiTransBB, ThisBB);
636 Value *FalseVInPred = FalseV->DoPHITranslation(PhiTransBB, ThisBB);
Chris Lattner5d1704d2009-09-27 19:57:57 +0000637 Value *InV = 0;
638 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Chris Lattnerc6df8f42009-09-27 20:18:49 +0000639 InV = InC->isNullValue() ? FalseVInPred : TrueVInPred;
Chris Lattner5d1704d2009-09-27 19:57:57 +0000640 } else {
641 assert(PN->getIncomingBlock(i) == NonConstBB);
Chris Lattnerc6df8f42009-09-27 20:18:49 +0000642 InV = SelectInst::Create(PN->getIncomingValue(i), TrueVInPred,
643 FalseVInPred,
Chris Lattner5d1704d2009-09-27 19:57:57 +0000644 "phitmp", NonConstBB->getTerminator());
Chris Lattner857eb572009-10-21 23:41:58 +0000645 Worklist.Add(cast<Instruction>(InV));
Chris Lattner5d1704d2009-09-27 19:57:57 +0000646 }
Chris Lattnerc6df8f42009-09-27 20:18:49 +0000647 NewPN->addIncoming(InV, ThisBB);
Chris Lattner5d1704d2009-09-27 19:57:57 +0000648 }
649 } else if (I.getNumOperands() == 2) {
Chris Lattner4e998b22004-09-29 05:07:12 +0000650 Constant *C = cast<Constant>(I.getOperand(1));
Chris Lattnerbac32862004-11-14 19:13:23 +0000651 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattnera9ff5eb2007-08-05 08:47:58 +0000652 Value *InV = 0;
Chris Lattner2a86f3b2006-09-09 22:02:56 +0000653 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Reid Spencere4d87aa2006-12-23 06:05:41 +0000654 if (CmpInst *CI = dyn_cast<CmpInst>(&I))
Owen Andersonbaf3c402009-07-29 18:55:55 +0000655 InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C);
Reid Spencere4d87aa2006-12-23 06:05:41 +0000656 else
Owen Andersonbaf3c402009-07-29 18:55:55 +0000657 InV = ConstantExpr::get(I.getOpcode(), InC, C);
Chris Lattner2a86f3b2006-09-09 22:02:56 +0000658 } else {
659 assert(PN->getIncomingBlock(i) == NonConstBB);
660 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000661 InV = BinaryOperator::Create(BO->getOpcode(),
Chris Lattner2a86f3b2006-09-09 22:02:56 +0000662 PN->getIncomingValue(i), C, "phitmp",
663 NonConstBB->getTerminator());
Reid Spencere4d87aa2006-12-23 06:05:41 +0000664 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
Dan Gohman1c8a23c2009-08-25 23:17:54 +0000665 InV = CmpInst::Create(CI->getOpcode(),
Reid Spencere4d87aa2006-12-23 06:05:41 +0000666 CI->getPredicate(),
667 PN->getIncomingValue(i), C, "phitmp",
668 NonConstBB->getTerminator());
Chris Lattner2a86f3b2006-09-09 22:02:56 +0000669 else
Torok Edwinc23197a2009-07-14 16:55:14 +0000670 llvm_unreachable("Unknown binop!");
Chris Lattner857eb572009-10-21 23:41:58 +0000671
672 Worklist.Add(cast<Instruction>(InV));
Chris Lattner2a86f3b2006-09-09 22:02:56 +0000673 }
674 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner4e998b22004-09-29 05:07:12 +0000675 }
Reid Spencer3da59db2006-11-27 01:05:10 +0000676 } else {
677 CastInst *CI = cast<CastInst>(&I);
678 const Type *RetTy = CI->getType();
Chris Lattnerbac32862004-11-14 19:13:23 +0000679 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattner2a86f3b2006-09-09 22:02:56 +0000680 Value *InV;
681 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Owen Andersonbaf3c402009-07-29 18:55:55 +0000682 InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
Chris Lattner2a86f3b2006-09-09 22:02:56 +0000683 } else {
684 assert(PN->getIncomingBlock(i) == NonConstBB);
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000685 InV = CastInst::Create(CI->getOpcode(), PN->getIncomingValue(i),
Reid Spencer3da59db2006-11-27 01:05:10 +0000686 I.getType(), "phitmp",
687 NonConstBB->getTerminator());
Chris Lattner857eb572009-10-21 23:41:58 +0000688 Worklist.Add(cast<Instruction>(InV));
Chris Lattner2a86f3b2006-09-09 22:02:56 +0000689 }
690 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner4e998b22004-09-29 05:07:12 +0000691 }
692 }
693 return ReplaceInstUsesWith(I, NewPN);
694}
695
Chris Lattner2454a2e2008-01-29 06:52:45 +0000696
Chris Lattner3d28b1b2008-05-20 05:46:13 +0000697/// WillNotOverflowSignedAdd - Return true if we can prove that:
698/// (sext (add LHS, RHS)) === (add (sext LHS), (sext RHS))
699/// This basically requires proving that the add in the original type would not
700/// overflow to change the sign bit or have a carry out.
701bool InstCombiner::WillNotOverflowSignedAdd(Value *LHS, Value *RHS) {
702 // There are different heuristics we can use for this. Here are some simple
703 // ones.
704
705 // Add has the property that adding any two 2's complement numbers can only
706 // have one carry bit which can change a sign. As such, if LHS and RHS each
Chris Lattner8aee8ef2009-11-27 17:42:22 +0000707 // have at least two sign bits, we know that the addition of the two values
708 // will sign extend fine.
Chris Lattner3d28b1b2008-05-20 05:46:13 +0000709 if (ComputeNumSignBits(LHS) > 1 && ComputeNumSignBits(RHS) > 1)
710 return true;
711
712
713 // If one of the operands only has one non-zero bit, and if the other operand
714 // has a known-zero bit in a more significant place than it (not including the
715 // sign bit) the ripple may go up to and fill the zero, but won't change the
716 // sign. For example, (X & ~4) + 1.
717
718 // TODO: Implement.
719
720 return false;
721}
722
Chris Lattner2454a2e2008-01-29 06:52:45 +0000723
Chris Lattner7e708292002-06-25 16:13:24 +0000724Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +0000725 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +0000726 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
Chris Lattnerb35dde12002-05-06 16:49:18 +0000727
Chris Lattner8aee8ef2009-11-27 17:42:22 +0000728 if (Value *V = SimplifyAddInst(LHS, RHS, I.hasNoSignedWrap(),
729 I.hasNoUnsignedWrap(), TD))
730 return ReplaceInstUsesWith(I, V);
731
732
Chris Lattner66331a42004-04-10 22:01:55 +0000733 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
Chris Lattner66331a42004-04-10 22:01:55 +0000734 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
Chris Lattnerb4a2f052006-11-09 05:12:27 +0000735 // X + (signbit) --> X ^ signbit
Zhou Sheng3a507fd2007-04-01 17:13:37 +0000736 const APInt& Val = CI->getValue();
Zhou Sheng4351c642007-04-02 08:20:41 +0000737 uint32_t BitWidth = Val.getBitWidth();
Reid Spencer2ec619a2007-03-23 21:24:59 +0000738 if (Val == APInt::getSignBit(BitWidth))
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000739 return BinaryOperator::CreateXor(LHS, RHS);
Chris Lattnerb4a2f052006-11-09 05:12:27 +0000740
741 // See if SimplifyDemandedBits can simplify this. This handles stuff like
742 // (X & 254)+1 -> (X&254)|1
Dan Gohman6de29f82009-06-15 22:12:54 +0000743 if (SimplifyDemandedInstructionBits(I))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000744 return &I;
Dan Gohman1975d032008-10-30 20:40:10 +0000745
Eli Friedman709b33d2009-07-13 22:27:52 +0000746 // zext(bool) + C -> bool ? C + 1 : C
Dan Gohman1975d032008-10-30 20:40:10 +0000747 if (ZExtInst *ZI = dyn_cast<ZExtInst>(LHS))
Chris Lattner4de84762010-01-04 07:02:48 +0000748 if (ZI->getSrcTy() == Type::getInt1Ty(I.getContext()))
Dan Gohman186a6362009-08-12 16:04:34 +0000749 return SelectInst::Create(ZI->getOperand(0), AddOne(CI), CI);
Chris Lattner66331a42004-04-10 22:01:55 +0000750 }
Chris Lattner4e998b22004-09-29 05:07:12 +0000751
752 if (isa<PHINode>(LHS))
753 if (Instruction *NV = FoldOpIntoPhi(I))
754 return NV;
Chris Lattner5931c542005-09-24 23:43:33 +0000755
Chris Lattner4f637d42006-01-06 17:59:59 +0000756 ConstantInt *XorRHS = 0;
757 Value *XorLHS = 0;
Chris Lattnerc5eff442007-01-30 22:32:46 +0000758 if (isa<ConstantInt>(RHSC) &&
Dan Gohman4ae51262009-08-12 16:23:25 +0000759 match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
Dan Gohman6de29f82009-06-15 22:12:54 +0000760 uint32_t TySizeBits = I.getType()->getScalarSizeInBits();
Zhou Sheng3a507fd2007-04-01 17:13:37 +0000761 const APInt& RHSVal = cast<ConstantInt>(RHSC)->getValue();
Chris Lattner5931c542005-09-24 23:43:33 +0000762
Zhou Sheng4351c642007-04-02 08:20:41 +0000763 uint32_t Size = TySizeBits / 2;
Reid Spencer2ec619a2007-03-23 21:24:59 +0000764 APInt C0080Val(APInt(TySizeBits, 1ULL).shl(Size - 1));
765 APInt CFF80Val(-C0080Val);
Chris Lattner5931c542005-09-24 23:43:33 +0000766 do {
767 if (TySizeBits > Size) {
Chris Lattner5931c542005-09-24 23:43:33 +0000768 // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
769 // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
Reid Spencer2ec619a2007-03-23 21:24:59 +0000770 if ((RHSVal == CFF80Val && XorRHS->getValue() == C0080Val) ||
771 (RHSVal == C0080Val && XorRHS->getValue() == CFF80Val)) {
Chris Lattner5931c542005-09-24 23:43:33 +0000772 // This is a sign extend if the top bits are known zero.
Zhou Sheng290bec52007-03-29 08:15:12 +0000773 if (!MaskedValueIsZero(XorLHS,
774 APInt::getHighBitsSet(TySizeBits, TySizeBits - Size)))
Chris Lattner5931c542005-09-24 23:43:33 +0000775 Size = 0; // Not a sign ext, but can't be any others either.
Reid Spencer2ec619a2007-03-23 21:24:59 +0000776 break;
Chris Lattner5931c542005-09-24 23:43:33 +0000777 }
778 }
779 Size >>= 1;
Reid Spencer2ec619a2007-03-23 21:24:59 +0000780 C0080Val = APIntOps::lshr(C0080Val, Size);
781 CFF80Val = APIntOps::ashr(CFF80Val, Size);
782 } while (Size >= 1);
Chris Lattner5931c542005-09-24 23:43:33 +0000783
Reid Spencer35c38852007-03-28 01:36:16 +0000784 // FIXME: This shouldn't be necessary. When the backends can handle types
Chris Lattner0c7a9a02008-05-19 20:25:04 +0000785 // with funny bit widths then this switch statement should be removed. It
786 // is just here to get the size of the "middle" type back up to something
787 // that the back ends can handle.
Reid Spencer35c38852007-03-28 01:36:16 +0000788 const Type *MiddleType = 0;
789 switch (Size) {
790 default: break;
Chris Lattner4de84762010-01-04 07:02:48 +0000791 case 32:
792 case 16:
793 case 8: MiddleType = IntegerType::get(I.getContext(), Size); break;
Reid Spencer35c38852007-03-28 01:36:16 +0000794 }
795 if (MiddleType) {
Chris Lattner74381062009-08-30 07:44:24 +0000796 Value *NewTrunc = Builder->CreateTrunc(XorLHS, MiddleType, "sext");
Reid Spencer35c38852007-03-28 01:36:16 +0000797 return new SExtInst(NewTrunc, I.getType(), I.getName());
Chris Lattner5931c542005-09-24 23:43:33 +0000798 }
799 }
Chris Lattner66331a42004-04-10 22:01:55 +0000800 }
Chris Lattnerb35dde12002-05-06 16:49:18 +0000801
Chris Lattner4de84762010-01-04 07:02:48 +0000802 if (I.getType() == Type::getInt1Ty(I.getContext()))
Nick Lewycky9419ddb2008-05-31 17:59:52 +0000803 return BinaryOperator::CreateXor(LHS, RHS);
804
Nick Lewycky7d26bd82008-05-23 04:39:38 +0000805 // X + X --> X << 1
Nick Lewycky9419ddb2008-05-31 17:59:52 +0000806 if (I.getType()->isInteger()) {
Dan Gohman4ae51262009-08-12 16:23:25 +0000807 if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS)))
Owen Andersond672ecb2009-07-03 00:17:18 +0000808 return Result;
Chris Lattner7edc8c22005-04-07 17:14:51 +0000809
810 if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
811 if (RHSI->getOpcode() == Instruction::Sub)
812 if (LHS == RHSI->getOperand(1)) // A + (B - A) --> B
813 return ReplaceInstUsesWith(I, RHSI->getOperand(0));
814 }
815 if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
816 if (LHSI->getOpcode() == Instruction::Sub)
817 if (RHS == LHSI->getOperand(1)) // (B - A) + A --> B
818 return ReplaceInstUsesWith(I, LHSI->getOperand(0));
819 }
Robert Bocchino71698282004-07-27 21:02:21 +0000820 }
Chris Lattnere92d2f42003-08-13 04:18:28 +0000821
Chris Lattner5c4afb92002-05-08 22:46:53 +0000822 // -A + B --> B - A
Chris Lattnerdd12f962008-02-17 21:03:36 +0000823 // -A + -B --> -(A + B)
Dan Gohman186a6362009-08-12 16:04:34 +0000824 if (Value *LHSV = dyn_castNegVal(LHS)) {
Chris Lattnere10c0b92008-02-18 17:50:16 +0000825 if (LHS->getType()->isIntOrIntVector()) {
Dan Gohman186a6362009-08-12 16:04:34 +0000826 if (Value *RHSV = dyn_castNegVal(RHS)) {
Chris Lattner74381062009-08-30 07:44:24 +0000827 Value *NewAdd = Builder->CreateAdd(LHSV, RHSV, "sum");
Dan Gohman4ae51262009-08-12 16:23:25 +0000828 return BinaryOperator::CreateNeg(NewAdd);
Chris Lattnere10c0b92008-02-18 17:50:16 +0000829 }
Chris Lattnerdd12f962008-02-17 21:03:36 +0000830 }
831
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000832 return BinaryOperator::CreateSub(RHS, LHSV);
Chris Lattnerdd12f962008-02-17 21:03:36 +0000833 }
Chris Lattnerb35dde12002-05-06 16:49:18 +0000834
835 // A + -B --> A - B
Chris Lattner8d969642003-03-10 23:06:50 +0000836 if (!isa<Constant>(RHS))
Dan Gohman186a6362009-08-12 16:04:34 +0000837 if (Value *V = dyn_castNegVal(RHS))
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000838 return BinaryOperator::CreateSub(LHS, V);
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000839
Misha Brukmanfd939082005-04-21 23:48:37 +0000840
Chris Lattner50af16a2004-11-13 19:50:12 +0000841 ConstantInt *C2;
Dan Gohman186a6362009-08-12 16:04:34 +0000842 if (Value *X = dyn_castFoldableMul(LHS, C2)) {
Chris Lattner50af16a2004-11-13 19:50:12 +0000843 if (X == RHS) // X*C + X --> X * (C+1)
Dan Gohman186a6362009-08-12 16:04:34 +0000844 return BinaryOperator::CreateMul(RHS, AddOne(C2));
Chris Lattner50af16a2004-11-13 19:50:12 +0000845
846 // X*C1 + X*C2 --> X * (C1+C2)
847 ConstantInt *C1;
Dan Gohman186a6362009-08-12 16:04:34 +0000848 if (X == dyn_castFoldableMul(RHS, C1))
Owen Andersonbaf3c402009-07-29 18:55:55 +0000849 return BinaryOperator::CreateMul(X, ConstantExpr::getAdd(C1, C2));
Chris Lattnerad3448c2003-02-18 19:57:07 +0000850 }
851
852 // X + X*C --> X * (C+1)
Dan Gohman186a6362009-08-12 16:04:34 +0000853 if (dyn_castFoldableMul(RHS, C2) == LHS)
854 return BinaryOperator::CreateMul(LHS, AddOne(C2));
Chris Lattner50af16a2004-11-13 19:50:12 +0000855
Chris Lattnere617c9e2007-01-05 02:17:46 +0000856 // X + ~X --> -1 since ~X = -X-1
Dan Gohman186a6362009-08-12 16:04:34 +0000857 if (dyn_castNotVal(LHS) == RHS ||
858 dyn_castNotVal(RHS) == LHS)
Owen Andersona7235ea2009-07-31 20:28:14 +0000859 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnere617c9e2007-01-05 02:17:46 +0000860
Chris Lattnerad3448c2003-02-18 19:57:07 +0000861
Chris Lattner564a7272003-08-13 19:01:45 +0000862 // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
Dan Gohman4ae51262009-08-12 16:23:25 +0000863 if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
864 if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2)))
Chris Lattnere617c9e2007-01-05 02:17:46 +0000865 return R;
Chris Lattner5e0d7182008-05-19 20:01:56 +0000866
867 // A+B --> A|B iff A and B have no bits set in common.
868 if (const IntegerType *IT = dyn_cast<IntegerType>(I.getType())) {
869 APInt Mask = APInt::getAllOnesValue(IT->getBitWidth());
870 APInt LHSKnownOne(IT->getBitWidth(), 0);
871 APInt LHSKnownZero(IT->getBitWidth(), 0);
872 ComputeMaskedBits(LHS, Mask, LHSKnownZero, LHSKnownOne);
873 if (LHSKnownZero != 0) {
874 APInt RHSKnownOne(IT->getBitWidth(), 0);
875 APInt RHSKnownZero(IT->getBitWidth(), 0);
876 ComputeMaskedBits(RHS, Mask, RHSKnownZero, RHSKnownOne);
877
878 // No bits in common -> bitwise or.
Chris Lattner9d60ba92008-05-19 20:03:53 +0000879 if ((LHSKnownZero|RHSKnownZero).isAllOnesValue())
Chris Lattner5e0d7182008-05-19 20:01:56 +0000880 return BinaryOperator::CreateOr(LHS, RHS);
Chris Lattner5e0d7182008-05-19 20:01:56 +0000881 }
882 }
Chris Lattnerc8802d22003-03-11 00:12:48 +0000883
Nick Lewyckyb6eabff2008-02-03 07:42:09 +0000884 // W*X + Y*Z --> W * (X+Z) iff W == Y
Nick Lewycky0c2c3f62008-02-03 08:19:11 +0000885 if (I.getType()->isIntOrIntVector()) {
Nick Lewyckyb6eabff2008-02-03 07:42:09 +0000886 Value *W, *X, *Y, *Z;
Dan Gohman4ae51262009-08-12 16:23:25 +0000887 if (match(LHS, m_Mul(m_Value(W), m_Value(X))) &&
888 match(RHS, m_Mul(m_Value(Y), m_Value(Z)))) {
Nick Lewyckyb6eabff2008-02-03 07:42:09 +0000889 if (W != Y) {
890 if (W == Z) {
Bill Wendling587c01d2008-02-26 10:53:30 +0000891 std::swap(Y, Z);
Nick Lewyckyb6eabff2008-02-03 07:42:09 +0000892 } else if (Y == X) {
Bill Wendling587c01d2008-02-26 10:53:30 +0000893 std::swap(W, X);
894 } else if (X == Z) {
Nick Lewyckyb6eabff2008-02-03 07:42:09 +0000895 std::swap(Y, Z);
896 std::swap(W, X);
897 }
898 }
899
900 if (W == Y) {
Chris Lattner74381062009-08-30 07:44:24 +0000901 Value *NewAdd = Builder->CreateAdd(X, Z, LHS->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000902 return BinaryOperator::CreateMul(W, NewAdd);
Nick Lewyckyb6eabff2008-02-03 07:42:09 +0000903 }
904 }
905 }
906
Chris Lattner6b032052003-10-02 15:11:26 +0000907 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
Chris Lattner4f637d42006-01-06 17:59:59 +0000908 Value *X = 0;
Dan Gohman4ae51262009-08-12 16:23:25 +0000909 if (match(LHS, m_Not(m_Value(X)))) // ~X + C --> (C-1) - X
Dan Gohman186a6362009-08-12 16:04:34 +0000910 return BinaryOperator::CreateSub(SubOne(CRHS), X);
Chris Lattneracd1f0f2004-07-30 07:50:03 +0000911
Chris Lattnerb99d6b12004-10-08 05:07:56 +0000912 // (X & FF00) + xx00 -> (X+xx00) & FF00
Owen Andersonc7d2ce72009-07-10 17:35:01 +0000913 if (LHS->hasOneUse() &&
Dan Gohman4ae51262009-08-12 16:23:25 +0000914 match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
Owen Andersonbaf3c402009-07-29 18:55:55 +0000915 Constant *Anded = ConstantExpr::getAnd(CRHS, C2);
Chris Lattnerb99d6b12004-10-08 05:07:56 +0000916 if (Anded == CRHS) {
917 // See if all bits from the first bit set in the Add RHS up are included
918 // in the mask. First, get the rightmost bit.
Zhou Sheng3a507fd2007-04-01 17:13:37 +0000919 const APInt& AddRHSV = CRHS->getValue();
Chris Lattnerb99d6b12004-10-08 05:07:56 +0000920
921 // Form a mask of all bits from the lowest bit added through the top.
Zhou Sheng3a507fd2007-04-01 17:13:37 +0000922 APInt AddRHSHighBits(~((AddRHSV & -AddRHSV)-1));
Chris Lattnerb99d6b12004-10-08 05:07:56 +0000923
924 // See if the and mask includes all of these bits.
Zhou Sheng3a507fd2007-04-01 17:13:37 +0000925 APInt AddRHSHighBitsAnd(AddRHSHighBits & C2->getValue());
Misha Brukmanfd939082005-04-21 23:48:37 +0000926
Chris Lattnerb99d6b12004-10-08 05:07:56 +0000927 if (AddRHSHighBits == AddRHSHighBitsAnd) {
928 // Okay, the xform is safe. Insert the new add pronto.
Chris Lattner74381062009-08-30 07:44:24 +0000929 Value *NewAdd = Builder->CreateAdd(X, CRHS, LHS->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000930 return BinaryOperator::CreateAnd(NewAdd, C2);
Chris Lattnerb99d6b12004-10-08 05:07:56 +0000931 }
932 }
933 }
934
Chris Lattneracd1f0f2004-07-30 07:50:03 +0000935 // Try to fold constant add into select arguments.
936 if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
Chris Lattner6e7ba452005-01-01 16:22:27 +0000937 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattneracd1f0f2004-07-30 07:50:03 +0000938 return R;
Chris Lattner6b032052003-10-02 15:11:26 +0000939 }
940
Chris Lattner42790482007-12-20 01:56:58 +0000941 // add (select X 0 (sub n A)) A --> select X A n
Christopher Lamb30f017a2007-12-18 09:34:41 +0000942 {
943 SelectInst *SI = dyn_cast<SelectInst>(LHS);
Chris Lattner6046fb72008-11-16 04:46:19 +0000944 Value *A = RHS;
Christopher Lamb30f017a2007-12-18 09:34:41 +0000945 if (!SI) {
946 SI = dyn_cast<SelectInst>(RHS);
Chris Lattner6046fb72008-11-16 04:46:19 +0000947 A = LHS;
Christopher Lamb30f017a2007-12-18 09:34:41 +0000948 }
Chris Lattner42790482007-12-20 01:56:58 +0000949 if (SI && SI->hasOneUse()) {
Christopher Lamb30f017a2007-12-18 09:34:41 +0000950 Value *TV = SI->getTrueValue();
951 Value *FV = SI->getFalseValue();
Chris Lattner6046fb72008-11-16 04:46:19 +0000952 Value *N;
Christopher Lamb30f017a2007-12-18 09:34:41 +0000953
954 // Can we fold the add into the argument of the select?
955 // We check both true and false select arguments for a matching subtract.
Dan Gohman4ae51262009-08-12 16:23:25 +0000956 if (match(FV, m_Zero()) &&
957 match(TV, m_Sub(m_Value(N), m_Specific(A))))
Chris Lattner6046fb72008-11-16 04:46:19 +0000958 // Fold the add into the true select value.
Gabor Greif051a9502008-04-06 20:25:17 +0000959 return SelectInst::Create(SI->getCondition(), N, A);
Dan Gohman4ae51262009-08-12 16:23:25 +0000960 if (match(TV, m_Zero()) &&
961 match(FV, m_Sub(m_Value(N), m_Specific(A))))
Chris Lattner6046fb72008-11-16 04:46:19 +0000962 // Fold the add into the false select value.
Gabor Greif051a9502008-04-06 20:25:17 +0000963 return SelectInst::Create(SI->getCondition(), A, N);
Christopher Lamb30f017a2007-12-18 09:34:41 +0000964 }
965 }
Andrew Lenharth16d79552006-09-19 18:24:51 +0000966
Chris Lattner3d28b1b2008-05-20 05:46:13 +0000967 // Check for (add (sext x), y), see if we can merge this into an
968 // integer add followed by a sext.
969 if (SExtInst *LHSConv = dyn_cast<SExtInst>(LHS)) {
970 // (add (sext x), cst) --> (sext (add x, cst'))
971 if (ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS)) {
972 Constant *CI =
Owen Andersonbaf3c402009-07-29 18:55:55 +0000973 ConstantExpr::getTrunc(RHSC, LHSConv->getOperand(0)->getType());
Chris Lattner3d28b1b2008-05-20 05:46:13 +0000974 if (LHSConv->hasOneUse() &&
Owen Andersonbaf3c402009-07-29 18:55:55 +0000975 ConstantExpr::getSExt(CI, I.getType()) == RHSC &&
Chris Lattner3d28b1b2008-05-20 05:46:13 +0000976 WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
977 // Insert the new, smaller add.
Dan Gohmanfe359552009-10-26 22:14:22 +0000978 Value *NewAdd = Builder->CreateNSWAdd(LHSConv->getOperand(0),
979 CI, "addconv");
Chris Lattner3d28b1b2008-05-20 05:46:13 +0000980 return new SExtInst(NewAdd, I.getType());
981 }
982 }
983
984 // (add (sext x), (sext y)) --> (sext (add int x, y))
985 if (SExtInst *RHSConv = dyn_cast<SExtInst>(RHS)) {
986 // Only do this if x/y have the same type, if at last one of them has a
987 // single use (so we don't increase the number of sexts), and if the
988 // integer add will not overflow.
989 if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
990 (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
991 WillNotOverflowSignedAdd(LHSConv->getOperand(0),
992 RHSConv->getOperand(0))) {
993 // Insert the new integer add.
Dan Gohmanfe359552009-10-26 22:14:22 +0000994 Value *NewAdd = Builder->CreateNSWAdd(LHSConv->getOperand(0),
995 RHSConv->getOperand(0), "addconv");
Chris Lattner3d28b1b2008-05-20 05:46:13 +0000996 return new SExtInst(NewAdd, I.getType());
997 }
998 }
999 }
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001000
1001 return Changed ? &I : 0;
1002}
1003
1004Instruction *InstCombiner::visitFAdd(BinaryOperator &I) {
1005 bool Changed = SimplifyCommutative(I);
1006 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
1007
1008 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
1009 // X + 0 --> X
1010 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
Owen Anderson6f83c9c2009-07-27 20:59:43 +00001011 if (CFP->isExactlyValue(ConstantFP::getNegativeZero
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001012 (I.getType())->getValueAPF()))
1013 return ReplaceInstUsesWith(I, LHS);
1014 }
1015
1016 if (isa<PHINode>(LHS))
1017 if (Instruction *NV = FoldOpIntoPhi(I))
1018 return NV;
1019 }
1020
1021 // -A + B --> B - A
1022 // -A + -B --> -(A + B)
Dan Gohman186a6362009-08-12 16:04:34 +00001023 if (Value *LHSV = dyn_castFNegVal(LHS))
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001024 return BinaryOperator::CreateFSub(RHS, LHSV);
1025
1026 // A + -B --> A - B
1027 if (!isa<Constant>(RHS))
Dan Gohman186a6362009-08-12 16:04:34 +00001028 if (Value *V = dyn_castFNegVal(RHS))
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001029 return BinaryOperator::CreateFSub(LHS, V);
1030
1031 // Check for X+0.0. Simplify it to X if we know X is not -0.0.
1032 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS))
1033 if (CFP->getValueAPF().isPosZero() && CannotBeNegativeZero(LHS))
1034 return ReplaceInstUsesWith(I, LHS);
1035
Chris Lattner3d28b1b2008-05-20 05:46:13 +00001036 // Check for (add double (sitofp x), y), see if we can merge this into an
1037 // integer add followed by a promotion.
1038 if (SIToFPInst *LHSConv = dyn_cast<SIToFPInst>(LHS)) {
1039 // (add double (sitofp x), fpcst) --> (sitofp (add int x, intcst))
1040 // ... if the constant fits in the integer value. This is useful for things
1041 // like (double)(x & 1234) + 4.0 -> (double)((X & 1234)+4) which no longer
1042 // requires a constant pool load, and generally allows the add to be better
1043 // instcombined.
1044 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS)) {
1045 Constant *CI =
Owen Andersonbaf3c402009-07-29 18:55:55 +00001046 ConstantExpr::getFPToSI(CFP, LHSConv->getOperand(0)->getType());
Chris Lattner3d28b1b2008-05-20 05:46:13 +00001047 if (LHSConv->hasOneUse() &&
Owen Andersonbaf3c402009-07-29 18:55:55 +00001048 ConstantExpr::getSIToFP(CI, I.getType()) == CFP &&
Chris Lattner3d28b1b2008-05-20 05:46:13 +00001049 WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
1050 // Insert the new integer add.
Dan Gohmanfe359552009-10-26 22:14:22 +00001051 Value *NewAdd = Builder->CreateNSWAdd(LHSConv->getOperand(0),
1052 CI, "addconv");
Chris Lattner3d28b1b2008-05-20 05:46:13 +00001053 return new SIToFPInst(NewAdd, I.getType());
1054 }
1055 }
1056
1057 // (add double (sitofp x), (sitofp y)) --> (sitofp (add int x, y))
1058 if (SIToFPInst *RHSConv = dyn_cast<SIToFPInst>(RHS)) {
1059 // Only do this if x/y have the same type, if at last one of them has a
1060 // single use (so we don't increase the number of int->fp conversions),
1061 // and if the integer add will not overflow.
1062 if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
1063 (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
1064 WillNotOverflowSignedAdd(LHSConv->getOperand(0),
1065 RHSConv->getOperand(0))) {
1066 // Insert the new integer add.
Dan Gohmanfe359552009-10-26 22:14:22 +00001067 Value *NewAdd = Builder->CreateNSWAdd(LHSConv->getOperand(0),
Chris Lattner092543c2009-11-04 08:05:20 +00001068 RHSConv->getOperand(0),"addconv");
Chris Lattner3d28b1b2008-05-20 05:46:13 +00001069 return new SIToFPInst(NewAdd, I.getType());
1070 }
1071 }
1072 }
1073
Chris Lattner7e708292002-06-25 16:13:24 +00001074 return Changed ? &I : 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00001075}
1076
Chris Lattner092543c2009-11-04 08:05:20 +00001077
1078/// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
1079/// code necessary to compute the offset from the base pointer (without adding
1080/// in the base pointer). Return the result as a signed integer of intptr size.
Chris Lattner02446fc2010-01-04 07:37:31 +00001081Value *InstCombiner::EmitGEPOffset(User *GEP) {
1082 TargetData &TD = *getTargetData();
Chris Lattner092543c2009-11-04 08:05:20 +00001083 gep_type_iterator GTI = gep_type_begin(GEP);
1084 const Type *IntPtrTy = TD.getIntPtrType(GEP->getContext());
1085 Value *Result = Constant::getNullValue(IntPtrTy);
1086
1087 // Build a mask for high order bits.
1088 unsigned IntPtrWidth = TD.getPointerSizeInBits();
1089 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
1090
1091 for (User::op_iterator i = GEP->op_begin() + 1, e = GEP->op_end(); i != e;
1092 ++i, ++GTI) {
1093 Value *Op = *i;
1094 uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType()) & PtrSizeMask;
1095 if (ConstantInt *OpC = dyn_cast<ConstantInt>(Op)) {
1096 if (OpC->isZero()) continue;
1097
1098 // Handle a struct index, which adds its field offset to the pointer.
1099 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
1100 Size = TD.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
1101
Chris Lattner02446fc2010-01-04 07:37:31 +00001102 Result = Builder->CreateAdd(Result,
1103 ConstantInt::get(IntPtrTy, Size),
1104 GEP->getName()+".offs");
Chris Lattner092543c2009-11-04 08:05:20 +00001105 continue;
1106 }
1107
1108 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
1109 Constant *OC =
1110 ConstantExpr::getIntegerCast(OpC, IntPtrTy, true /*SExt*/);
1111 Scale = ConstantExpr::getMul(OC, Scale);
1112 // Emit an add instruction.
Chris Lattner02446fc2010-01-04 07:37:31 +00001113 Result = Builder->CreateAdd(Result, Scale, GEP->getName()+".offs");
Chris Lattner092543c2009-11-04 08:05:20 +00001114 continue;
1115 }
1116 // Convert to correct type.
1117 if (Op->getType() != IntPtrTy)
Chris Lattner02446fc2010-01-04 07:37:31 +00001118 Op = Builder->CreateIntCast(Op, IntPtrTy, true, Op->getName()+".c");
Chris Lattner092543c2009-11-04 08:05:20 +00001119 if (Size != 1) {
1120 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
1121 // We'll let instcombine(mul) convert this to a shl if possible.
Chris Lattner02446fc2010-01-04 07:37:31 +00001122 Op = Builder->CreateMul(Op, Scale, GEP->getName()+".idx");
Chris Lattner092543c2009-11-04 08:05:20 +00001123 }
1124
1125 // Emit an add instruction.
Chris Lattner02446fc2010-01-04 07:37:31 +00001126 Result = Builder->CreateAdd(Op, Result, GEP->getName()+".offs");
Chris Lattner092543c2009-11-04 08:05:20 +00001127 }
1128 return Result;
1129}
1130
1131
Chris Lattner092543c2009-11-04 08:05:20 +00001132
1133
1134/// Optimize pointer differences into the same array into a size. Consider:
1135/// &A[10] - &A[0]: we should compile this to "10". LHS/RHS are the pointer
1136/// operands to the ptrtoint instructions for the LHS/RHS of the subtract.
1137///
1138Value *InstCombiner::OptimizePointerDifference(Value *LHS, Value *RHS,
1139 const Type *Ty) {
1140 assert(TD && "Must have target data info for this");
1141
1142 // If LHS is a gep based on RHS or RHS is a gep based on LHS, we can optimize
1143 // this.
1144 bool Swapped;
Chris Lattner85c1c962010-01-01 22:42:29 +00001145 GetElementPtrInst *GEP = 0;
1146 ConstantExpr *CstGEP = 0;
Chris Lattner092543c2009-11-04 08:05:20 +00001147
Chris Lattner85c1c962010-01-01 22:42:29 +00001148 // TODO: Could also optimize &A[i] - &A[j] -> "i-j", and "&A.foo[i] - &A.foo".
1149 // For now we require one side to be the base pointer "A" or a constant
1150 // expression derived from it.
1151 if (GetElementPtrInst *LHSGEP = dyn_cast<GetElementPtrInst>(LHS)) {
1152 // (gep X, ...) - X
1153 if (LHSGEP->getOperand(0) == RHS) {
1154 GEP = LHSGEP;
1155 Swapped = false;
1156 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(RHS)) {
1157 // (gep X, ...) - (ce_gep X, ...)
1158 if (CE->getOpcode() == Instruction::GetElementPtr &&
1159 LHSGEP->getOperand(0) == CE->getOperand(0)) {
1160 CstGEP = CE;
1161 GEP = LHSGEP;
1162 Swapped = false;
1163 }
1164 }
1165 }
1166
1167 if (GetElementPtrInst *RHSGEP = dyn_cast<GetElementPtrInst>(RHS)) {
1168 // X - (gep X, ...)
1169 if (RHSGEP->getOperand(0) == LHS) {
1170 GEP = RHSGEP;
1171 Swapped = true;
1172 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(LHS)) {
1173 // (ce_gep X, ...) - (gep X, ...)
1174 if (CE->getOpcode() == Instruction::GetElementPtr &&
1175 RHSGEP->getOperand(0) == CE->getOperand(0)) {
1176 CstGEP = CE;
1177 GEP = RHSGEP;
1178 Swapped = true;
1179 }
1180 }
1181 }
1182
1183 if (GEP == 0)
Chris Lattner092543c2009-11-04 08:05:20 +00001184 return 0;
1185
Chris Lattner092543c2009-11-04 08:05:20 +00001186 // Emit the offset of the GEP and an intptr_t.
Chris Lattner02446fc2010-01-04 07:37:31 +00001187 Value *Result = EmitGEPOffset(GEP);
Chris Lattner85c1c962010-01-01 22:42:29 +00001188
1189 // If we had a constant expression GEP on the other side offsetting the
1190 // pointer, subtract it from the offset we have.
1191 if (CstGEP) {
Chris Lattner02446fc2010-01-04 07:37:31 +00001192 Value *CstOffset = EmitGEPOffset(CstGEP);
Chris Lattner85c1c962010-01-01 22:42:29 +00001193 Result = Builder->CreateSub(Result, CstOffset);
1194 }
1195
Chris Lattner092543c2009-11-04 08:05:20 +00001196
1197 // If we have p - gep(p, ...) then we have to negate the result.
1198 if (Swapped)
1199 Result = Builder->CreateNeg(Result, "diff.neg");
1200
1201 return Builder->CreateIntCast(Result, Ty, true);
1202}
1203
1204
Chris Lattner7e708292002-06-25 16:13:24 +00001205Instruction *InstCombiner::visitSub(BinaryOperator &I) {
Chris Lattner7e708292002-06-25 16:13:24 +00001206 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00001207
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001208 if (Op0 == Op1) // sub X, X -> 0
Owen Andersona7235ea2009-07-31 20:28:14 +00001209 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerdd841ae2002-04-18 17:39:14 +00001210
Chris Lattner3bf68152009-12-21 04:04:05 +00001211 // If this is a 'B = x-(-A)', change to B = x+A. This preserves NSW/NUW.
1212 if (Value *V = dyn_castNegVal(Op1)) {
1213 BinaryOperator *Res = BinaryOperator::CreateAdd(Op0, V);
1214 Res->setHasNoSignedWrap(I.hasNoSignedWrap());
1215 Res->setHasNoUnsignedWrap(I.hasNoUnsignedWrap());
1216 return Res;
1217 }
Chris Lattnerb35dde12002-05-06 16:49:18 +00001218
Chris Lattnere87597f2004-10-16 18:11:37 +00001219 if (isa<UndefValue>(Op0))
1220 return ReplaceInstUsesWith(I, Op0); // undef - X -> undef
1221 if (isa<UndefValue>(Op1))
1222 return ReplaceInstUsesWith(I, Op1); // X - undef -> undef
Chris Lattner4de84762010-01-04 07:02:48 +00001223 if (I.getType() == Type::getInt1Ty(I.getContext()))
Chris Lattner092543c2009-11-04 08:05:20 +00001224 return BinaryOperator::CreateXor(Op0, Op1);
1225
Chris Lattnerd65460f2003-11-05 01:06:05 +00001226 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
Chris Lattner092543c2009-11-04 08:05:20 +00001227 // Replace (-1 - A) with (~A).
Chris Lattnera2881962003-02-18 19:28:33 +00001228 if (C->isAllOnesValue())
Dan Gohman4ae51262009-08-12 16:23:25 +00001229 return BinaryOperator::CreateNot(Op1);
Chris Lattner40371712002-05-09 01:29:19 +00001230
Chris Lattnerd65460f2003-11-05 01:06:05 +00001231 // C - ~X == X + (1+C)
Reid Spencer4b828e62005-06-18 17:37:34 +00001232 Value *X = 0;
Dan Gohman4ae51262009-08-12 16:23:25 +00001233 if (match(Op1, m_Not(m_Value(X))))
Dan Gohman186a6362009-08-12 16:04:34 +00001234 return BinaryOperator::CreateAdd(X, AddOne(C));
Reid Spencer7177c3a2007-03-25 05:33:51 +00001235
Chris Lattner76b7a062007-01-15 07:02:54 +00001236 // -(X >>u 31) -> (X >>s 31)
1237 // -(X >>s 31) -> (X >>u 31)
Zhou Sheng302748d2007-03-30 17:20:39 +00001238 if (C->isZero()) {
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00001239 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op1)) {
Reid Spencer3822ff52006-11-08 06:47:33 +00001240 if (SI->getOpcode() == Instruction::LShr) {
Reid Spencerb83eb642006-10-20 07:07:24 +00001241 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
Chris Lattner9c290672004-03-12 23:53:13 +00001242 // Check to see if we are shifting out everything but the sign bit.
Zhou Sheng302748d2007-03-30 17:20:39 +00001243 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
Reid Spencerb83eb642006-10-20 07:07:24 +00001244 SI->getType()->getPrimitiveSizeInBits()-1) {
Reid Spencer3822ff52006-11-08 06:47:33 +00001245 // Ok, the transformation is safe. Insert AShr.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001246 return BinaryOperator::Create(Instruction::AShr,
Reid Spencer832254e2007-02-02 02:16:23 +00001247 SI->getOperand(0), CU, SI->getName());
Chris Lattner9c290672004-03-12 23:53:13 +00001248 }
1249 }
Chris Lattner092543c2009-11-04 08:05:20 +00001250 } else if (SI->getOpcode() == Instruction::AShr) {
Reid Spencer3822ff52006-11-08 06:47:33 +00001251 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
1252 // Check to see if we are shifting out everything but the sign bit.
Zhou Sheng302748d2007-03-30 17:20:39 +00001253 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
Reid Spencer3822ff52006-11-08 06:47:33 +00001254 SI->getType()->getPrimitiveSizeInBits()-1) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00001255 // Ok, the transformation is safe. Insert LShr.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001256 return BinaryOperator::CreateLShr(
Reid Spencer832254e2007-02-02 02:16:23 +00001257 SI->getOperand(0), CU, SI->getName());
Reid Spencer3822ff52006-11-08 06:47:33 +00001258 }
1259 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00001260 }
1261 }
Chris Lattnerbfe492b2004-03-13 00:11:49 +00001262 }
Chris Lattner2eefe512004-04-09 19:05:30 +00001263
1264 // Try to fold constant sub into select arguments.
1265 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner6e7ba452005-01-01 16:22:27 +00001266 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00001267 return R;
Eli Friedman709b33d2009-07-13 22:27:52 +00001268
1269 // C - zext(bool) -> bool ? C - 1 : C
1270 if (ZExtInst *ZI = dyn_cast<ZExtInst>(Op1))
Chris Lattner4de84762010-01-04 07:02:48 +00001271 if (ZI->getSrcTy() == Type::getInt1Ty(I.getContext()))
Dan Gohman186a6362009-08-12 16:04:34 +00001272 return SelectInst::Create(ZI->getOperand(0), SubOne(C), C);
Chris Lattnerd65460f2003-11-05 01:06:05 +00001273 }
1274
Chris Lattner43d84d62005-04-07 16:15:25 +00001275 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001276 if (Op1I->getOpcode() == Instruction::Add) {
Chris Lattner08954a22005-04-07 16:28:01 +00001277 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
Dan Gohman4ae51262009-08-12 16:23:25 +00001278 return BinaryOperator::CreateNeg(Op1I->getOperand(1),
Owen Anderson0a5372e2009-07-13 04:09:18 +00001279 I.getName());
Chris Lattner08954a22005-04-07 16:28:01 +00001280 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
Dan Gohman4ae51262009-08-12 16:23:25 +00001281 return BinaryOperator::CreateNeg(Op1I->getOperand(0),
Owen Anderson0a5372e2009-07-13 04:09:18 +00001282 I.getName());
Chris Lattner08954a22005-04-07 16:28:01 +00001283 else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
1284 if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
1285 // C1-(X+C2) --> (C1-C2)-X
Owen Andersond672ecb2009-07-03 00:17:18 +00001286 return BinaryOperator::CreateSub(
Owen Andersonbaf3c402009-07-29 18:55:55 +00001287 ConstantExpr::getSub(CI1, CI2), Op1I->getOperand(0));
Chris Lattner08954a22005-04-07 16:28:01 +00001288 }
Chris Lattner43d84d62005-04-07 16:15:25 +00001289 }
1290
Chris Lattnerfd059242003-10-15 16:48:29 +00001291 if (Op1I->hasOneUse()) {
Chris Lattnera2881962003-02-18 19:28:33 +00001292 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
1293 // is not used by anyone else...
1294 //
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001295 if (Op1I->getOpcode() == Instruction::Sub) {
Chris Lattnera2881962003-02-18 19:28:33 +00001296 // Swap the two operands of the subexpr...
1297 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
1298 Op1I->setOperand(0, IIOp1);
1299 Op1I->setOperand(1, IIOp0);
Misha Brukmanfd939082005-04-21 23:48:37 +00001300
Chris Lattnera2881962003-02-18 19:28:33 +00001301 // Create the new top level add instruction...
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001302 return BinaryOperator::CreateAdd(Op0, Op1);
Chris Lattnera2881962003-02-18 19:28:33 +00001303 }
1304
1305 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
1306 //
1307 if (Op1I->getOpcode() == Instruction::And &&
1308 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
1309 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
1310
Chris Lattner74381062009-08-30 07:44:24 +00001311 Value *NewNot = Builder->CreateNot(OtherOp, "B.not");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001312 return BinaryOperator::CreateAnd(Op0, NewNot);
Chris Lattnera2881962003-02-18 19:28:33 +00001313 }
Chris Lattnerad3448c2003-02-18 19:57:07 +00001314
Reid Spencerac5209e2006-10-16 23:08:08 +00001315 // 0 - (X sdiv C) -> (X sdiv -C)
Reid Spencer1628cec2006-10-26 06:15:43 +00001316 if (Op1I->getOpcode() == Instruction::SDiv)
Reid Spencerb83eb642006-10-20 07:07:24 +00001317 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
Zhou Sheng843f07672007-04-19 05:39:12 +00001318 if (CSI->isZero())
Chris Lattner91ccc152004-10-06 15:08:25 +00001319 if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001320 return BinaryOperator::CreateSDiv(Op1I->getOperand(0),
Owen Andersonbaf3c402009-07-29 18:55:55 +00001321 ConstantExpr::getNeg(DivRHS));
Chris Lattner91ccc152004-10-06 15:08:25 +00001322
Chris Lattnerad3448c2003-02-18 19:57:07 +00001323 // X - X*C --> X * (1-C)
Reid Spencer4b828e62005-06-18 17:37:34 +00001324 ConstantInt *C2 = 0;
Dan Gohman186a6362009-08-12 16:04:34 +00001325 if (dyn_castFoldableMul(Op1I, C2) == Op0) {
Owen Andersond672ecb2009-07-03 00:17:18 +00001326 Constant *CP1 =
Owen Andersonbaf3c402009-07-29 18:55:55 +00001327 ConstantExpr::getSub(ConstantInt::get(I.getType(), 1),
Dan Gohman6de29f82009-06-15 22:12:54 +00001328 C2);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001329 return BinaryOperator::CreateMul(Op0, CP1);
Chris Lattnerad3448c2003-02-18 19:57:07 +00001330 }
Chris Lattner40371712002-05-09 01:29:19 +00001331 }
Chris Lattner43d84d62005-04-07 16:15:25 +00001332 }
Chris Lattnera2881962003-02-18 19:28:33 +00001333
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001334 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
1335 if (Op0I->getOpcode() == Instruction::Add) {
1336 if (Op0I->getOperand(0) == Op1) // (Y+X)-Y == X
1337 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
1338 else if (Op0I->getOperand(1) == Op1) // (X+Y)-Y == X
1339 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
1340 } else if (Op0I->getOpcode() == Instruction::Sub) {
1341 if (Op0I->getOperand(0) == Op1) // (X-Y)-X == -Y
Dan Gohman4ae51262009-08-12 16:23:25 +00001342 return BinaryOperator::CreateNeg(Op0I->getOperand(1),
Owen Anderson0a5372e2009-07-13 04:09:18 +00001343 I.getName());
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00001344 }
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001345 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001346
Chris Lattner50af16a2004-11-13 19:50:12 +00001347 ConstantInt *C1;
Dan Gohman186a6362009-08-12 16:04:34 +00001348 if (Value *X = dyn_castFoldableMul(Op0, C1)) {
Reid Spencer7177c3a2007-03-25 05:33:51 +00001349 if (X == Op1) // X*C - X --> X * (C-1)
Dan Gohman186a6362009-08-12 16:04:34 +00001350 return BinaryOperator::CreateMul(Op1, SubOne(C1));
Chris Lattnerad3448c2003-02-18 19:57:07 +00001351
Chris Lattner50af16a2004-11-13 19:50:12 +00001352 ConstantInt *C2; // X*C1 - X*C2 -> X * (C1-C2)
Dan Gohman186a6362009-08-12 16:04:34 +00001353 if (X == dyn_castFoldableMul(Op1, C2))
Owen Andersonbaf3c402009-07-29 18:55:55 +00001354 return BinaryOperator::CreateMul(X, ConstantExpr::getSub(C1, C2));
Chris Lattner50af16a2004-11-13 19:50:12 +00001355 }
Chris Lattner092543c2009-11-04 08:05:20 +00001356
1357 // Optimize pointer differences into the same array into a size. Consider:
1358 // &A[10] - &A[0]: we should compile this to "10".
1359 if (TD) {
Chris Lattner33767182010-01-01 22:12:03 +00001360 Value *LHSOp, *RHSOp;
Chris Lattnerf2ebc682010-01-01 22:29:12 +00001361 if (match(Op0, m_PtrToInt(m_Value(LHSOp))) &&
1362 match(Op1, m_PtrToInt(m_Value(RHSOp))))
Chris Lattner33767182010-01-01 22:12:03 +00001363 if (Value *Res = OptimizePointerDifference(LHSOp, RHSOp, I.getType()))
1364 return ReplaceInstUsesWith(I, Res);
Chris Lattner092543c2009-11-04 08:05:20 +00001365
1366 // trunc(p)-trunc(q) -> trunc(p-q)
Chris Lattnerf2ebc682010-01-01 22:29:12 +00001367 if (match(Op0, m_Trunc(m_PtrToInt(m_Value(LHSOp)))) &&
1368 match(Op1, m_Trunc(m_PtrToInt(m_Value(RHSOp)))))
1369 if (Value *Res = OptimizePointerDifference(LHSOp, RHSOp, I.getType()))
1370 return ReplaceInstUsesWith(I, Res);
Chris Lattner092543c2009-11-04 08:05:20 +00001371 }
1372
Chris Lattner3f5b8772002-05-06 16:14:14 +00001373 return 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00001374}
1375
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001376Instruction *InstCombiner::visitFSub(BinaryOperator &I) {
1377 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1378
1379 // If this is a 'B = x-(-A)', change to B = x+A...
Dan Gohman186a6362009-08-12 16:04:34 +00001380 if (Value *V = dyn_castFNegVal(Op1))
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001381 return BinaryOperator::CreateFAdd(Op0, V);
1382
1383 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
1384 if (Op1I->getOpcode() == Instruction::FAdd) {
1385 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
Dan Gohman4ae51262009-08-12 16:23:25 +00001386 return BinaryOperator::CreateFNeg(Op1I->getOperand(1),
Owen Anderson0a5372e2009-07-13 04:09:18 +00001387 I.getName());
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001388 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
Dan Gohman4ae51262009-08-12 16:23:25 +00001389 return BinaryOperator::CreateFNeg(Op1I->getOperand(0),
Owen Anderson0a5372e2009-07-13 04:09:18 +00001390 I.getName());
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001391 }
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001392 }
1393
1394 return 0;
1395}
1396
Chris Lattner7e708292002-06-25 16:13:24 +00001397Instruction *InstCombiner::visitMul(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00001398 bool Changed = SimplifyCommutative(I);
Chris Lattnera2498472009-10-11 21:36:10 +00001399 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerdd841ae2002-04-18 17:39:14 +00001400
Chris Lattnera2498472009-10-11 21:36:10 +00001401 if (isa<UndefValue>(Op1)) // undef * X -> 0
Owen Andersona7235ea2009-07-31 20:28:14 +00001402 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00001403
Chris Lattner8af304a2009-10-11 07:53:15 +00001404 // Simplify mul instructions with a constant RHS.
Chris Lattnera2498472009-10-11 21:36:10 +00001405 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
1406 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1C)) {
Chris Lattnere92d2f42003-08-13 04:18:28 +00001407
1408 // ((X << C1)*C2) == (X * (C2 << C1))
Reid Spencer832254e2007-02-02 02:16:23 +00001409 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op0))
Chris Lattnere92d2f42003-08-13 04:18:28 +00001410 if (SI->getOpcode() == Instruction::Shl)
1411 if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001412 return BinaryOperator::CreateMul(SI->getOperand(0),
Owen Andersonbaf3c402009-07-29 18:55:55 +00001413 ConstantExpr::getShl(CI, ShOp));
Misha Brukmanfd939082005-04-21 23:48:37 +00001414
Zhou Sheng843f07672007-04-19 05:39:12 +00001415 if (CI->isZero())
Chris Lattnera2498472009-10-11 21:36:10 +00001416 return ReplaceInstUsesWith(I, Op1C); // X * 0 == 0
Chris Lattner515c97c2003-09-11 22:24:54 +00001417 if (CI->equalsInt(1)) // X * 1 == X
1418 return ReplaceInstUsesWith(I, Op0);
1419 if (CI->isAllOnesValue()) // X * -1 == 0 - X
Dan Gohman4ae51262009-08-12 16:23:25 +00001420 return BinaryOperator::CreateNeg(Op0, I.getName());
Chris Lattner6c1ce212002-04-29 22:24:47 +00001421
Zhou Sheng97b52c22007-03-29 01:57:21 +00001422 const APInt& Val = cast<ConstantInt>(CI)->getValue();
Reid Spencerbca0e382007-03-23 20:05:17 +00001423 if (Val.isPowerOf2()) { // Replace X*(2^C) with X << C
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001424 return BinaryOperator::CreateShl(Op0,
Owen Andersoneed707b2009-07-24 23:12:02 +00001425 ConstantInt::get(Op0->getType(), Val.logBase2()));
Chris Lattnerbcd7db52005-08-02 19:16:58 +00001426 }
Chris Lattnera2498472009-10-11 21:36:10 +00001427 } else if (isa<VectorType>(Op1C->getType())) {
1428 if (Op1C->isNullValue())
1429 return ReplaceInstUsesWith(I, Op1C);
Nick Lewycky895f0852008-11-27 20:21:08 +00001430
Chris Lattnera2498472009-10-11 21:36:10 +00001431 if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1C)) {
Nick Lewycky895f0852008-11-27 20:21:08 +00001432 if (Op1V->isAllOnesValue()) // X * -1 == 0 - X
Dan Gohman4ae51262009-08-12 16:23:25 +00001433 return BinaryOperator::CreateNeg(Op0, I.getName());
Nick Lewycky895f0852008-11-27 20:21:08 +00001434
1435 // As above, vector X*splat(1.0) -> X in all defined cases.
1436 if (Constant *Splat = Op1V->getSplatValue()) {
Nick Lewycky895f0852008-11-27 20:21:08 +00001437 if (ConstantInt *CI = dyn_cast<ConstantInt>(Splat))
1438 if (CI->equalsInt(1))
1439 return ReplaceInstUsesWith(I, Op0);
1440 }
1441 }
Chris Lattnera2881962003-02-18 19:28:33 +00001442 }
Chris Lattnerab51f3f2006-03-04 06:04:02 +00001443
1444 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
1445 if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
Chris Lattnera2498472009-10-11 21:36:10 +00001446 isa<ConstantInt>(Op0I->getOperand(1)) && isa<ConstantInt>(Op1C)) {
Chris Lattnerab51f3f2006-03-04 06:04:02 +00001447 // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
Chris Lattnera2498472009-10-11 21:36:10 +00001448 Value *Add = Builder->CreateMul(Op0I->getOperand(0), Op1C, "tmp");
1449 Value *C1C2 = Builder->CreateMul(Op1C, Op0I->getOperand(1));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001450 return BinaryOperator::CreateAdd(Add, C1C2);
Chris Lattnerab51f3f2006-03-04 06:04:02 +00001451
1452 }
Chris Lattner2eefe512004-04-09 19:05:30 +00001453
1454 // Try to fold constant mul into select arguments.
1455 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00001456 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00001457 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00001458
1459 if (isa<PHINode>(Op0))
1460 if (Instruction *NV = FoldOpIntoPhi(I))
1461 return NV;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00001462 }
1463
Dan Gohman186a6362009-08-12 16:04:34 +00001464 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
Chris Lattnera2498472009-10-11 21:36:10 +00001465 if (Value *Op1v = dyn_castNegVal(Op1))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001466 return BinaryOperator::CreateMul(Op0v, Op1v);
Chris Lattnera4f445b2003-03-10 23:23:04 +00001467
Nick Lewycky0c730792008-11-21 07:33:58 +00001468 // (X / Y) * Y = X - (X % Y)
1469 // (X / Y) * -Y = (X % Y) - X
1470 {
Chris Lattnera2498472009-10-11 21:36:10 +00001471 Value *Op1C = Op1;
Nick Lewycky0c730792008-11-21 07:33:58 +00001472 BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0);
1473 if (!BO ||
1474 (BO->getOpcode() != Instruction::UDiv &&
1475 BO->getOpcode() != Instruction::SDiv)) {
Chris Lattnera2498472009-10-11 21:36:10 +00001476 Op1C = Op0;
1477 BO = dyn_cast<BinaryOperator>(Op1);
Nick Lewycky0c730792008-11-21 07:33:58 +00001478 }
Chris Lattnera2498472009-10-11 21:36:10 +00001479 Value *Neg = dyn_castNegVal(Op1C);
Nick Lewycky0c730792008-11-21 07:33:58 +00001480 if (BO && BO->hasOneUse() &&
Chris Lattnera2498472009-10-11 21:36:10 +00001481 (BO->getOperand(1) == Op1C || BO->getOperand(1) == Neg) &&
Nick Lewycky0c730792008-11-21 07:33:58 +00001482 (BO->getOpcode() == Instruction::UDiv ||
1483 BO->getOpcode() == Instruction::SDiv)) {
1484 Value *Op0BO = BO->getOperand(0), *Op1BO = BO->getOperand(1);
1485
Dan Gohmanfa94b942009-08-12 16:33:09 +00001486 // If the division is exact, X % Y is zero.
1487 if (SDivOperator *SDiv = dyn_cast<SDivOperator>(BO))
1488 if (SDiv->isExact()) {
Chris Lattnera2498472009-10-11 21:36:10 +00001489 if (Op1BO == Op1C)
Dan Gohmanfa94b942009-08-12 16:33:09 +00001490 return ReplaceInstUsesWith(I, Op0BO);
Chris Lattnera2498472009-10-11 21:36:10 +00001491 return BinaryOperator::CreateNeg(Op0BO);
Dan Gohmanfa94b942009-08-12 16:33:09 +00001492 }
1493
Chris Lattner74381062009-08-30 07:44:24 +00001494 Value *Rem;
Nick Lewycky0c730792008-11-21 07:33:58 +00001495 if (BO->getOpcode() == Instruction::UDiv)
Chris Lattner74381062009-08-30 07:44:24 +00001496 Rem = Builder->CreateURem(Op0BO, Op1BO);
Nick Lewycky0c730792008-11-21 07:33:58 +00001497 else
Chris Lattner74381062009-08-30 07:44:24 +00001498 Rem = Builder->CreateSRem(Op0BO, Op1BO);
Nick Lewycky0c730792008-11-21 07:33:58 +00001499 Rem->takeName(BO);
1500
Chris Lattnera2498472009-10-11 21:36:10 +00001501 if (Op1BO == Op1C)
Nick Lewycky0c730792008-11-21 07:33:58 +00001502 return BinaryOperator::CreateSub(Op0BO, Rem);
Chris Lattner74381062009-08-30 07:44:24 +00001503 return BinaryOperator::CreateSub(Rem, Op0BO);
Nick Lewycky0c730792008-11-21 07:33:58 +00001504 }
1505 }
1506
Chris Lattner8af304a2009-10-11 07:53:15 +00001507 /// i1 mul -> i1 and.
Chris Lattner4de84762010-01-04 07:02:48 +00001508 if (I.getType() == Type::getInt1Ty(I.getContext()))
Chris Lattnera2498472009-10-11 21:36:10 +00001509 return BinaryOperator::CreateAnd(Op0, Op1);
Nick Lewycky9419ddb2008-05-31 17:59:52 +00001510
Chris Lattner8af304a2009-10-11 07:53:15 +00001511 // X*(1 << Y) --> X << Y
1512 // (1 << Y)*X --> X << Y
1513 {
1514 Value *Y;
1515 if (match(Op0, m_Shl(m_One(), m_Value(Y))))
Chris Lattnera2498472009-10-11 21:36:10 +00001516 return BinaryOperator::CreateShl(Op1, Y);
1517 if (match(Op1, m_Shl(m_One(), m_Value(Y))))
Chris Lattner8af304a2009-10-11 07:53:15 +00001518 return BinaryOperator::CreateShl(Op0, Y);
1519 }
1520
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00001521 // If one of the operands of the multiply is a cast from a boolean value, then
1522 // we know the bool is either zero or one, so this is a 'masking' multiply.
Chris Lattnerd2c58362009-10-11 21:29:45 +00001523 // X * Y (where Y is 0 or 1) -> X & (0-Y)
1524 if (!isa<VectorType>(I.getType())) {
1525 // -2 is "-1 << 1" so it is all bits set except the low one.
Dale Johannesenc1deda52009-10-12 18:45:32 +00001526 APInt Negative2(I.getType()->getPrimitiveSizeInBits(), (uint64_t)-2, true);
Chris Lattner0036e3a2009-10-11 21:22:21 +00001527
Chris Lattnerd2c58362009-10-11 21:29:45 +00001528 Value *BoolCast = 0, *OtherOp = 0;
1529 if (MaskedValueIsZero(Op0, Negative2))
Chris Lattnera2498472009-10-11 21:36:10 +00001530 BoolCast = Op0, OtherOp = Op1;
1531 else if (MaskedValueIsZero(Op1, Negative2))
1532 BoolCast = Op1, OtherOp = Op0;
Chris Lattnerd2c58362009-10-11 21:29:45 +00001533
Chris Lattner0036e3a2009-10-11 21:22:21 +00001534 if (BoolCast) {
Chris Lattner0036e3a2009-10-11 21:22:21 +00001535 Value *V = Builder->CreateSub(Constant::getNullValue(I.getType()),
1536 BoolCast, "tmp");
1537 return BinaryOperator::CreateAnd(V, OtherOp);
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00001538 }
1539 }
1540
Chris Lattner7e708292002-06-25 16:13:24 +00001541 return Changed ? &I : 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00001542}
1543
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001544Instruction *InstCombiner::visitFMul(BinaryOperator &I) {
1545 bool Changed = SimplifyCommutative(I);
Chris Lattnera2498472009-10-11 21:36:10 +00001546 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001547
1548 // Simplify mul instructions with a constant RHS...
Chris Lattnera2498472009-10-11 21:36:10 +00001549 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
1550 if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1C)) {
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001551 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
1552 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
1553 if (Op1F->isExactlyValue(1.0))
1554 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0'
Chris Lattnera2498472009-10-11 21:36:10 +00001555 } else if (isa<VectorType>(Op1C->getType())) {
1556 if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1C)) {
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001557 // As above, vector X*splat(1.0) -> X in all defined cases.
1558 if (Constant *Splat = Op1V->getSplatValue()) {
1559 if (ConstantFP *F = dyn_cast<ConstantFP>(Splat))
1560 if (F->isExactlyValue(1.0))
1561 return ReplaceInstUsesWith(I, Op0);
1562 }
1563 }
1564 }
1565
1566 // Try to fold constant mul into select arguments.
1567 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
1568 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
1569 return R;
1570
1571 if (isa<PHINode>(Op0))
1572 if (Instruction *NV = FoldOpIntoPhi(I))
1573 return NV;
1574 }
1575
Dan Gohman186a6362009-08-12 16:04:34 +00001576 if (Value *Op0v = dyn_castFNegVal(Op0)) // -X * -Y = X*Y
Chris Lattnera2498472009-10-11 21:36:10 +00001577 if (Value *Op1v = dyn_castFNegVal(Op1))
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001578 return BinaryOperator::CreateFMul(Op0v, Op1v);
1579
1580 return Changed ? &I : 0;
1581}
1582
Chris Lattnerfdb19e52008-07-14 00:15:52 +00001583/// SimplifyDivRemOfSelect - Try to fold a divide or remainder of a select
1584/// instruction.
1585bool InstCombiner::SimplifyDivRemOfSelect(BinaryOperator &I) {
1586 SelectInst *SI = cast<SelectInst>(I.getOperand(1));
1587
1588 // div/rem X, (Cond ? 0 : Y) -> div/rem X, Y
1589 int NonNullOperand = -1;
1590 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
1591 if (ST->isNullValue())
1592 NonNullOperand = 2;
1593 // div/rem X, (Cond ? Y : 0) -> div/rem X, Y
1594 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
1595 if (ST->isNullValue())
1596 NonNullOperand = 1;
1597
1598 if (NonNullOperand == -1)
1599 return false;
1600
1601 Value *SelectCond = SI->getOperand(0);
1602
1603 // Change the div/rem to use 'Y' instead of the select.
1604 I.setOperand(1, SI->getOperand(NonNullOperand));
1605
1606 // Okay, we know we replace the operand of the div/rem with 'Y' with no
1607 // problem. However, the select, or the condition of the select may have
1608 // multiple uses. Based on our knowledge that the operand must be non-zero,
1609 // propagate the known value for the select into other uses of it, and
1610 // propagate a known value of the condition into its other users.
1611
1612 // If the select and condition only have a single use, don't bother with this,
1613 // early exit.
1614 if (SI->use_empty() && SelectCond->hasOneUse())
1615 return true;
1616
1617 // Scan the current block backward, looking for other uses of SI.
1618 BasicBlock::iterator BBI = &I, BBFront = I.getParent()->begin();
1619
1620 while (BBI != BBFront) {
1621 --BBI;
1622 // If we found a call to a function, we can't assume it will return, so
1623 // information from below it cannot be propagated above it.
1624 if (isa<CallInst>(BBI) && !isa<IntrinsicInst>(BBI))
1625 break;
1626
1627 // Replace uses of the select or its condition with the known values.
1628 for (Instruction::op_iterator I = BBI->op_begin(), E = BBI->op_end();
1629 I != E; ++I) {
1630 if (*I == SI) {
1631 *I = SI->getOperand(NonNullOperand);
Chris Lattner7a1e9242009-08-30 06:13:40 +00001632 Worklist.Add(BBI);
Chris Lattnerfdb19e52008-07-14 00:15:52 +00001633 } else if (*I == SelectCond) {
Chris Lattner4de84762010-01-04 07:02:48 +00001634 *I = NonNullOperand == 1 ? ConstantInt::getTrue(BBI->getContext()) :
1635 ConstantInt::getFalse(BBI->getContext());
Chris Lattner7a1e9242009-08-30 06:13:40 +00001636 Worklist.Add(BBI);
Chris Lattnerfdb19e52008-07-14 00:15:52 +00001637 }
1638 }
1639
1640 // If we past the instruction, quit looking for it.
1641 if (&*BBI == SI)
1642 SI = 0;
1643 if (&*BBI == SelectCond)
1644 SelectCond = 0;
1645
1646 // If we ran out of things to eliminate, break out of the loop.
1647 if (SelectCond == 0 && SI == 0)
1648 break;
1649
1650 }
1651 return true;
1652}
1653
1654
Reid Spencer1628cec2006-10-26 06:15:43 +00001655/// This function implements the transforms on div instructions that work
1656/// regardless of the kind of div instruction it is (udiv, sdiv, or fdiv). It is
1657/// used by the visitors to those instructions.
1658/// @brief Transforms common to all three div instructions
Reid Spencer3da59db2006-11-27 01:05:10 +00001659Instruction *InstCombiner::commonDivTransforms(BinaryOperator &I) {
Chris Lattner857e8cd2004-12-12 21:48:58 +00001660 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnere87597f2004-10-16 18:11:37 +00001661
Chris Lattner50b2ca42008-02-19 06:12:18 +00001662 // undef / X -> 0 for integer.
1663 // undef / X -> undef for FP (the undef could be a snan).
1664 if (isa<UndefValue>(Op0)) {
1665 if (Op0->getType()->isFPOrFPVector())
1666 return ReplaceInstUsesWith(I, Op0);
Owen Andersona7235ea2009-07-31 20:28:14 +00001667 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner50b2ca42008-02-19 06:12:18 +00001668 }
Reid Spencer1628cec2006-10-26 06:15:43 +00001669
1670 // X / undef -> undef
Chris Lattner857e8cd2004-12-12 21:48:58 +00001671 if (isa<UndefValue>(Op1))
Reid Spencer1628cec2006-10-26 06:15:43 +00001672 return ReplaceInstUsesWith(I, Op1);
Chris Lattner857e8cd2004-12-12 21:48:58 +00001673
Reid Spencer1628cec2006-10-26 06:15:43 +00001674 return 0;
1675}
Misha Brukmanfd939082005-04-21 23:48:37 +00001676
Reid Spencer1628cec2006-10-26 06:15:43 +00001677/// This function implements the transforms common to both integer division
1678/// instructions (udiv and sdiv). It is called by the visitors to those integer
1679/// division instructions.
1680/// @brief Common integer divide transforms
Reid Spencer3da59db2006-11-27 01:05:10 +00001681Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
Reid Spencer1628cec2006-10-26 06:15:43 +00001682 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1683
Chris Lattnerb2ae9e32008-05-16 02:59:42 +00001684 // (sdiv X, X) --> 1 (udiv X, X) --> 1
Nick Lewycky39ac3b52008-05-23 03:26:47 +00001685 if (Op0 == Op1) {
1686 if (const VectorType *Ty = dyn_cast<VectorType>(I.getType())) {
Owen Andersoneed707b2009-07-24 23:12:02 +00001687 Constant *CI = ConstantInt::get(Ty->getElementType(), 1);
Nick Lewycky39ac3b52008-05-23 03:26:47 +00001688 std::vector<Constant*> Elts(Ty->getNumElements(), CI);
Owen Andersonaf7ec972009-07-28 21:19:26 +00001689 return ReplaceInstUsesWith(I, ConstantVector::get(Elts));
Nick Lewycky39ac3b52008-05-23 03:26:47 +00001690 }
1691
Owen Andersoneed707b2009-07-24 23:12:02 +00001692 Constant *CI = ConstantInt::get(I.getType(), 1);
Nick Lewycky39ac3b52008-05-23 03:26:47 +00001693 return ReplaceInstUsesWith(I, CI);
1694 }
Chris Lattnerb2ae9e32008-05-16 02:59:42 +00001695
Reid Spencer1628cec2006-10-26 06:15:43 +00001696 if (Instruction *Common = commonDivTransforms(I))
1697 return Common;
Chris Lattnerfdb19e52008-07-14 00:15:52 +00001698
1699 // Handle cases involving: [su]div X, (select Cond, Y, Z)
1700 // This does not apply for fdiv.
1701 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
1702 return &I;
Reid Spencer1628cec2006-10-26 06:15:43 +00001703
1704 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
1705 // div X, 1 == X
1706 if (RHS->equalsInt(1))
1707 return ReplaceInstUsesWith(I, Op0);
1708
1709 // (X / C1) / C2 -> X / (C1*C2)
1710 if (Instruction *LHS = dyn_cast<Instruction>(Op0))
1711 if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
1712 if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
Owen Andersond672ecb2009-07-03 00:17:18 +00001713 if (MultiplyOverflows(RHS, LHSRHS,
Dan Gohman186a6362009-08-12 16:04:34 +00001714 I.getOpcode()==Instruction::SDiv))
Owen Andersona7235ea2009-07-31 20:28:14 +00001715 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Nick Lewyckye0cfecf2008-02-18 22:48:05 +00001716 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001717 return BinaryOperator::Create(I.getOpcode(), LHS->getOperand(0),
Owen Andersonbaf3c402009-07-29 18:55:55 +00001718 ConstantExpr::getMul(RHS, LHSRHS));
Chris Lattnerbf70b832005-04-08 04:03:26 +00001719 }
Reid Spencer1628cec2006-10-26 06:15:43 +00001720
Reid Spencerbca0e382007-03-23 20:05:17 +00001721 if (!RHS->isZero()) { // avoid X udiv 0
Reid Spencer1628cec2006-10-26 06:15:43 +00001722 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
1723 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
1724 return R;
1725 if (isa<PHINode>(Op0))
1726 if (Instruction *NV = FoldOpIntoPhi(I))
1727 return NV;
1728 }
Chris Lattner8e49e082006-09-09 20:26:32 +00001729 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001730
Chris Lattnera2881962003-02-18 19:28:33 +00001731 // 0 / X == 0, we don't need to preserve faults!
Chris Lattner857e8cd2004-12-12 21:48:58 +00001732 if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
Chris Lattnera2881962003-02-18 19:28:33 +00001733 if (LHS->equalsInt(0))
Owen Andersona7235ea2009-07-31 20:28:14 +00001734 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00001735
Nick Lewycky9419ddb2008-05-31 17:59:52 +00001736 // It can't be division by zero, hence it must be division by one.
Chris Lattner4de84762010-01-04 07:02:48 +00001737 if (I.getType() == Type::getInt1Ty(I.getContext()))
Nick Lewycky9419ddb2008-05-31 17:59:52 +00001738 return ReplaceInstUsesWith(I, Op0);
1739
Nick Lewycky895f0852008-11-27 20:21:08 +00001740 if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
1741 if (ConstantInt *X = cast_or_null<ConstantInt>(Op1V->getSplatValue()))
1742 // div X, 1 == X
1743 if (X->isOne())
1744 return ReplaceInstUsesWith(I, Op0);
1745 }
1746
Reid Spencer1628cec2006-10-26 06:15:43 +00001747 return 0;
1748}
1749
1750Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
1751 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1752
1753 // Handle the integer div common cases
1754 if (Instruction *Common = commonIDivTransforms(I))
1755 return Common;
1756
Reid Spencer1628cec2006-10-26 06:15:43 +00001757 if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
Nick Lewycky8ca52482008-11-27 22:41:10 +00001758 // X udiv C^2 -> X >> C
1759 // Check to see if this is an unsigned division with an exact power of 2,
1760 // if so, convert to a right shift.
Reid Spencer6eb0d992007-03-26 23:58:26 +00001761 if (C->getValue().isPowerOf2()) // 0 not included in isPowerOf2
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001762 return BinaryOperator::CreateLShr(Op0,
Owen Andersoneed707b2009-07-24 23:12:02 +00001763 ConstantInt::get(Op0->getType(), C->getValue().logBase2()));
Nick Lewycky8ca52482008-11-27 22:41:10 +00001764
1765 // X udiv C, where C >= signbit
1766 if (C->getValue().isNegative()) {
Chris Lattner74381062009-08-30 07:44:24 +00001767 Value *IC = Builder->CreateICmpULT( Op0, C);
Owen Andersona7235ea2009-07-31 20:28:14 +00001768 return SelectInst::Create(IC, Constant::getNullValue(I.getType()),
Owen Andersoneed707b2009-07-24 23:12:02 +00001769 ConstantInt::get(I.getType(), 1));
Nick Lewycky8ca52482008-11-27 22:41:10 +00001770 }
Reid Spencer1628cec2006-10-26 06:15:43 +00001771 }
1772
1773 // X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2)
Reid Spencer832254e2007-02-02 02:16:23 +00001774 if (BinaryOperator *RHSI = dyn_cast<BinaryOperator>(I.getOperand(1))) {
Reid Spencer1628cec2006-10-26 06:15:43 +00001775 if (RHSI->getOpcode() == Instruction::Shl &&
1776 isa<ConstantInt>(RHSI->getOperand(0))) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00001777 const APInt& C1 = cast<ConstantInt>(RHSI->getOperand(0))->getValue();
Reid Spencerbca0e382007-03-23 20:05:17 +00001778 if (C1.isPowerOf2()) {
Reid Spencer1628cec2006-10-26 06:15:43 +00001779 Value *N = RHSI->getOperand(1);
Reid Spencer3da59db2006-11-27 01:05:10 +00001780 const Type *NTy = N->getType();
Chris Lattner74381062009-08-30 07:44:24 +00001781 if (uint32_t C2 = C1.logBase2())
1782 N = Builder->CreateAdd(N, ConstantInt::get(NTy, C2), "tmp");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001783 return BinaryOperator::CreateLShr(Op0, N);
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00001784 }
1785 }
Chris Lattnerc812e5d2005-11-05 07:40:31 +00001786 }
1787
Reid Spencer1628cec2006-10-26 06:15:43 +00001788 // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
1789 // where C1&C2 are powers of two.
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00001790 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Reid Spencer1628cec2006-10-26 06:15:43 +00001791 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00001792 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00001793 const APInt &TVA = STO->getValue(), &FVA = SFO->getValue();
Reid Spencerbca0e382007-03-23 20:05:17 +00001794 if (TVA.isPowerOf2() && FVA.isPowerOf2()) {
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00001795 // Compute the shift amounts
Reid Spencerbca0e382007-03-23 20:05:17 +00001796 uint32_t TSA = TVA.logBase2(), FSA = FVA.logBase2();
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00001797 // Construct the "on true" case of the select
Owen Andersoneed707b2009-07-24 23:12:02 +00001798 Constant *TC = ConstantInt::get(Op0->getType(), TSA);
Chris Lattner74381062009-08-30 07:44:24 +00001799 Value *TSI = Builder->CreateLShr(Op0, TC, SI->getName()+".t");
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00001800
1801 // Construct the "on false" case of the select
Owen Andersoneed707b2009-07-24 23:12:02 +00001802 Constant *FC = ConstantInt::get(Op0->getType(), FSA);
Chris Lattner74381062009-08-30 07:44:24 +00001803 Value *FSI = Builder->CreateLShr(Op0, FC, SI->getName()+".f");
Reid Spencer1628cec2006-10-26 06:15:43 +00001804
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00001805 // construct the select instruction and return it.
Gabor Greif051a9502008-04-06 20:25:17 +00001806 return SelectInst::Create(SI->getOperand(0), TSI, FSI, SI->getName());
Reid Spencer1628cec2006-10-26 06:15:43 +00001807 }
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00001808 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00001809 return 0;
1810}
1811
Reid Spencer1628cec2006-10-26 06:15:43 +00001812Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
1813 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1814
1815 // Handle the integer div common cases
1816 if (Instruction *Common = commonIDivTransforms(I))
1817 return Common;
1818
1819 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
1820 // sdiv X, -1 == -X
1821 if (RHS->isAllOnesValue())
Dan Gohman4ae51262009-08-12 16:23:25 +00001822 return BinaryOperator::CreateNeg(Op0);
Dan Gohman1bdf5dc2009-08-11 20:47:47 +00001823
Dan Gohmanfa94b942009-08-12 16:33:09 +00001824 // sdiv X, C --> ashr X, log2(C)
Dan Gohman1bdf5dc2009-08-11 20:47:47 +00001825 if (cast<SDivOperator>(&I)->isExact() &&
1826 RHS->getValue().isNonNegative() &&
1827 RHS->getValue().isPowerOf2()) {
1828 Value *ShAmt = llvm::ConstantInt::get(RHS->getType(),
1829 RHS->getValue().exactLogBase2());
1830 return BinaryOperator::CreateAShr(Op0, ShAmt, I.getName());
1831 }
Dan Gohman9ca9daa2009-08-12 16:37:02 +00001832
1833 // -X/C --> X/-C provided the negation doesn't overflow.
1834 if (SubOperator *Sub = dyn_cast<SubOperator>(Op0))
1835 if (isa<Constant>(Sub->getOperand(0)) &&
1836 cast<Constant>(Sub->getOperand(0))->isNullValue() &&
Dan Gohman5078f842009-08-20 17:11:38 +00001837 Sub->hasNoSignedWrap())
Dan Gohman9ca9daa2009-08-12 16:37:02 +00001838 return BinaryOperator::CreateSDiv(Sub->getOperand(1),
1839 ConstantExpr::getNeg(RHS));
Reid Spencer1628cec2006-10-26 06:15:43 +00001840 }
1841
1842 // If the sign bits of both operands are zero (i.e. we can prove they are
1843 // unsigned inputs), turn this into a udiv.
Chris Lattner42a75512007-01-15 02:27:26 +00001844 if (I.getType()->isInteger()) {
Reid Spencerbca0e382007-03-23 20:05:17 +00001845 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
Eli Friedman8be17392009-07-18 09:53:21 +00001846 if (MaskedValueIsZero(Op0, Mask)) {
1847 if (MaskedValueIsZero(Op1, Mask)) {
1848 // X sdiv Y -> X udiv Y, iff X and Y don't have sign bit set
1849 return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
1850 }
1851 ConstantInt *ShiftedInt;
Dan Gohman4ae51262009-08-12 16:23:25 +00001852 if (match(Op1, m_Shl(m_ConstantInt(ShiftedInt), m_Value())) &&
Eli Friedman8be17392009-07-18 09:53:21 +00001853 ShiftedInt->getValue().isPowerOf2()) {
1854 // X sdiv (1 << Y) -> X udiv (1 << Y) ( -> X u>> Y)
1855 // Safe because the only negative value (1 << Y) can take on is
1856 // INT_MIN, and X sdiv INT_MIN == X udiv INT_MIN == 0 if X doesn't have
1857 // the sign bit set.
1858 return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
1859 }
Reid Spencer1628cec2006-10-26 06:15:43 +00001860 }
Eli Friedman8be17392009-07-18 09:53:21 +00001861 }
Reid Spencer1628cec2006-10-26 06:15:43 +00001862
1863 return 0;
1864}
1865
1866Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
1867 return commonDivTransforms(I);
1868}
Chris Lattner3f5b8772002-05-06 16:14:14 +00001869
Reid Spencer0a783f72006-11-02 01:53:59 +00001870/// This function implements the transforms on rem instructions that work
1871/// regardless of the kind of rem instruction it is (urem, srem, or frem). It
1872/// is used by the visitors to those instructions.
1873/// @brief Transforms common to all three rem instructions
1874Instruction *InstCombiner::commonRemTransforms(BinaryOperator &I) {
Chris Lattner857e8cd2004-12-12 21:48:58 +00001875 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Reid Spencer0a783f72006-11-02 01:53:59 +00001876
Chris Lattner50b2ca42008-02-19 06:12:18 +00001877 if (isa<UndefValue>(Op0)) { // undef % X -> 0
1878 if (I.getType()->isFPOrFPVector())
1879 return ReplaceInstUsesWith(I, Op0); // X % undef -> undef (could be SNaN)
Owen Andersona7235ea2009-07-31 20:28:14 +00001880 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner50b2ca42008-02-19 06:12:18 +00001881 }
Chris Lattner19ccd5c2006-02-28 05:30:45 +00001882 if (isa<UndefValue>(Op1))
1883 return ReplaceInstUsesWith(I, Op1); // X % undef -> undef
Reid Spencer0a783f72006-11-02 01:53:59 +00001884
1885 // Handle cases involving: rem X, (select Cond, Y, Z)
Chris Lattnerfdb19e52008-07-14 00:15:52 +00001886 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
1887 return &I;
Chris Lattner5b73c082004-07-06 07:01:22 +00001888
Reid Spencer0a783f72006-11-02 01:53:59 +00001889 return 0;
1890}
1891
1892/// This function implements the transforms common to both integer remainder
1893/// instructions (urem and srem). It is called by the visitors to those integer
1894/// remainder instructions.
1895/// @brief Common integer remainder transforms
1896Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
1897 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1898
1899 if (Instruction *common = commonRemTransforms(I))
1900 return common;
1901
Dale Johannesened6af242009-01-21 00:35:19 +00001902 // 0 % X == 0 for integer, we don't need to preserve faults!
1903 if (Constant *LHS = dyn_cast<Constant>(Op0))
1904 if (LHS->isNullValue())
Owen Andersona7235ea2009-07-31 20:28:14 +00001905 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Dale Johannesened6af242009-01-21 00:35:19 +00001906
Chris Lattner857e8cd2004-12-12 21:48:58 +00001907 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner19ccd5c2006-02-28 05:30:45 +00001908 // X % 0 == undef, we don't need to preserve faults!
1909 if (RHS->equalsInt(0))
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001910 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
Chris Lattner19ccd5c2006-02-28 05:30:45 +00001911
Chris Lattnera2881962003-02-18 19:28:33 +00001912 if (RHS->equalsInt(1)) // X % 1 == 0
Owen Andersona7235ea2009-07-31 20:28:14 +00001913 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00001914
Chris Lattner97943922006-02-28 05:49:21 +00001915 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
1916 if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
1917 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
1918 return R;
1919 } else if (isa<PHINode>(Op0I)) {
1920 if (Instruction *NV = FoldOpIntoPhi(I))
1921 return NV;
Chris Lattner97943922006-02-28 05:49:21 +00001922 }
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001923
1924 // See if we can fold away this rem instruction.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001925 if (SimplifyDemandedInstructionBits(I))
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001926 return &I;
Chris Lattner97943922006-02-28 05:49:21 +00001927 }
Chris Lattnera2881962003-02-18 19:28:33 +00001928 }
1929
Reid Spencer0a783f72006-11-02 01:53:59 +00001930 return 0;
1931}
1932
1933Instruction *InstCombiner::visitURem(BinaryOperator &I) {
1934 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1935
1936 if (Instruction *common = commonIRemTransforms(I))
1937 return common;
1938
1939 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
1940 // X urem C^2 -> X and C
1941 // Check to see if this is an unsigned remainder with an exact power of 2,
1942 // if so, convert to a bitwise and.
1943 if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
Reid Spencerbca0e382007-03-23 20:05:17 +00001944 if (C->getValue().isPowerOf2())
Dan Gohman186a6362009-08-12 16:04:34 +00001945 return BinaryOperator::CreateAnd(Op0, SubOne(C));
Reid Spencer0a783f72006-11-02 01:53:59 +00001946 }
1947
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00001948 if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
Reid Spencer0a783f72006-11-02 01:53:59 +00001949 // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)
1950 if (RHSI->getOpcode() == Instruction::Shl &&
1951 isa<ConstantInt>(RHSI->getOperand(0))) {
Zhou Sheng0fc50952007-03-25 05:01:29 +00001952 if (cast<ConstantInt>(RHSI->getOperand(0))->getValue().isPowerOf2()) {
Owen Andersona7235ea2009-07-31 20:28:14 +00001953 Constant *N1 = Constant::getAllOnesValue(I.getType());
Chris Lattner74381062009-08-30 07:44:24 +00001954 Value *Add = Builder->CreateAdd(RHSI, N1, "tmp");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001955 return BinaryOperator::CreateAnd(Op0, Add);
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00001956 }
1957 }
Reid Spencer0a783f72006-11-02 01:53:59 +00001958 }
Chris Lattner8e49e082006-09-09 20:26:32 +00001959
Reid Spencer0a783f72006-11-02 01:53:59 +00001960 // urem X, (select Cond, 2^C1, 2^C2) --> select Cond, (and X, C1), (and X, C2)
1961 // where C1&C2 are powers of two.
1962 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
1963 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
1964 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
1965 // STO == 0 and SFO == 0 handled above.
Reid Spencerbca0e382007-03-23 20:05:17 +00001966 if ((STO->getValue().isPowerOf2()) &&
1967 (SFO->getValue().isPowerOf2())) {
Chris Lattner74381062009-08-30 07:44:24 +00001968 Value *TrueAnd = Builder->CreateAnd(Op0, SubOne(STO),
1969 SI->getName()+".t");
1970 Value *FalseAnd = Builder->CreateAnd(Op0, SubOne(SFO),
1971 SI->getName()+".f");
Gabor Greif051a9502008-04-06 20:25:17 +00001972 return SelectInst::Create(SI->getOperand(0), TrueAnd, FalseAnd);
Reid Spencer0a783f72006-11-02 01:53:59 +00001973 }
1974 }
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00001975 }
1976
Chris Lattner3f5b8772002-05-06 16:14:14 +00001977 return 0;
1978}
1979
Reid Spencer0a783f72006-11-02 01:53:59 +00001980Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
1981 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1982
Dan Gohmancff55092007-11-05 23:16:33 +00001983 // Handle the integer rem common cases
Chris Lattnere5ecdb52009-08-30 06:22:51 +00001984 if (Instruction *Common = commonIRemTransforms(I))
1985 return Common;
Reid Spencer0a783f72006-11-02 01:53:59 +00001986
Dan Gohman186a6362009-08-12 16:04:34 +00001987 if (Value *RHSNeg = dyn_castNegVal(Op1))
Nick Lewycky23c04302008-09-03 06:24:21 +00001988 if (!isa<Constant>(RHSNeg) ||
1989 (isa<ConstantInt>(RHSNeg) &&
1990 cast<ConstantInt>(RHSNeg)->getValue().isStrictlyPositive())) {
Reid Spencer0a783f72006-11-02 01:53:59 +00001991 // X % -Y -> X % Y
Chris Lattner3c4e38e2009-08-30 06:27:41 +00001992 Worklist.AddValue(I.getOperand(1));
Reid Spencer0a783f72006-11-02 01:53:59 +00001993 I.setOperand(1, RHSNeg);
1994 return &I;
1995 }
Nick Lewyckya06cf822008-09-30 06:08:34 +00001996
Dan Gohmancff55092007-11-05 23:16:33 +00001997 // If the sign bits of both operands are zero (i.e. we can prove they are
Reid Spencer0a783f72006-11-02 01:53:59 +00001998 // unsigned inputs), turn this into a urem.
Dan Gohmancff55092007-11-05 23:16:33 +00001999 if (I.getType()->isInteger()) {
2000 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
2001 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
2002 // X srem Y -> X urem Y, iff X and Y don't have sign bit set
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002003 return BinaryOperator::CreateURem(Op0, Op1, I.getName());
Dan Gohmancff55092007-11-05 23:16:33 +00002004 }
Reid Spencer0a783f72006-11-02 01:53:59 +00002005 }
2006
Nick Lewycky2a8f6592008-12-18 06:31:11 +00002007 // If it's a constant vector, flip any negative values positive.
Nick Lewycky9dce8732008-12-20 16:48:00 +00002008 if (ConstantVector *RHSV = dyn_cast<ConstantVector>(Op1)) {
2009 unsigned VWidth = RHSV->getNumOperands();
Nick Lewycky2a8f6592008-12-18 06:31:11 +00002010
Nick Lewycky9dce8732008-12-20 16:48:00 +00002011 bool hasNegative = false;
2012 for (unsigned i = 0; !hasNegative && i != VWidth; ++i)
2013 if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i)))
2014 if (RHS->getValue().isNegative())
2015 hasNegative = true;
2016
2017 if (hasNegative) {
2018 std::vector<Constant *> Elts(VWidth);
Nick Lewycky2a8f6592008-12-18 06:31:11 +00002019 for (unsigned i = 0; i != VWidth; ++i) {
2020 if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i))) {
2021 if (RHS->getValue().isNegative())
Owen Andersonbaf3c402009-07-29 18:55:55 +00002022 Elts[i] = cast<ConstantInt>(ConstantExpr::getNeg(RHS));
Nick Lewycky2a8f6592008-12-18 06:31:11 +00002023 else
2024 Elts[i] = RHS;
2025 }
2026 }
2027
Owen Andersonaf7ec972009-07-28 21:19:26 +00002028 Constant *NewRHSV = ConstantVector::get(Elts);
Nick Lewycky2a8f6592008-12-18 06:31:11 +00002029 if (NewRHSV != RHSV) {
Chris Lattner3c4e38e2009-08-30 06:27:41 +00002030 Worklist.AddValue(I.getOperand(1));
Nick Lewycky2a8f6592008-12-18 06:31:11 +00002031 I.setOperand(1, NewRHSV);
2032 return &I;
2033 }
2034 }
2035 }
2036
Reid Spencer0a783f72006-11-02 01:53:59 +00002037 return 0;
2038}
2039
2040Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
Reid Spencer0a783f72006-11-02 01:53:59 +00002041 return commonRemTransforms(I);
2042}
2043
Chris Lattner457dd822004-06-09 07:59:58 +00002044// isOneBitSet - Return true if there is exactly one bit set in the specified
2045// constant.
2046static bool isOneBitSet(const ConstantInt *CI) {
Reid Spencer5f6a8952007-03-20 00:16:52 +00002047 return CI->getValue().isPowerOf2();
Chris Lattner457dd822004-06-09 07:59:58 +00002048}
2049
Reid Spencere4d87aa2006-12-23 06:05:41 +00002050/// getICmpCode - Encode a icmp predicate into a three bit mask. These bits
Chris Lattneraa9c1f12003-08-13 20:16:26 +00002051/// are carefully arranged to allow folding of expressions such as:
2052///
2053/// (A < B) | (A > B) --> (A != B)
2054///
Reid Spencere4d87aa2006-12-23 06:05:41 +00002055/// Note that this is only valid if the first and second predicates have the
2056/// same sign. Is illegal to do: (A u< B) | (A s> B)
Chris Lattneraa9c1f12003-08-13 20:16:26 +00002057///
Reid Spencere4d87aa2006-12-23 06:05:41 +00002058/// Three bits are used to represent the condition, as follows:
2059/// 0 A > B
2060/// 1 A == B
2061/// 2 A < B
2062///
2063/// <=> Value Definition
2064/// 000 0 Always false
2065/// 001 1 A > B
2066/// 010 2 A == B
2067/// 011 3 A >= B
2068/// 100 4 A < B
2069/// 101 5 A != B
2070/// 110 6 A <= B
2071/// 111 7 Always true
2072///
2073static unsigned getICmpCode(const ICmpInst *ICI) {
2074 switch (ICI->getPredicate()) {
Chris Lattneraa9c1f12003-08-13 20:16:26 +00002075 // False -> 0
Reid Spencere4d87aa2006-12-23 06:05:41 +00002076 case ICmpInst::ICMP_UGT: return 1; // 001
2077 case ICmpInst::ICMP_SGT: return 1; // 001
2078 case ICmpInst::ICMP_EQ: return 2; // 010
2079 case ICmpInst::ICMP_UGE: return 3; // 011
2080 case ICmpInst::ICMP_SGE: return 3; // 011
2081 case ICmpInst::ICMP_ULT: return 4; // 100
2082 case ICmpInst::ICMP_SLT: return 4; // 100
2083 case ICmpInst::ICMP_NE: return 5; // 101
2084 case ICmpInst::ICMP_ULE: return 6; // 110
2085 case ICmpInst::ICMP_SLE: return 6; // 110
Chris Lattneraa9c1f12003-08-13 20:16:26 +00002086 // True -> 7
2087 default:
Torok Edwinc23197a2009-07-14 16:55:14 +00002088 llvm_unreachable("Invalid ICmp predicate!");
Chris Lattneraa9c1f12003-08-13 20:16:26 +00002089 return 0;
2090 }
2091}
2092
Evan Cheng8db90722008-10-14 17:15:11 +00002093/// getFCmpCode - Similar to getICmpCode but for FCmpInst. This encodes a fcmp
2094/// predicate into a three bit mask. It also returns whether it is an ordered
2095/// predicate by reference.
2096static unsigned getFCmpCode(FCmpInst::Predicate CC, bool &isOrdered) {
2097 isOrdered = false;
2098 switch (CC) {
2099 case FCmpInst::FCMP_ORD: isOrdered = true; return 0; // 000
2100 case FCmpInst::FCMP_UNO: return 0; // 000
Evan Cheng4990b252008-10-14 18:13:38 +00002101 case FCmpInst::FCMP_OGT: isOrdered = true; return 1; // 001
2102 case FCmpInst::FCMP_UGT: return 1; // 001
2103 case FCmpInst::FCMP_OEQ: isOrdered = true; return 2; // 010
2104 case FCmpInst::FCMP_UEQ: return 2; // 010
Evan Cheng8db90722008-10-14 17:15:11 +00002105 case FCmpInst::FCMP_OGE: isOrdered = true; return 3; // 011
2106 case FCmpInst::FCMP_UGE: return 3; // 011
2107 case FCmpInst::FCMP_OLT: isOrdered = true; return 4; // 100
2108 case FCmpInst::FCMP_ULT: return 4; // 100
Evan Cheng4990b252008-10-14 18:13:38 +00002109 case FCmpInst::FCMP_ONE: isOrdered = true; return 5; // 101
2110 case FCmpInst::FCMP_UNE: return 5; // 101
Evan Cheng8db90722008-10-14 17:15:11 +00002111 case FCmpInst::FCMP_OLE: isOrdered = true; return 6; // 110
2112 case FCmpInst::FCMP_ULE: return 6; // 110
Evan Cheng40300622008-10-14 18:44:08 +00002113 // True -> 7
Evan Cheng8db90722008-10-14 17:15:11 +00002114 default:
2115 // Not expecting FCMP_FALSE and FCMP_TRUE;
Torok Edwinc23197a2009-07-14 16:55:14 +00002116 llvm_unreachable("Unexpected FCmp predicate!");
Evan Cheng8db90722008-10-14 17:15:11 +00002117 return 0;
2118 }
2119}
2120
Reid Spencere4d87aa2006-12-23 06:05:41 +00002121/// getICmpValue - This is the complement of getICmpCode, which turns an
2122/// opcode and two operands into either a constant true or false, or a brand
Dan Gohman5d066ff2007-09-17 17:31:57 +00002123/// new ICmp instruction. The sign is passed in to determine which kind
Evan Cheng8db90722008-10-14 17:15:11 +00002124/// of predicate to use in the new icmp instruction.
Chris Lattner4de84762010-01-04 07:02:48 +00002125static Value *getICmpValue(bool sign, unsigned code, Value *LHS, Value *RHS) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00002126 switch (code) {
Torok Edwinc23197a2009-07-14 16:55:14 +00002127 default: llvm_unreachable("Illegal ICmp code!");
Chris Lattner4de84762010-01-04 07:02:48 +00002128 case 0: return ConstantInt::getFalse(LHS->getContext());
Reid Spencere4d87aa2006-12-23 06:05:41 +00002129 case 1:
2130 if (sign)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00002131 return new ICmpInst(ICmpInst::ICMP_SGT, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00002132 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00002133 return new ICmpInst(ICmpInst::ICMP_UGT, LHS, RHS);
2134 case 2: return new ICmpInst(ICmpInst::ICMP_EQ, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00002135 case 3:
2136 if (sign)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00002137 return new ICmpInst(ICmpInst::ICMP_SGE, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00002138 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00002139 return new ICmpInst(ICmpInst::ICMP_UGE, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00002140 case 4:
2141 if (sign)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00002142 return new ICmpInst(ICmpInst::ICMP_SLT, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00002143 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00002144 return new ICmpInst(ICmpInst::ICMP_ULT, LHS, RHS);
2145 case 5: return new ICmpInst(ICmpInst::ICMP_NE, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00002146 case 6:
2147 if (sign)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00002148 return new ICmpInst(ICmpInst::ICMP_SLE, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00002149 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00002150 return new ICmpInst(ICmpInst::ICMP_ULE, LHS, RHS);
Chris Lattner4de84762010-01-04 07:02:48 +00002151 case 7: return ConstantInt::getTrue(LHS->getContext());
Chris Lattneraa9c1f12003-08-13 20:16:26 +00002152 }
2153}
2154
Evan Cheng8db90722008-10-14 17:15:11 +00002155/// getFCmpValue - This is the complement of getFCmpCode, which turns an
2156/// opcode and two operands into either a FCmp instruction. isordered is passed
2157/// in to determine which kind of predicate to use in the new fcmp instruction.
2158static Value *getFCmpValue(bool isordered, unsigned code,
Chris Lattner4de84762010-01-04 07:02:48 +00002159 Value *LHS, Value *RHS) {
Evan Cheng8db90722008-10-14 17:15:11 +00002160 switch (code) {
Torok Edwinc23197a2009-07-14 16:55:14 +00002161 default: llvm_unreachable("Illegal FCmp code!");
Evan Cheng8db90722008-10-14 17:15:11 +00002162 case 0:
2163 if (isordered)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00002164 return new FCmpInst(FCmpInst::FCMP_ORD, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00002165 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00002166 return new FCmpInst(FCmpInst::FCMP_UNO, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00002167 case 1:
2168 if (isordered)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00002169 return new FCmpInst(FCmpInst::FCMP_OGT, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00002170 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00002171 return new FCmpInst(FCmpInst::FCMP_UGT, LHS, RHS);
Evan Cheng4990b252008-10-14 18:13:38 +00002172 case 2:
2173 if (isordered)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00002174 return new FCmpInst(FCmpInst::FCMP_OEQ, LHS, RHS);
Evan Cheng4990b252008-10-14 18:13:38 +00002175 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00002176 return new FCmpInst(FCmpInst::FCMP_UEQ, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00002177 case 3:
2178 if (isordered)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00002179 return new FCmpInst(FCmpInst::FCMP_OGE, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00002180 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00002181 return new FCmpInst(FCmpInst::FCMP_UGE, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00002182 case 4:
2183 if (isordered)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00002184 return new FCmpInst(FCmpInst::FCMP_OLT, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00002185 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00002186 return new FCmpInst(FCmpInst::FCMP_ULT, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00002187 case 5:
2188 if (isordered)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00002189 return new FCmpInst(FCmpInst::FCMP_ONE, LHS, RHS);
Evan Cheng4990b252008-10-14 18:13:38 +00002190 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00002191 return new FCmpInst(FCmpInst::FCMP_UNE, LHS, RHS);
Evan Cheng4990b252008-10-14 18:13:38 +00002192 case 6:
2193 if (isordered)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00002194 return new FCmpInst(FCmpInst::FCMP_OLE, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00002195 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00002196 return new FCmpInst(FCmpInst::FCMP_ULE, LHS, RHS);
Chris Lattner4de84762010-01-04 07:02:48 +00002197 case 7: return ConstantInt::getTrue(LHS->getContext());
Evan Cheng8db90722008-10-14 17:15:11 +00002198 }
2199}
2200
Chris Lattnerb9553d62008-11-16 04:55:20 +00002201/// PredicatesFoldable - Return true if both predicates match sign or if at
2202/// least one of them is an equality comparison (which is signless).
Reid Spencere4d87aa2006-12-23 06:05:41 +00002203static bool PredicatesFoldable(ICmpInst::Predicate p1, ICmpInst::Predicate p2) {
Nick Lewycky4a134af2009-10-25 05:20:17 +00002204 return (CmpInst::isSigned(p1) == CmpInst::isSigned(p2)) ||
2205 (CmpInst::isSigned(p1) && ICmpInst::isEquality(p2)) ||
2206 (CmpInst::isSigned(p2) && ICmpInst::isEquality(p1));
Reid Spencere4d87aa2006-12-23 06:05:41 +00002207}
2208
2209namespace {
2210// FoldICmpLogical - Implements (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
2211struct FoldICmpLogical {
Chris Lattneraa9c1f12003-08-13 20:16:26 +00002212 InstCombiner &IC;
2213 Value *LHS, *RHS;
Reid Spencere4d87aa2006-12-23 06:05:41 +00002214 ICmpInst::Predicate pred;
2215 FoldICmpLogical(InstCombiner &ic, ICmpInst *ICI)
2216 : IC(ic), LHS(ICI->getOperand(0)), RHS(ICI->getOperand(1)),
2217 pred(ICI->getPredicate()) {}
Chris Lattneraa9c1f12003-08-13 20:16:26 +00002218 bool shouldApply(Value *V) const {
Reid Spencere4d87aa2006-12-23 06:05:41 +00002219 if (ICmpInst *ICI = dyn_cast<ICmpInst>(V))
2220 if (PredicatesFoldable(pred, ICI->getPredicate()))
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00002221 return ((ICI->getOperand(0) == LHS && ICI->getOperand(1) == RHS) ||
2222 (ICI->getOperand(0) == RHS && ICI->getOperand(1) == LHS));
Chris Lattneraa9c1f12003-08-13 20:16:26 +00002223 return false;
2224 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00002225 Instruction *apply(Instruction &Log) const {
2226 ICmpInst *ICI = cast<ICmpInst>(Log.getOperand(0));
2227 if (ICI->getOperand(0) != LHS) {
2228 assert(ICI->getOperand(1) == LHS);
2229 ICI->swapOperands(); // Swap the LHS and RHS of the ICmp
Chris Lattneraa9c1f12003-08-13 20:16:26 +00002230 }
2231
Chris Lattnerbc1dbfc2007-03-13 14:27:42 +00002232 ICmpInst *RHSICI = cast<ICmpInst>(Log.getOperand(1));
Reid Spencere4d87aa2006-12-23 06:05:41 +00002233 unsigned LHSCode = getICmpCode(ICI);
Chris Lattnerbc1dbfc2007-03-13 14:27:42 +00002234 unsigned RHSCode = getICmpCode(RHSICI);
Chris Lattneraa9c1f12003-08-13 20:16:26 +00002235 unsigned Code;
2236 switch (Log.getOpcode()) {
2237 case Instruction::And: Code = LHSCode & RHSCode; break;
2238 case Instruction::Or: Code = LHSCode | RHSCode; break;
2239 case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
Torok Edwinc23197a2009-07-14 16:55:14 +00002240 default: llvm_unreachable("Illegal logical opcode!"); return 0;
Chris Lattneraa9c1f12003-08-13 20:16:26 +00002241 }
2242
Nick Lewycky4a134af2009-10-25 05:20:17 +00002243 bool isSigned = RHSICI->isSigned() || ICI->isSigned();
Chris Lattner4de84762010-01-04 07:02:48 +00002244 Value *RV = getICmpValue(isSigned, Code, LHS, RHS);
Chris Lattneraa9c1f12003-08-13 20:16:26 +00002245 if (Instruction *I = dyn_cast<Instruction>(RV))
2246 return I;
2247 // Otherwise, it's a constant boolean value...
2248 return IC.ReplaceInstUsesWith(Log, RV);
2249 }
2250};
Chris Lattnerd23b5ba2006-11-15 04:53:24 +00002251} // end anonymous namespace
Chris Lattneraa9c1f12003-08-13 20:16:26 +00002252
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00002253// OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
2254// the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
Reid Spencer832254e2007-02-02 02:16:23 +00002255// guaranteed to be a binary operator.
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00002256Instruction *InstCombiner::OptAndOp(Instruction *Op,
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002257 ConstantInt *OpRHS,
2258 ConstantInt *AndRHS,
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00002259 BinaryOperator &TheAnd) {
2260 Value *X = Op->getOperand(0);
Chris Lattner76f7fe22004-01-12 19:47:05 +00002261 Constant *Together = 0;
Reid Spencer832254e2007-02-02 02:16:23 +00002262 if (!Op->isShift())
Owen Andersonbaf3c402009-07-29 18:55:55 +00002263 Together = ConstantExpr::getAnd(AndRHS, OpRHS);
Chris Lattner7c4049c2004-01-12 19:35:11 +00002264
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00002265 switch (Op->getOpcode()) {
2266 case Instruction::Xor:
Chris Lattner6e7ba452005-01-01 16:22:27 +00002267 if (Op->hasOneUse()) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00002268 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
Chris Lattner74381062009-08-30 07:44:24 +00002269 Value *And = Builder->CreateAnd(X, AndRHS);
Chris Lattner6934a042007-02-11 01:23:03 +00002270 And->takeName(Op);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002271 return BinaryOperator::CreateXor(And, Together);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00002272 }
2273 break;
2274 case Instruction::Or:
Chris Lattner6e7ba452005-01-01 16:22:27 +00002275 if (Together == AndRHS) // (X | C) & C --> C
2276 return ReplaceInstUsesWith(TheAnd, AndRHS);
Misha Brukmanfd939082005-04-21 23:48:37 +00002277
Chris Lattner6e7ba452005-01-01 16:22:27 +00002278 if (Op->hasOneUse() && Together != OpRHS) {
2279 // (X | C1) & C2 --> (X | (C1&C2)) & C2
Chris Lattner74381062009-08-30 07:44:24 +00002280 Value *Or = Builder->CreateOr(X, Together);
Chris Lattner6934a042007-02-11 01:23:03 +00002281 Or->takeName(Op);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002282 return BinaryOperator::CreateAnd(Or, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00002283 }
2284 break;
2285 case Instruction::Add:
Chris Lattnerfd059242003-10-15 16:48:29 +00002286 if (Op->hasOneUse()) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00002287 // Adding a one to a single bit bit-field should be turned into an XOR
2288 // of the bit. First thing to check is to see if this AND is with a
2289 // single bit constant.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002290 const APInt& AndRHSV = cast<ConstantInt>(AndRHS)->getValue();
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00002291
2292 // If there is only one bit set...
Chris Lattner457dd822004-06-09 07:59:58 +00002293 if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00002294 // Ok, at this point, we know that we are masking the result of the
2295 // ADD down to exactly one bit. If the constant we are adding has
2296 // no bits set below this bit, then we can eliminate the ADD.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002297 const APInt& AddRHS = cast<ConstantInt>(OpRHS)->getValue();
Misha Brukmanfd939082005-04-21 23:48:37 +00002298
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00002299 // Check to see if any bits below the one bit set in AndRHSV are set.
2300 if ((AddRHS & (AndRHSV-1)) == 0) {
2301 // If not, the only thing that can effect the output of the AND is
2302 // the bit specified by AndRHSV. If that bit is set, the effect of
2303 // the XOR is to toggle the bit. If it is clear, then the ADD has
2304 // no effect.
2305 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
2306 TheAnd.setOperand(0, X);
2307 return &TheAnd;
2308 } else {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00002309 // Pull the XOR out of the AND.
Chris Lattner74381062009-08-30 07:44:24 +00002310 Value *NewAnd = Builder->CreateAnd(X, AndRHS);
Chris Lattner6934a042007-02-11 01:23:03 +00002311 NewAnd->takeName(Op);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002312 return BinaryOperator::CreateXor(NewAnd, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00002313 }
2314 }
2315 }
2316 }
2317 break;
Chris Lattner62a355c2003-09-19 19:05:02 +00002318
2319 case Instruction::Shl: {
2320 // We know that the AND will not produce any of the bits shifted in, so if
2321 // the anded constant includes them, clear them now!
2322 //
Zhou Sheng290bec52007-03-29 08:15:12 +00002323 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00002324 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +00002325 APInt ShlMask(APInt::getHighBitsSet(BitWidth, BitWidth-OpRHSVal));
Chris Lattner4de84762010-01-04 07:02:48 +00002326 ConstantInt *CI = ConstantInt::get(AndRHS->getContext(),
2327 AndRHS->getValue() & ShlMask);
Misha Brukmanfd939082005-04-21 23:48:37 +00002328
Zhou Sheng290bec52007-03-29 08:15:12 +00002329 if (CI->getValue() == ShlMask) {
2330 // Masking out bits that the shift already masks
Chris Lattner0c967662004-09-24 15:21:34 +00002331 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
2332 } else if (CI != AndRHS) { // Reducing bits set in and.
Chris Lattner62a355c2003-09-19 19:05:02 +00002333 TheAnd.setOperand(1, CI);
2334 return &TheAnd;
2335 }
2336 break;
Misha Brukmanfd939082005-04-21 23:48:37 +00002337 }
Chris Lattner4de84762010-01-04 07:02:48 +00002338 case Instruction::LShr: {
Chris Lattner62a355c2003-09-19 19:05:02 +00002339 // We know that the AND will not produce any of the bits shifted in, so if
2340 // the anded constant includes them, clear them now! This only applies to
2341 // unsigned shifts, because a signed shr may bring in set bits!
2342 //
Zhou Sheng290bec52007-03-29 08:15:12 +00002343 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00002344 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +00002345 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
Chris Lattner4de84762010-01-04 07:02:48 +00002346 ConstantInt *CI = ConstantInt::get(Op->getContext(),
2347 AndRHS->getValue() & ShrMask);
Chris Lattner0c967662004-09-24 15:21:34 +00002348
Zhou Sheng290bec52007-03-29 08:15:12 +00002349 if (CI->getValue() == ShrMask) {
2350 // Masking out bits that the shift already masks.
Reid Spencer3822ff52006-11-08 06:47:33 +00002351 return ReplaceInstUsesWith(TheAnd, Op);
2352 } else if (CI != AndRHS) {
2353 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
2354 return &TheAnd;
2355 }
2356 break;
2357 }
2358 case Instruction::AShr:
2359 // Signed shr.
2360 // See if this is shifting in some sign extension, then masking it out
2361 // with an and.
2362 if (Op->hasOneUse()) {
Zhou Sheng290bec52007-03-29 08:15:12 +00002363 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00002364 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +00002365 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
Chris Lattner4de84762010-01-04 07:02:48 +00002366 Constant *C = ConstantInt::get(Op->getContext(),
2367 AndRHS->getValue() & ShrMask);
Reid Spencer7eb76382006-12-13 17:19:09 +00002368 if (C == AndRHS) { // Masking out bits shifted in.
Reid Spencer17212df2006-12-12 09:18:51 +00002369 // (Val ashr C1) & C2 -> (Val lshr C1) & C2
Reid Spencer3822ff52006-11-08 06:47:33 +00002370 // Make the argument unsigned.
2371 Value *ShVal = Op->getOperand(0);
Chris Lattner74381062009-08-30 07:44:24 +00002372 ShVal = Builder->CreateLShr(ShVal, OpRHS, Op->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002373 return BinaryOperator::CreateAnd(ShVal, AndRHS, TheAnd.getName());
Chris Lattner0c967662004-09-24 15:21:34 +00002374 }
Chris Lattner62a355c2003-09-19 19:05:02 +00002375 }
2376 break;
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00002377 }
2378 return 0;
2379}
2380
Chris Lattner8b170942002-08-09 23:47:40 +00002381
Chris Lattnera96879a2004-09-29 17:40:11 +00002382/// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
2383/// true, otherwise (V < Lo || V >= Hi). In pratice, we emit the more efficient
Reid Spencere4d87aa2006-12-23 06:05:41 +00002384/// (V-Lo) <u Hi-Lo. This method expects that Lo <= Hi. isSigned indicates
2385/// whether to treat the V, Lo and HI as signed or not. IB is the location to
Chris Lattnera96879a2004-09-29 17:40:11 +00002386/// insert new instructions.
2387Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
Reid Spencere4d87aa2006-12-23 06:05:41 +00002388 bool isSigned, bool Inside,
2389 Instruction &IB) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00002390 assert(cast<ConstantInt>(ConstantExpr::getICmp((isSigned ?
Reid Spencer579dca12007-01-12 04:24:46 +00002391 ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
Chris Lattnera96879a2004-09-29 17:40:11 +00002392 "Lo is not <= Hi in range emission code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00002393
Chris Lattnera96879a2004-09-29 17:40:11 +00002394 if (Inside) {
2395 if (Lo == Hi) // Trivially false.
Dan Gohman1c8a23c2009-08-25 23:17:54 +00002396 return new ICmpInst(ICmpInst::ICMP_NE, V, V);
Misha Brukmanfd939082005-04-21 23:48:37 +00002397
Reid Spencere4d87aa2006-12-23 06:05:41 +00002398 // V >= Min && V < Hi --> V < Hi
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002399 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
Reid Spencere4e40032007-03-21 23:19:50 +00002400 ICmpInst::Predicate pred = (isSigned ?
Reid Spencere4d87aa2006-12-23 06:05:41 +00002401 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00002402 return new ICmpInst(pred, V, Hi);
Reid Spencere4d87aa2006-12-23 06:05:41 +00002403 }
2404
2405 // Emit V-Lo <u Hi-Lo
Owen Andersonbaf3c402009-07-29 18:55:55 +00002406 Constant *NegLo = ConstantExpr::getNeg(Lo);
Chris Lattner74381062009-08-30 07:44:24 +00002407 Value *Add = Builder->CreateAdd(V, NegLo, V->getName()+".off");
Owen Andersonbaf3c402009-07-29 18:55:55 +00002408 Constant *UpperBound = ConstantExpr::getAdd(NegLo, Hi);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00002409 return new ICmpInst(ICmpInst::ICMP_ULT, Add, UpperBound);
Chris Lattnera96879a2004-09-29 17:40:11 +00002410 }
2411
2412 if (Lo == Hi) // Trivially true.
Dan Gohman1c8a23c2009-08-25 23:17:54 +00002413 return new ICmpInst(ICmpInst::ICMP_EQ, V, V);
Chris Lattnera96879a2004-09-29 17:40:11 +00002414
Reid Spencere4e40032007-03-21 23:19:50 +00002415 // V < Min || V >= Hi -> V > Hi-1
Dan Gohman186a6362009-08-12 16:04:34 +00002416 Hi = SubOne(cast<ConstantInt>(Hi));
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002417 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00002418 ICmpInst::Predicate pred = (isSigned ?
2419 ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00002420 return new ICmpInst(pred, V, Hi);
Reid Spencere4d87aa2006-12-23 06:05:41 +00002421 }
Reid Spencerb83eb642006-10-20 07:07:24 +00002422
Reid Spencere4e40032007-03-21 23:19:50 +00002423 // Emit V-Lo >u Hi-1-Lo
2424 // Note that Hi has already had one subtracted from it, above.
Owen Andersonbaf3c402009-07-29 18:55:55 +00002425 ConstantInt *NegLo = cast<ConstantInt>(ConstantExpr::getNeg(Lo));
Chris Lattner74381062009-08-30 07:44:24 +00002426 Value *Add = Builder->CreateAdd(V, NegLo, V->getName()+".off");
Owen Andersonbaf3c402009-07-29 18:55:55 +00002427 Constant *LowerBound = ConstantExpr::getAdd(NegLo, Hi);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00002428 return new ICmpInst(ICmpInst::ICMP_UGT, Add, LowerBound);
Chris Lattnera96879a2004-09-29 17:40:11 +00002429}
2430
Chris Lattner7203e152005-09-18 07:22:02 +00002431// isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
2432// any number of 0s on either side. The 1s are allowed to wrap from LSB to
2433// MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs. 0x0F0F0000 is
2434// not, since all 1s are not contiguous.
Zhou Sheng4351c642007-04-02 08:20:41 +00002435static bool isRunOfOnes(ConstantInt *Val, uint32_t &MB, uint32_t &ME) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002436 const APInt& V = Val->getValue();
Reid Spencerf2442522007-03-24 00:42:08 +00002437 uint32_t BitWidth = Val->getType()->getBitWidth();
2438 if (!APIntOps::isShiftedMask(BitWidth, V)) return false;
Chris Lattner7203e152005-09-18 07:22:02 +00002439
2440 // look for the first zero bit after the run of ones
Reid Spencerf2442522007-03-24 00:42:08 +00002441 MB = BitWidth - ((V - 1) ^ V).countLeadingZeros();
Chris Lattner7203e152005-09-18 07:22:02 +00002442 // look for the first non-zero bit
Reid Spencerf2442522007-03-24 00:42:08 +00002443 ME = V.getActiveBits();
Chris Lattner7203e152005-09-18 07:22:02 +00002444 return true;
2445}
2446
Chris Lattner7203e152005-09-18 07:22:02 +00002447/// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
2448/// where isSub determines whether the operator is a sub. If we can fold one of
2449/// the following xforms:
Chris Lattnerc8e77562005-09-18 04:24:45 +00002450///
2451/// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
2452/// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
2453/// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
2454///
2455/// return (A +/- B).
2456///
2457Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002458 ConstantInt *Mask, bool isSub,
Chris Lattnerc8e77562005-09-18 04:24:45 +00002459 Instruction &I) {
2460 Instruction *LHSI = dyn_cast<Instruction>(LHS);
2461 if (!LHSI || LHSI->getNumOperands() != 2 ||
2462 !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
2463
2464 ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
2465
2466 switch (LHSI->getOpcode()) {
2467 default: return 0;
2468 case Instruction::And:
Owen Andersonbaf3c402009-07-29 18:55:55 +00002469 if (ConstantExpr::getAnd(N, Mask) == Mask) {
Chris Lattner7203e152005-09-18 07:22:02 +00002470 // If the AndRHS is a power of two minus one (0+1+), this is simple.
Zhou Sheng00f436c2007-03-24 15:34:37 +00002471 if ((Mask->getValue().countLeadingZeros() +
2472 Mask->getValue().countPopulation()) ==
2473 Mask->getValue().getBitWidth())
Chris Lattner7203e152005-09-18 07:22:02 +00002474 break;
2475
2476 // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
2477 // part, we don't need any explicit masks to take them out of A. If that
2478 // is all N is, ignore it.
Zhou Sheng4351c642007-04-02 08:20:41 +00002479 uint32_t MB = 0, ME = 0;
Chris Lattner7203e152005-09-18 07:22:02 +00002480 if (isRunOfOnes(Mask, MB, ME)) { // begin/end bit of run, inclusive
Reid Spencerb35ae032007-03-23 18:46:34 +00002481 uint32_t BitWidth = cast<IntegerType>(RHS->getType())->getBitWidth();
Zhou Sheng290bec52007-03-29 08:15:12 +00002482 APInt Mask(APInt::getLowBitsSet(BitWidth, MB-1));
Chris Lattner3bedbd92006-02-07 07:27:52 +00002483 if (MaskedValueIsZero(RHS, Mask))
Chris Lattner7203e152005-09-18 07:22:02 +00002484 break;
2485 }
2486 }
Chris Lattnerc8e77562005-09-18 04:24:45 +00002487 return 0;
2488 case Instruction::Or:
2489 case Instruction::Xor:
Chris Lattner7203e152005-09-18 07:22:02 +00002490 // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
Zhou Sheng00f436c2007-03-24 15:34:37 +00002491 if ((Mask->getValue().countLeadingZeros() +
2492 Mask->getValue().countPopulation()) == Mask->getValue().getBitWidth()
Owen Andersonbaf3c402009-07-29 18:55:55 +00002493 && ConstantExpr::getAnd(N, Mask)->isNullValue())
Chris Lattnerc8e77562005-09-18 04:24:45 +00002494 break;
2495 return 0;
2496 }
2497
Chris Lattnerc8e77562005-09-18 04:24:45 +00002498 if (isSub)
Chris Lattner74381062009-08-30 07:44:24 +00002499 return Builder->CreateSub(LHSI->getOperand(0), RHS, "fold");
2500 return Builder->CreateAdd(LHSI->getOperand(0), RHS, "fold");
Chris Lattnerc8e77562005-09-18 04:24:45 +00002501}
2502
Chris Lattner29cd5ba2008-11-16 05:06:21 +00002503/// FoldAndOfICmps - Fold (icmp)&(icmp) if possible.
2504Instruction *InstCombiner::FoldAndOfICmps(Instruction &I,
2505 ICmpInst *LHS, ICmpInst *RHS) {
Chris Lattnerea065fb2008-11-16 05:10:52 +00002506 Value *Val, *Val2;
Chris Lattner29cd5ba2008-11-16 05:06:21 +00002507 ConstantInt *LHSCst, *RHSCst;
2508 ICmpInst::Predicate LHSCC, RHSCC;
2509
Chris Lattnerea065fb2008-11-16 05:10:52 +00002510 // This only handles icmp of constants: (icmp1 A, C1) & (icmp2 B, C2).
Owen Andersonc7d2ce72009-07-10 17:35:01 +00002511 if (!match(LHS, m_ICmp(LHSCC, m_Value(Val),
Dan Gohman4ae51262009-08-12 16:23:25 +00002512 m_ConstantInt(LHSCst))) ||
Owen Andersonc7d2ce72009-07-10 17:35:01 +00002513 !match(RHS, m_ICmp(RHSCC, m_Value(Val2),
Dan Gohman4ae51262009-08-12 16:23:25 +00002514 m_ConstantInt(RHSCst))))
Chris Lattner29cd5ba2008-11-16 05:06:21 +00002515 return 0;
Chris Lattnerea065fb2008-11-16 05:10:52 +00002516
Chris Lattner3f40e232009-11-29 00:51:17 +00002517 if (LHSCst == RHSCst && LHSCC == RHSCC) {
2518 // (icmp ult A, C) & (icmp ult B, C) --> (icmp ult (A|B), C)
2519 // where C is a power of 2
2520 if (LHSCC == ICmpInst::ICMP_ULT &&
2521 LHSCst->getValue().isPowerOf2()) {
2522 Value *NewOr = Builder->CreateOr(Val, Val2);
2523 return new ICmpInst(LHSCC, NewOr, LHSCst);
2524 }
2525
2526 // (icmp eq A, 0) & (icmp eq B, 0) --> (icmp eq (A|B), 0)
2527 if (LHSCC == ICmpInst::ICMP_EQ && LHSCst->isZero()) {
2528 Value *NewOr = Builder->CreateOr(Val, Val2);
2529 return new ICmpInst(LHSCC, NewOr, LHSCst);
2530 }
Chris Lattnerea065fb2008-11-16 05:10:52 +00002531 }
2532
2533 // From here on, we only handle:
2534 // (icmp1 A, C1) & (icmp2 A, C2) --> something simpler.
2535 if (Val != Val2) return 0;
2536
Chris Lattner29cd5ba2008-11-16 05:06:21 +00002537 // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
2538 if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
2539 RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
2540 LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
2541 RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
2542 return 0;
2543
2544 // We can't fold (ugt x, C) & (sgt x, C2).
2545 if (!PredicatesFoldable(LHSCC, RHSCC))
2546 return 0;
2547
2548 // Ensure that the larger constant is on the RHS.
Chris Lattneraa3e1572008-11-16 05:14:43 +00002549 bool ShouldSwap;
Nick Lewycky4a134af2009-10-25 05:20:17 +00002550 if (CmpInst::isSigned(LHSCC) ||
Chris Lattner29cd5ba2008-11-16 05:06:21 +00002551 (ICmpInst::isEquality(LHSCC) &&
Nick Lewycky4a134af2009-10-25 05:20:17 +00002552 CmpInst::isSigned(RHSCC)))
Chris Lattneraa3e1572008-11-16 05:14:43 +00002553 ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
Chris Lattner29cd5ba2008-11-16 05:06:21 +00002554 else
Chris Lattneraa3e1572008-11-16 05:14:43 +00002555 ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
2556
2557 if (ShouldSwap) {
Chris Lattner29cd5ba2008-11-16 05:06:21 +00002558 std::swap(LHS, RHS);
2559 std::swap(LHSCst, RHSCst);
2560 std::swap(LHSCC, RHSCC);
2561 }
2562
2563 // At this point, we know we have have two icmp instructions
2564 // comparing a value against two constants and and'ing the result
2565 // together. Because of the above check, we know that we only have
2566 // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know
2567 // (from the FoldICmpLogical check above), that the two constants
2568 // are not equal and that the larger constant is on the RHS
2569 assert(LHSCst != RHSCst && "Compares not folded above?");
2570
2571 switch (LHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00002572 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00002573 case ICmpInst::ICMP_EQ:
2574 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00002575 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00002576 case ICmpInst::ICMP_EQ: // (X == 13 & X == 15) -> false
2577 case ICmpInst::ICMP_UGT: // (X == 13 & X > 15) -> false
2578 case ICmpInst::ICMP_SGT: // (X == 13 & X > 15) -> false
Chris Lattner4de84762010-01-04 07:02:48 +00002579 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getContext()));
Chris Lattner29cd5ba2008-11-16 05:06:21 +00002580 case ICmpInst::ICMP_NE: // (X == 13 & X != 15) -> X == 13
2581 case ICmpInst::ICMP_ULT: // (X == 13 & X < 15) -> X == 13
2582 case ICmpInst::ICMP_SLT: // (X == 13 & X < 15) -> X == 13
2583 return ReplaceInstUsesWith(I, LHS);
2584 }
2585 case ICmpInst::ICMP_NE:
2586 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00002587 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00002588 case ICmpInst::ICMP_ULT:
Dan Gohman186a6362009-08-12 16:04:34 +00002589 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X u< 14) -> X < 13
Dan Gohman1c8a23c2009-08-25 23:17:54 +00002590 return new ICmpInst(ICmpInst::ICMP_ULT, Val, LHSCst);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00002591 break; // (X != 13 & X u< 15) -> no change
2592 case ICmpInst::ICMP_SLT:
Dan Gohman186a6362009-08-12 16:04:34 +00002593 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X s< 14) -> X < 13
Dan Gohman1c8a23c2009-08-25 23:17:54 +00002594 return new ICmpInst(ICmpInst::ICMP_SLT, Val, LHSCst);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00002595 break; // (X != 13 & X s< 15) -> no change
2596 case ICmpInst::ICMP_EQ: // (X != 13 & X == 15) -> X == 15
2597 case ICmpInst::ICMP_UGT: // (X != 13 & X u> 15) -> X u> 15
2598 case ICmpInst::ICMP_SGT: // (X != 13 & X s> 15) -> X s> 15
2599 return ReplaceInstUsesWith(I, RHS);
2600 case ICmpInst::ICMP_NE:
Dan Gohman186a6362009-08-12 16:04:34 +00002601 if (LHSCst == SubOne(RHSCst)){// (X != 13 & X != 14) -> X-13 >u 1
Owen Andersonbaf3c402009-07-29 18:55:55 +00002602 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
Chris Lattner74381062009-08-30 07:44:24 +00002603 Value *Add = Builder->CreateAdd(Val, AddCST, Val->getName()+".off");
Dan Gohman1c8a23c2009-08-25 23:17:54 +00002604 return new ICmpInst(ICmpInst::ICMP_UGT, Add,
Owen Andersoneed707b2009-07-24 23:12:02 +00002605 ConstantInt::get(Add->getType(), 1));
Chris Lattner29cd5ba2008-11-16 05:06:21 +00002606 }
2607 break; // (X != 13 & X != 15) -> no change
2608 }
2609 break;
2610 case ICmpInst::ICMP_ULT:
2611 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00002612 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00002613 case ICmpInst::ICMP_EQ: // (X u< 13 & X == 15) -> false
2614 case ICmpInst::ICMP_UGT: // (X u< 13 & X u> 15) -> false
Chris Lattner4de84762010-01-04 07:02:48 +00002615 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getContext()));
Chris Lattner29cd5ba2008-11-16 05:06:21 +00002616 case ICmpInst::ICMP_SGT: // (X u< 13 & X s> 15) -> no change
2617 break;
2618 case ICmpInst::ICMP_NE: // (X u< 13 & X != 15) -> X u< 13
2619 case ICmpInst::ICMP_ULT: // (X u< 13 & X u< 15) -> X u< 13
2620 return ReplaceInstUsesWith(I, LHS);
2621 case ICmpInst::ICMP_SLT: // (X u< 13 & X s< 15) -> no change
2622 break;
2623 }
2624 break;
2625 case ICmpInst::ICMP_SLT:
2626 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00002627 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00002628 case ICmpInst::ICMP_EQ: // (X s< 13 & X == 15) -> false
2629 case ICmpInst::ICMP_SGT: // (X s< 13 & X s> 15) -> false
Chris Lattner4de84762010-01-04 07:02:48 +00002630 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getContext()));
Chris Lattner29cd5ba2008-11-16 05:06:21 +00002631 case ICmpInst::ICMP_UGT: // (X s< 13 & X u> 15) -> no change
2632 break;
2633 case ICmpInst::ICMP_NE: // (X s< 13 & X != 15) -> X < 13
2634 case ICmpInst::ICMP_SLT: // (X s< 13 & X s< 15) -> X < 13
2635 return ReplaceInstUsesWith(I, LHS);
2636 case ICmpInst::ICMP_ULT: // (X s< 13 & X u< 15) -> no change
2637 break;
2638 }
2639 break;
2640 case ICmpInst::ICMP_UGT:
2641 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00002642 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00002643 case ICmpInst::ICMP_EQ: // (X u> 13 & X == 15) -> X == 15
2644 case ICmpInst::ICMP_UGT: // (X u> 13 & X u> 15) -> X u> 15
2645 return ReplaceInstUsesWith(I, RHS);
2646 case ICmpInst::ICMP_SGT: // (X u> 13 & X s> 15) -> no change
2647 break;
2648 case ICmpInst::ICMP_NE:
Dan Gohman186a6362009-08-12 16:04:34 +00002649 if (RHSCst == AddOne(LHSCst)) // (X u> 13 & X != 14) -> X u> 14
Dan Gohman1c8a23c2009-08-25 23:17:54 +00002650 return new ICmpInst(LHSCC, Val, RHSCst);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00002651 break; // (X u> 13 & X != 15) -> no change
Chris Lattner69d4ced2008-11-16 05:20:07 +00002652 case ICmpInst::ICMP_ULT: // (X u> 13 & X u< 15) -> (X-14) <u 1
Dan Gohman186a6362009-08-12 16:04:34 +00002653 return InsertRangeTest(Val, AddOne(LHSCst),
Owen Andersond672ecb2009-07-03 00:17:18 +00002654 RHSCst, false, true, I);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00002655 case ICmpInst::ICMP_SLT: // (X u> 13 & X s< 15) -> no change
2656 break;
2657 }
2658 break;
2659 case ICmpInst::ICMP_SGT:
2660 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00002661 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00002662 case ICmpInst::ICMP_EQ: // (X s> 13 & X == 15) -> X == 15
2663 case ICmpInst::ICMP_SGT: // (X s> 13 & X s> 15) -> X s> 15
2664 return ReplaceInstUsesWith(I, RHS);
2665 case ICmpInst::ICMP_UGT: // (X s> 13 & X u> 15) -> no change
2666 break;
2667 case ICmpInst::ICMP_NE:
Dan Gohman186a6362009-08-12 16:04:34 +00002668 if (RHSCst == AddOne(LHSCst)) // (X s> 13 & X != 14) -> X s> 14
Dan Gohman1c8a23c2009-08-25 23:17:54 +00002669 return new ICmpInst(LHSCC, Val, RHSCst);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00002670 break; // (X s> 13 & X != 15) -> no change
Chris Lattner69d4ced2008-11-16 05:20:07 +00002671 case ICmpInst::ICMP_SLT: // (X s> 13 & X s< 15) -> (X-14) s< 1
Dan Gohman186a6362009-08-12 16:04:34 +00002672 return InsertRangeTest(Val, AddOne(LHSCst),
Owen Andersond672ecb2009-07-03 00:17:18 +00002673 RHSCst, true, true, I);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00002674 case ICmpInst::ICMP_ULT: // (X s> 13 & X u< 15) -> no change
2675 break;
2676 }
2677 break;
2678 }
Chris Lattner29cd5ba2008-11-16 05:06:21 +00002679
2680 return 0;
2681}
2682
Chris Lattner42d1be02009-07-23 05:14:02 +00002683Instruction *InstCombiner::FoldAndOfFCmps(Instruction &I, FCmpInst *LHS,
2684 FCmpInst *RHS) {
2685
2686 if (LHS->getPredicate() == FCmpInst::FCMP_ORD &&
2687 RHS->getPredicate() == FCmpInst::FCMP_ORD) {
2688 // (fcmp ord x, c) & (fcmp ord y, c) -> (fcmp ord x, y)
2689 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
2690 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
2691 // If either of the constants are nans, then the whole thing returns
2692 // false.
2693 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Chris Lattner4de84762010-01-04 07:02:48 +00002694 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getContext()));
Dan Gohman1c8a23c2009-08-25 23:17:54 +00002695 return new FCmpInst(FCmpInst::FCMP_ORD,
Chris Lattner42d1be02009-07-23 05:14:02 +00002696 LHS->getOperand(0), RHS->getOperand(0));
2697 }
Chris Lattnerf98d2532009-07-23 05:32:17 +00002698
2699 // Handle vector zeros. This occurs because the canonical form of
2700 // "fcmp ord x,x" is "fcmp ord x, 0".
2701 if (isa<ConstantAggregateZero>(LHS->getOperand(1)) &&
2702 isa<ConstantAggregateZero>(RHS->getOperand(1)))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00002703 return new FCmpInst(FCmpInst::FCMP_ORD,
Chris Lattnerf98d2532009-07-23 05:32:17 +00002704 LHS->getOperand(0), RHS->getOperand(0));
Chris Lattner42d1be02009-07-23 05:14:02 +00002705 return 0;
2706 }
2707
2708 Value *Op0LHS = LHS->getOperand(0), *Op0RHS = LHS->getOperand(1);
2709 Value *Op1LHS = RHS->getOperand(0), *Op1RHS = RHS->getOperand(1);
2710 FCmpInst::Predicate Op0CC = LHS->getPredicate(), Op1CC = RHS->getPredicate();
2711
2712
2713 if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
2714 // Swap RHS operands to match LHS.
2715 Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
2716 std::swap(Op1LHS, Op1RHS);
2717 }
2718
2719 if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
2720 // Simplify (fcmp cc0 x, y) & (fcmp cc1 x, y).
2721 if (Op0CC == Op1CC)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00002722 return new FCmpInst((FCmpInst::Predicate)Op0CC, Op0LHS, Op0RHS);
Chris Lattner42d1be02009-07-23 05:14:02 +00002723
2724 if (Op0CC == FCmpInst::FCMP_FALSE || Op1CC == FCmpInst::FCMP_FALSE)
Chris Lattner4de84762010-01-04 07:02:48 +00002725 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getContext()));
Chris Lattner42d1be02009-07-23 05:14:02 +00002726 if (Op0CC == FCmpInst::FCMP_TRUE)
2727 return ReplaceInstUsesWith(I, RHS);
2728 if (Op1CC == FCmpInst::FCMP_TRUE)
2729 return ReplaceInstUsesWith(I, LHS);
2730
2731 bool Op0Ordered;
2732 bool Op1Ordered;
2733 unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
2734 unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
2735 if (Op1Pred == 0) {
2736 std::swap(LHS, RHS);
2737 std::swap(Op0Pred, Op1Pred);
2738 std::swap(Op0Ordered, Op1Ordered);
2739 }
2740 if (Op0Pred == 0) {
2741 // uno && ueq -> uno && (uno || eq) -> ueq
2742 // ord && olt -> ord && (ord && lt) -> olt
2743 if (Op0Ordered == Op1Ordered)
2744 return ReplaceInstUsesWith(I, RHS);
2745
2746 // uno && oeq -> uno && (ord && eq) -> false
2747 // uno && ord -> false
2748 if (!Op0Ordered)
Chris Lattner4de84762010-01-04 07:02:48 +00002749 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getContext()));
Chris Lattner42d1be02009-07-23 05:14:02 +00002750 // ord && ueq -> ord && (uno || eq) -> oeq
Chris Lattner4de84762010-01-04 07:02:48 +00002751 return cast<Instruction>(getFCmpValue(true, Op1Pred, Op0LHS, Op0RHS));
Chris Lattner42d1be02009-07-23 05:14:02 +00002752 }
2753 }
2754
2755 return 0;
2756}
2757
Chris Lattner29cd5ba2008-11-16 05:06:21 +00002758
Chris Lattner7e708292002-06-25 16:13:24 +00002759Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00002760 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00002761 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00002762
Chris Lattnerd06094f2009-11-10 00:55:12 +00002763 if (Value *V = SimplifyAndInst(Op0, Op1, TD))
2764 return ReplaceInstUsesWith(I, V);
Chris Lattner3f5b8772002-05-06 16:14:14 +00002765
Chris Lattnerf8c36f52006-02-12 08:02:11 +00002766 // See if we can simplify any instructions used by the instruction whose sole
Chris Lattner9ca96412006-02-08 03:25:32 +00002767 // purpose is to compute bits we don't care about.
Dan Gohman6de29f82009-06-15 22:12:54 +00002768 if (SimplifyDemandedInstructionBits(I))
Nick Lewycky546d6312010-01-02 15:25:44 +00002769 return &I;
Dan Gohman6de29f82009-06-15 22:12:54 +00002770
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002771 if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner7acdf1d2009-10-11 22:00:32 +00002772 const APInt &AndRHSMask = AndRHS->getValue();
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002773 APInt NotAndRHS(~AndRHSMask);
Chris Lattner6e7ba452005-01-01 16:22:27 +00002774
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00002775 // Optimize a variety of ((val OP C1) & C2) combinations...
Chris Lattner7acdf1d2009-10-11 22:00:32 +00002776 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Chris Lattner6e7ba452005-01-01 16:22:27 +00002777 Value *Op0LHS = Op0I->getOperand(0);
2778 Value *Op0RHS = Op0I->getOperand(1);
2779 switch (Op0I->getOpcode()) {
Chris Lattner7acdf1d2009-10-11 22:00:32 +00002780 default: break;
Chris Lattner6e7ba452005-01-01 16:22:27 +00002781 case Instruction::Xor:
2782 case Instruction::Or:
Chris Lattnerad1e3022005-01-23 20:26:55 +00002783 // If the mask is only needed on one incoming arm, push it up.
Chris Lattner7acdf1d2009-10-11 22:00:32 +00002784 if (!Op0I->hasOneUse()) break;
2785
2786 if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
2787 // Not masking anything out for the LHS, move to RHS.
2788 Value *NewRHS = Builder->CreateAnd(Op0RHS, AndRHS,
2789 Op0RHS->getName()+".masked");
2790 return BinaryOperator::Create(Op0I->getOpcode(), Op0LHS, NewRHS);
2791 }
2792 if (!isa<Constant>(Op0RHS) &&
2793 MaskedValueIsZero(Op0RHS, NotAndRHS)) {
2794 // Not masking anything out for the RHS, move to LHS.
2795 Value *NewLHS = Builder->CreateAnd(Op0LHS, AndRHS,
2796 Op0LHS->getName()+".masked");
2797 return BinaryOperator::Create(Op0I->getOpcode(), NewLHS, Op0RHS);
Chris Lattnerad1e3022005-01-23 20:26:55 +00002798 }
2799
Chris Lattner6e7ba452005-01-01 16:22:27 +00002800 break;
Chris Lattnerc8e77562005-09-18 04:24:45 +00002801 case Instruction::Add:
Chris Lattner7203e152005-09-18 07:22:02 +00002802 // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
2803 // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
2804 // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
2805 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002806 return BinaryOperator::CreateAnd(V, AndRHS);
Chris Lattner7203e152005-09-18 07:22:02 +00002807 if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002808 return BinaryOperator::CreateAnd(V, AndRHS); // Add commutes
Chris Lattnerc8e77562005-09-18 04:24:45 +00002809 break;
2810
2811 case Instruction::Sub:
Chris Lattner7203e152005-09-18 07:22:02 +00002812 // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
2813 // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
2814 // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
2815 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002816 return BinaryOperator::CreateAnd(V, AndRHS);
Nick Lewyckyb4d1bc92008-07-09 04:32:37 +00002817
Nick Lewycky5dcc41f2008-07-10 05:51:40 +00002818 // (A - N) & AndRHS -> -N & AndRHS iff A&AndRHS==0 and AndRHS
2819 // has 1's for all bits that the subtraction with A might affect.
2820 if (Op0I->hasOneUse()) {
2821 uint32_t BitWidth = AndRHSMask.getBitWidth();
2822 uint32_t Zeros = AndRHSMask.countLeadingZeros();
2823 APInt Mask = APInt::getLowBitsSet(BitWidth, BitWidth - Zeros);
2824
Nick Lewyckyb4d1bc92008-07-09 04:32:37 +00002825 ConstantInt *A = dyn_cast<ConstantInt>(Op0LHS);
Nick Lewycky5dcc41f2008-07-10 05:51:40 +00002826 if (!(A && A->isZero()) && // avoid infinite recursion.
2827 MaskedValueIsZero(Op0LHS, Mask)) {
Chris Lattner74381062009-08-30 07:44:24 +00002828 Value *NewNeg = Builder->CreateNeg(Op0RHS);
Nick Lewyckyb4d1bc92008-07-09 04:32:37 +00002829 return BinaryOperator::CreateAnd(NewNeg, AndRHS);
2830 }
2831 }
Chris Lattnerc8e77562005-09-18 04:24:45 +00002832 break;
Nick Lewyckyd1f77bf2008-07-09 05:20:13 +00002833
2834 case Instruction::Shl:
2835 case Instruction::LShr:
2836 // (1 << x) & 1 --> zext(x == 0)
2837 // (1 >> x) & 1 --> zext(x == 0)
Nick Lewyckyd8ad4922008-07-09 07:35:26 +00002838 if (AndRHSMask == 1 && Op0LHS == AndRHS) {
Chris Lattner74381062009-08-30 07:44:24 +00002839 Value *NewICmp =
2840 Builder->CreateICmpEQ(Op0RHS, Constant::getNullValue(I.getType()));
Nick Lewyckyd1f77bf2008-07-09 05:20:13 +00002841 return new ZExtInst(NewICmp, I.getType());
2842 }
2843 break;
Chris Lattner6e7ba452005-01-01 16:22:27 +00002844 }
2845
Chris Lattner58403262003-07-23 19:25:52 +00002846 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002847 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00002848 return Res;
Chris Lattner6e7ba452005-01-01 16:22:27 +00002849 } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
Chris Lattner2b83af22005-08-07 07:03:10 +00002850 // If this is an integer truncation or change from signed-to-unsigned, and
2851 // if the source is an and/or with immediate, transform it. This
2852 // frequently occurs for bitfield accesses.
2853 if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
Reid Spencer3da59db2006-11-27 01:05:10 +00002854 if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
Chris Lattner2b83af22005-08-07 07:03:10 +00002855 CastOp->getNumOperands() == 2)
Chris Lattner48b59ec2009-10-26 15:40:07 +00002856 if (ConstantInt *AndCI =dyn_cast<ConstantInt>(CastOp->getOperand(1))){
Chris Lattner2b83af22005-08-07 07:03:10 +00002857 if (CastOp->getOpcode() == Instruction::And) {
2858 // Change: and (cast (and X, C1) to T), C2
Reid Spencer3da59db2006-11-27 01:05:10 +00002859 // into : and (cast X to T), trunc_or_bitcast(C1)&C2
2860 // This will fold the two constants together, which may allow
2861 // other simplifications.
Chris Lattner74381062009-08-30 07:44:24 +00002862 Value *NewCast = Builder->CreateTruncOrBitCast(
Reid Spencerd977d862006-12-12 23:36:14 +00002863 CastOp->getOperand(0), I.getType(),
2864 CastOp->getName()+".shrunk");
Reid Spencer3da59db2006-11-27 01:05:10 +00002865 // trunc_or_bitcast(C1)&C2
Chris Lattner74381062009-08-30 07:44:24 +00002866 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
Owen Andersonbaf3c402009-07-29 18:55:55 +00002867 C3 = ConstantExpr::getAnd(C3, AndRHS);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002868 return BinaryOperator::CreateAnd(NewCast, C3);
Chris Lattner2b83af22005-08-07 07:03:10 +00002869 } else if (CastOp->getOpcode() == Instruction::Or) {
2870 // Change: and (cast (or X, C1) to T), C2
2871 // into : trunc(C1)&C2 iff trunc(C1)&C2 == C2
Chris Lattner74381062009-08-30 07:44:24 +00002872 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
Owen Andersonbaf3c402009-07-29 18:55:55 +00002873 if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS)
Owen Andersond672ecb2009-07-03 00:17:18 +00002874 // trunc(C1)&C2
Chris Lattner2b83af22005-08-07 07:03:10 +00002875 return ReplaceInstUsesWith(I, AndRHS);
2876 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00002877 }
Chris Lattner2b83af22005-08-07 07:03:10 +00002878 }
Chris Lattner06782f82003-07-23 19:36:21 +00002879 }
Chris Lattner2eefe512004-04-09 19:05:30 +00002880
2881 // Try to fold constant and into select arguments.
2882 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002883 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00002884 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00002885 if (isa<PHINode>(Op0))
2886 if (Instruction *NV = FoldOpIntoPhi(I))
2887 return NV;
Chris Lattnerc6a8aff2003-07-23 17:57:01 +00002888 }
2889
Chris Lattner5b62aa72004-06-18 06:07:51 +00002890
Misha Brukmancb6267b2004-07-30 12:50:08 +00002891 // (~A & ~B) == (~(A | B)) - De Morgan's Law
Chris Lattnerd06094f2009-11-10 00:55:12 +00002892 if (Value *Op0NotVal = dyn_castNotVal(Op0))
2893 if (Value *Op1NotVal = dyn_castNotVal(Op1))
2894 if (Op0->hasOneUse() && Op1->hasOneUse()) {
2895 Value *Or = Builder->CreateOr(Op0NotVal, Op1NotVal,
2896 I.getName()+".demorgan");
2897 return BinaryOperator::CreateNot(Or);
2898 }
2899
Chris Lattner2082ad92006-02-13 23:07:23 +00002900 {
Chris Lattner003b6202007-06-15 05:58:24 +00002901 Value *A = 0, *B = 0, *C = 0, *D = 0;
Chris Lattnerd06094f2009-11-10 00:55:12 +00002902 // (A|B) & ~(A&B) -> A^B
2903 if (match(Op0, m_Or(m_Value(A), m_Value(B))) &&
2904 match(Op1, m_Not(m_And(m_Value(C), m_Value(D)))) &&
2905 ((A == C && B == D) || (A == D && B == C)))
2906 return BinaryOperator::CreateXor(A, B);
Chris Lattner003b6202007-06-15 05:58:24 +00002907
Chris Lattnerd06094f2009-11-10 00:55:12 +00002908 // ~(A&B) & (A|B) -> A^B
2909 if (match(Op1, m_Or(m_Value(A), m_Value(B))) &&
2910 match(Op0, m_Not(m_And(m_Value(C), m_Value(D)))) &&
2911 ((A == C && B == D) || (A == D && B == C)))
2912 return BinaryOperator::CreateXor(A, B);
Chris Lattner64daab52006-04-01 08:03:55 +00002913
2914 if (Op0->hasOneUse() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00002915 match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
Chris Lattner64daab52006-04-01 08:03:55 +00002916 if (A == Op1) { // (A^B)&A -> A&(A^B)
2917 I.swapOperands(); // Simplify below
2918 std::swap(Op0, Op1);
2919 } else if (B == Op1) { // (A^B)&B -> B&(B^A)
2920 cast<BinaryOperator>(Op0)->swapOperands();
2921 I.swapOperands(); // Simplify below
2922 std::swap(Op0, Op1);
2923 }
2924 }
Bill Wendling7f0ef6b2008-11-30 13:08:13 +00002925
Chris Lattner64daab52006-04-01 08:03:55 +00002926 if (Op1->hasOneUse() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00002927 match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
Chris Lattner64daab52006-04-01 08:03:55 +00002928 if (B == Op0) { // B&(A^B) -> B&(B^A)
2929 cast<BinaryOperator>(Op1)->swapOperands();
2930 std::swap(A, B);
2931 }
Chris Lattner74381062009-08-30 07:44:24 +00002932 if (A == Op0) // A&(A^B) -> A & ~B
2933 return BinaryOperator::CreateAnd(A, Builder->CreateNot(B, "tmp"));
Chris Lattner64daab52006-04-01 08:03:55 +00002934 }
Bill Wendling7f0ef6b2008-11-30 13:08:13 +00002935
2936 // (A&((~A)|B)) -> A&B
Dan Gohman4ae51262009-08-12 16:23:25 +00002937 if (match(Op0, m_Or(m_Not(m_Specific(Op1)), m_Value(A))) ||
2938 match(Op0, m_Or(m_Value(A), m_Not(m_Specific(Op1)))))
Chris Lattnerd8aafcb2008-12-01 05:16:26 +00002939 return BinaryOperator::CreateAnd(A, Op1);
Dan Gohman4ae51262009-08-12 16:23:25 +00002940 if (match(Op1, m_Or(m_Not(m_Specific(Op0)), m_Value(A))) ||
2941 match(Op1, m_Or(m_Value(A), m_Not(m_Specific(Op0)))))
Chris Lattnerd8aafcb2008-12-01 05:16:26 +00002942 return BinaryOperator::CreateAnd(A, Op0);
Chris Lattner2082ad92006-02-13 23:07:23 +00002943 }
2944
Reid Spencere4d87aa2006-12-23 06:05:41 +00002945 if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1)) {
2946 // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
Dan Gohman186a6362009-08-12 16:04:34 +00002947 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00002948 return R;
2949
Chris Lattner29cd5ba2008-11-16 05:06:21 +00002950 if (ICmpInst *LHS = dyn_cast<ICmpInst>(Op0))
2951 if (Instruction *Res = FoldAndOfICmps(I, LHS, RHS))
2952 return Res;
Chris Lattner955f3312004-09-28 21:48:02 +00002953 }
2954
Chris Lattner6fc205f2006-05-05 06:39:07 +00002955 // fold (and (cast A), (cast B)) -> (cast (and A, B))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00002956 if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
2957 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
2958 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind ?
2959 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattnerf98d2532009-07-23 05:32:17 +00002960 if (SrcTy == Op1C->getOperand(0)->getType() &&
2961 SrcTy->isIntOrIntVector() &&
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00002962 // Only do this if the casts both really cause code to be generated.
Reid Spencere4d87aa2006-12-23 06:05:41 +00002963 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
2964 I.getType(), TD) &&
2965 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
2966 I.getType(), TD)) {
Chris Lattner74381062009-08-30 07:44:24 +00002967 Value *NewOp = Builder->CreateAnd(Op0C->getOperand(0),
2968 Op1C->getOperand(0), I.getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002969 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00002970 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00002971 }
Chris Lattnere511b742006-11-14 07:46:50 +00002972
2973 // (X >> Z) & (Y >> Z) -> (X&Y) >> Z for all shifts.
Reid Spencer832254e2007-02-02 02:16:23 +00002974 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
2975 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
2976 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
Chris Lattnere511b742006-11-14 07:46:50 +00002977 SI0->getOperand(1) == SI1->getOperand(1) &&
2978 (SI0->hasOneUse() || SI1->hasOneUse())) {
Chris Lattner74381062009-08-30 07:44:24 +00002979 Value *NewOp =
2980 Builder->CreateAnd(SI0->getOperand(0), SI1->getOperand(0),
2981 SI0->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002982 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
Reid Spencer832254e2007-02-02 02:16:23 +00002983 SI1->getOperand(1));
Chris Lattnere511b742006-11-14 07:46:50 +00002984 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00002985 }
2986
Evan Cheng8db90722008-10-14 17:15:11 +00002987 // If and'ing two fcmp, try combine them into one.
Chris Lattner99c65742007-10-24 05:38:08 +00002988 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
Chris Lattner42d1be02009-07-23 05:14:02 +00002989 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
2990 if (Instruction *Res = FoldAndOfFCmps(I, LHS, RHS))
2991 return Res;
Chris Lattner99c65742007-10-24 05:38:08 +00002992 }
Nick Lewyckyb4d1bc92008-07-09 04:32:37 +00002993
Chris Lattner7e708292002-06-25 16:13:24 +00002994 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00002995}
2996
Chris Lattner8c34cd22008-10-05 02:13:19 +00002997/// CollectBSwapParts - Analyze the specified subexpression and see if it is
2998/// capable of providing pieces of a bswap. The subexpression provides pieces
2999/// of a bswap if it is proven that each of the non-zero bytes in the output of
3000/// the expression came from the corresponding "byte swapped" byte in some other
3001/// value. For example, if the current subexpression is "(shl i32 %X, 24)" then
3002/// we know that the expression deposits the low byte of %X into the high byte
3003/// of the bswap result and that all other bytes are zero. This expression is
3004/// accepted, the high byte of ByteValues is set to X to indicate a correct
3005/// match.
3006///
3007/// This function returns true if the match was unsuccessful and false if so.
3008/// On entry to the function the "OverallLeftShift" is a signed integer value
3009/// indicating the number of bytes that the subexpression is later shifted. For
3010/// example, if the expression is later right shifted by 16 bits, the
3011/// OverallLeftShift value would be -2 on entry. This is used to specify which
3012/// byte of ByteValues is actually being set.
3013///
3014/// Similarly, ByteMask is a bitmask where a bit is clear if its corresponding
3015/// byte is masked to zero by a user. For example, in (X & 255), X will be
3016/// processed with a bytemask of 1. Because bytemask is 32-bits, this limits
3017/// this function to working on up to 32-byte (256 bit) values. ByteMask is
3018/// always in the local (OverallLeftShift) coordinate space.
3019///
3020static bool CollectBSwapParts(Value *V, int OverallLeftShift, uint32_t ByteMask,
3021 SmallVector<Value*, 8> &ByteValues) {
3022 if (Instruction *I = dyn_cast<Instruction>(V)) {
3023 // If this is an or instruction, it may be an inner node of the bswap.
3024 if (I->getOpcode() == Instruction::Or) {
3025 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
3026 ByteValues) ||
3027 CollectBSwapParts(I->getOperand(1), OverallLeftShift, ByteMask,
3028 ByteValues);
Chris Lattnerafe91a52006-06-15 19:07:26 +00003029 }
Chris Lattner8c34cd22008-10-05 02:13:19 +00003030
3031 // If this is a logical shift by a constant multiple of 8, recurse with
3032 // OverallLeftShift and ByteMask adjusted.
3033 if (I->isLogicalShift() && isa<ConstantInt>(I->getOperand(1))) {
3034 unsigned ShAmt =
3035 cast<ConstantInt>(I->getOperand(1))->getLimitedValue(~0U);
3036 // Ensure the shift amount is defined and of a byte value.
3037 if ((ShAmt & 7) || (ShAmt > 8*ByteValues.size()))
3038 return true;
3039
3040 unsigned ByteShift = ShAmt >> 3;
3041 if (I->getOpcode() == Instruction::Shl) {
3042 // X << 2 -> collect(X, +2)
3043 OverallLeftShift += ByteShift;
3044 ByteMask >>= ByteShift;
3045 } else {
3046 // X >>u 2 -> collect(X, -2)
3047 OverallLeftShift -= ByteShift;
3048 ByteMask <<= ByteShift;
Chris Lattnerde17ddc2008-10-08 06:42:28 +00003049 ByteMask &= (~0U >> (32-ByteValues.size()));
Chris Lattner8c34cd22008-10-05 02:13:19 +00003050 }
3051
3052 if (OverallLeftShift >= (int)ByteValues.size()) return true;
3053 if (OverallLeftShift <= -(int)ByteValues.size()) return true;
3054
3055 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
3056 ByteValues);
3057 }
3058
3059 // If this is a logical 'and' with a mask that clears bytes, clear the
3060 // corresponding bytes in ByteMask.
3061 if (I->getOpcode() == Instruction::And &&
3062 isa<ConstantInt>(I->getOperand(1))) {
3063 // Scan every byte of the and mask, seeing if the byte is either 0 or 255.
3064 unsigned NumBytes = ByteValues.size();
3065 APInt Byte(I->getType()->getPrimitiveSizeInBits(), 255);
3066 const APInt &AndMask = cast<ConstantInt>(I->getOperand(1))->getValue();
3067
3068 for (unsigned i = 0; i != NumBytes; ++i, Byte <<= 8) {
3069 // If this byte is masked out by a later operation, we don't care what
3070 // the and mask is.
3071 if ((ByteMask & (1 << i)) == 0)
3072 continue;
3073
3074 // If the AndMask is all zeros for this byte, clear the bit.
3075 APInt MaskB = AndMask & Byte;
3076 if (MaskB == 0) {
3077 ByteMask &= ~(1U << i);
3078 continue;
3079 }
3080
3081 // If the AndMask is not all ones for this byte, it's not a bytezap.
3082 if (MaskB != Byte)
3083 return true;
3084
3085 // Otherwise, this byte is kept.
3086 }
3087
3088 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
3089 ByteValues);
3090 }
Chris Lattnerafe91a52006-06-15 19:07:26 +00003091 }
3092
Chris Lattner8c34cd22008-10-05 02:13:19 +00003093 // Okay, we got to something that isn't a shift, 'or' or 'and'. This must be
3094 // the input value to the bswap. Some observations: 1) if more than one byte
3095 // is demanded from this input, then it could not be successfully assembled
3096 // into a byteswap. At least one of the two bytes would not be aligned with
3097 // their ultimate destination.
3098 if (!isPowerOf2_32(ByteMask)) return true;
3099 unsigned InputByteNo = CountTrailingZeros_32(ByteMask);
Chris Lattnerafe91a52006-06-15 19:07:26 +00003100
Chris Lattner8c34cd22008-10-05 02:13:19 +00003101 // 2) The input and ultimate destinations must line up: if byte 3 of an i32
3102 // is demanded, it needs to go into byte 0 of the result. This means that the
3103 // byte needs to be shifted until it lands in the right byte bucket. The
3104 // shift amount depends on the position: if the byte is coming from the high
3105 // part of the value (e.g. byte 3) then it must be shifted right. If from the
3106 // low part, it must be shifted left.
3107 unsigned DestByteNo = InputByteNo + OverallLeftShift;
3108 if (InputByteNo < ByteValues.size()/2) {
3109 if (ByteValues.size()-1-DestByteNo != InputByteNo)
3110 return true;
3111 } else {
3112 if (ByteValues.size()-1-DestByteNo != InputByteNo)
3113 return true;
3114 }
Chris Lattnerafe91a52006-06-15 19:07:26 +00003115
3116 // If the destination byte value is already defined, the values are or'd
3117 // together, which isn't a bswap (unless it's an or of the same bits).
Chris Lattner8c34cd22008-10-05 02:13:19 +00003118 if (ByteValues[DestByteNo] && ByteValues[DestByteNo] != V)
Chris Lattnerafe91a52006-06-15 19:07:26 +00003119 return true;
Chris Lattner8c34cd22008-10-05 02:13:19 +00003120 ByteValues[DestByteNo] = V;
Chris Lattnerafe91a52006-06-15 19:07:26 +00003121 return false;
3122}
3123
3124/// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
3125/// If so, insert the new bswap intrinsic and return it.
3126Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
Chris Lattner55fc8c42007-04-01 20:57:36 +00003127 const IntegerType *ITy = dyn_cast<IntegerType>(I.getType());
Chris Lattner8c34cd22008-10-05 02:13:19 +00003128 if (!ITy || ITy->getBitWidth() % 16 ||
3129 // ByteMask only allows up to 32-byte values.
3130 ITy->getBitWidth() > 32*8)
Chris Lattner55fc8c42007-04-01 20:57:36 +00003131 return 0; // Can only bswap pairs of bytes. Can't do vectors.
Chris Lattnerafe91a52006-06-15 19:07:26 +00003132
3133 /// ByteValues - For each byte of the result, we keep track of which value
3134 /// defines each byte.
Chris Lattner535014f2007-02-15 22:52:10 +00003135 SmallVector<Value*, 8> ByteValues;
Chris Lattner55fc8c42007-04-01 20:57:36 +00003136 ByteValues.resize(ITy->getBitWidth()/8);
Chris Lattnerafe91a52006-06-15 19:07:26 +00003137
3138 // Try to find all the pieces corresponding to the bswap.
Chris Lattner8c34cd22008-10-05 02:13:19 +00003139 uint32_t ByteMask = ~0U >> (32-ByteValues.size());
3140 if (CollectBSwapParts(&I, 0, ByteMask, ByteValues))
Chris Lattnerafe91a52006-06-15 19:07:26 +00003141 return 0;
3142
3143 // Check to see if all of the bytes come from the same value.
3144 Value *V = ByteValues[0];
3145 if (V == 0) return 0; // Didn't find a byte? Must be zero.
3146
3147 // Check to make sure that all of the bytes come from the same value.
3148 for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
3149 if (ByteValues[i] != V)
3150 return 0;
Chandler Carruth69940402007-08-04 01:51:18 +00003151 const Type *Tys[] = { ITy };
Chris Lattnerafe91a52006-06-15 19:07:26 +00003152 Module *M = I.getParent()->getParent()->getParent();
Chandler Carruth69940402007-08-04 01:51:18 +00003153 Function *F = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 1);
Gabor Greif051a9502008-04-06 20:25:17 +00003154 return CallInst::Create(F, V);
Chris Lattnerafe91a52006-06-15 19:07:26 +00003155}
3156
Chris Lattnerfaaf9512008-11-16 04:24:12 +00003157/// MatchSelectFromAndOr - We have an expression of the form (A&C)|(B&D). Check
3158/// If A is (cond?-1:0) and either B or D is ~(cond?-1,0) or (cond?0,-1), then
3159/// we can simplify this expression to "cond ? C : D or B".
3160static Instruction *MatchSelectFromAndOr(Value *A, Value *B,
Chris Lattner4de84762010-01-04 07:02:48 +00003161 Value *C, Value *D) {
Chris Lattnera6a474d2008-11-16 04:26:55 +00003162 // If A is not a select of -1/0, this cannot match.
Chris Lattner6046fb72008-11-16 04:46:19 +00003163 Value *Cond = 0;
Dan Gohman4ae51262009-08-12 16:23:25 +00003164 if (!match(A, m_SelectCst<-1, 0>(m_Value(Cond))))
Chris Lattnerfaaf9512008-11-16 04:24:12 +00003165 return 0;
3166
Chris Lattnera6a474d2008-11-16 04:26:55 +00003167 // ((cond?-1:0)&C) | (B&(cond?0:-1)) -> cond ? C : B.
Dan Gohman4ae51262009-08-12 16:23:25 +00003168 if (match(D, m_SelectCst<0, -1>(m_Specific(Cond))))
Chris Lattnera6a474d2008-11-16 04:26:55 +00003169 return SelectInst::Create(Cond, C, B);
Dan Gohman4ae51262009-08-12 16:23:25 +00003170 if (match(D, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond)))))
Chris Lattnera6a474d2008-11-16 04:26:55 +00003171 return SelectInst::Create(Cond, C, B);
3172 // ((cond?-1:0)&C) | ((cond?0:-1)&D) -> cond ? C : D.
Dan Gohman4ae51262009-08-12 16:23:25 +00003173 if (match(B, m_SelectCst<0, -1>(m_Specific(Cond))))
Chris Lattnera6a474d2008-11-16 04:26:55 +00003174 return SelectInst::Create(Cond, C, D);
Dan Gohman4ae51262009-08-12 16:23:25 +00003175 if (match(B, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond)))))
Chris Lattnera6a474d2008-11-16 04:26:55 +00003176 return SelectInst::Create(Cond, C, D);
Chris Lattnerfaaf9512008-11-16 04:24:12 +00003177 return 0;
3178}
Chris Lattnerafe91a52006-06-15 19:07:26 +00003179
Chris Lattner69d4ced2008-11-16 05:20:07 +00003180/// FoldOrOfICmps - Fold (icmp)|(icmp) if possible.
3181Instruction *InstCombiner::FoldOrOfICmps(Instruction &I,
3182 ICmpInst *LHS, ICmpInst *RHS) {
3183 Value *Val, *Val2;
3184 ConstantInt *LHSCst, *RHSCst;
3185 ICmpInst::Predicate LHSCC, RHSCC;
3186
3187 // This only handles icmp of constants: (icmp1 A, C1) | (icmp2 B, C2).
Chris Lattner3f40e232009-11-29 00:51:17 +00003188 if (!match(LHS, m_ICmp(LHSCC, m_Value(Val), m_ConstantInt(LHSCst))) ||
3189 !match(RHS, m_ICmp(RHSCC, m_Value(Val2), m_ConstantInt(RHSCst))))
Chris Lattner69d4ced2008-11-16 05:20:07 +00003190 return 0;
Chris Lattner3f40e232009-11-29 00:51:17 +00003191
3192
3193 // (icmp ne A, 0) | (icmp ne B, 0) --> (icmp ne (A|B), 0)
3194 if (LHSCst == RHSCst && LHSCC == RHSCC &&
3195 LHSCC == ICmpInst::ICMP_NE && LHSCst->isZero()) {
3196 Value *NewOr = Builder->CreateOr(Val, Val2);
3197 return new ICmpInst(LHSCC, NewOr, LHSCst);
3198 }
Chris Lattner69d4ced2008-11-16 05:20:07 +00003199
3200 // From here on, we only handle:
3201 // (icmp1 A, C1) | (icmp2 A, C2) --> something simpler.
3202 if (Val != Val2) return 0;
3203
3204 // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
3205 if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
3206 RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
3207 LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
3208 RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
3209 return 0;
3210
3211 // We can't fold (ugt x, C) | (sgt x, C2).
3212 if (!PredicatesFoldable(LHSCC, RHSCC))
3213 return 0;
3214
3215 // Ensure that the larger constant is on the RHS.
3216 bool ShouldSwap;
Nick Lewycky4a134af2009-10-25 05:20:17 +00003217 if (CmpInst::isSigned(LHSCC) ||
Chris Lattner69d4ced2008-11-16 05:20:07 +00003218 (ICmpInst::isEquality(LHSCC) &&
Nick Lewycky4a134af2009-10-25 05:20:17 +00003219 CmpInst::isSigned(RHSCC)))
Chris Lattner69d4ced2008-11-16 05:20:07 +00003220 ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
3221 else
3222 ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
3223
3224 if (ShouldSwap) {
3225 std::swap(LHS, RHS);
3226 std::swap(LHSCst, RHSCst);
3227 std::swap(LHSCC, RHSCC);
3228 }
3229
3230 // At this point, we know we have have two icmp instructions
3231 // comparing a value against two constants and or'ing the result
3232 // together. Because of the above check, we know that we only have
3233 // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
3234 // FoldICmpLogical check above), that the two constants are not
3235 // equal.
3236 assert(LHSCst != RHSCst && "Compares not folded above?");
3237
3238 switch (LHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003239 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00003240 case ICmpInst::ICMP_EQ:
3241 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003242 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00003243 case ICmpInst::ICMP_EQ:
Dan Gohman186a6362009-08-12 16:04:34 +00003244 if (LHSCst == SubOne(RHSCst)) {
Owen Andersond672ecb2009-07-03 00:17:18 +00003245 // (X == 13 | X == 14) -> X-13 <u 2
Owen Andersonbaf3c402009-07-29 18:55:55 +00003246 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
Chris Lattner74381062009-08-30 07:44:24 +00003247 Value *Add = Builder->CreateAdd(Val, AddCST, Val->getName()+".off");
Dan Gohman186a6362009-08-12 16:04:34 +00003248 AddCST = ConstantExpr::getSub(AddOne(RHSCst), LHSCst);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003249 return new ICmpInst(ICmpInst::ICMP_ULT, Add, AddCST);
Chris Lattner69d4ced2008-11-16 05:20:07 +00003250 }
3251 break; // (X == 13 | X == 15) -> no change
3252 case ICmpInst::ICMP_UGT: // (X == 13 | X u> 14) -> no change
3253 case ICmpInst::ICMP_SGT: // (X == 13 | X s> 14) -> no change
3254 break;
3255 case ICmpInst::ICMP_NE: // (X == 13 | X != 15) -> X != 15
3256 case ICmpInst::ICMP_ULT: // (X == 13 | X u< 15) -> X u< 15
3257 case ICmpInst::ICMP_SLT: // (X == 13 | X s< 15) -> X s< 15
3258 return ReplaceInstUsesWith(I, RHS);
3259 }
3260 break;
3261 case ICmpInst::ICMP_NE:
3262 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003263 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00003264 case ICmpInst::ICMP_EQ: // (X != 13 | X == 15) -> X != 13
3265 case ICmpInst::ICMP_UGT: // (X != 13 | X u> 15) -> X != 13
3266 case ICmpInst::ICMP_SGT: // (X != 13 | X s> 15) -> X != 13
3267 return ReplaceInstUsesWith(I, LHS);
3268 case ICmpInst::ICMP_NE: // (X != 13 | X != 15) -> true
3269 case ICmpInst::ICMP_ULT: // (X != 13 | X u< 15) -> true
3270 case ICmpInst::ICMP_SLT: // (X != 13 | X s< 15) -> true
Chris Lattner4de84762010-01-04 07:02:48 +00003271 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getContext()));
Chris Lattner69d4ced2008-11-16 05:20:07 +00003272 }
3273 break;
3274 case ICmpInst::ICMP_ULT:
3275 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003276 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00003277 case ICmpInst::ICMP_EQ: // (X u< 13 | X == 14) -> no change
3278 break;
3279 case ICmpInst::ICMP_UGT: // (X u< 13 | X u> 15) -> (X-13) u> 2
3280 // If RHSCst is [us]MAXINT, it is always false. Not handling
3281 // this can cause overflow.
3282 if (RHSCst->isMaxValue(false))
3283 return ReplaceInstUsesWith(I, LHS);
Dan Gohman186a6362009-08-12 16:04:34 +00003284 return InsertRangeTest(Val, LHSCst, AddOne(RHSCst),
Owen Andersond672ecb2009-07-03 00:17:18 +00003285 false, false, I);
Chris Lattner69d4ced2008-11-16 05:20:07 +00003286 case ICmpInst::ICMP_SGT: // (X u< 13 | X s> 15) -> no change
3287 break;
3288 case ICmpInst::ICMP_NE: // (X u< 13 | X != 15) -> X != 15
3289 case ICmpInst::ICMP_ULT: // (X u< 13 | X u< 15) -> X u< 15
3290 return ReplaceInstUsesWith(I, RHS);
3291 case ICmpInst::ICMP_SLT: // (X u< 13 | X s< 15) -> no change
3292 break;
3293 }
3294 break;
3295 case ICmpInst::ICMP_SLT:
3296 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003297 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00003298 case ICmpInst::ICMP_EQ: // (X s< 13 | X == 14) -> no change
3299 break;
3300 case ICmpInst::ICMP_SGT: // (X s< 13 | X s> 15) -> (X-13) s> 2
3301 // If RHSCst is [us]MAXINT, it is always false. Not handling
3302 // this can cause overflow.
3303 if (RHSCst->isMaxValue(true))
3304 return ReplaceInstUsesWith(I, LHS);
Dan Gohman186a6362009-08-12 16:04:34 +00003305 return InsertRangeTest(Val, LHSCst, AddOne(RHSCst),
Owen Andersond672ecb2009-07-03 00:17:18 +00003306 true, false, I);
Chris Lattner69d4ced2008-11-16 05:20:07 +00003307 case ICmpInst::ICMP_UGT: // (X s< 13 | X u> 15) -> no change
3308 break;
3309 case ICmpInst::ICMP_NE: // (X s< 13 | X != 15) -> X != 15
3310 case ICmpInst::ICMP_SLT: // (X s< 13 | X s< 15) -> X s< 15
3311 return ReplaceInstUsesWith(I, RHS);
3312 case ICmpInst::ICMP_ULT: // (X s< 13 | X u< 15) -> no change
3313 break;
3314 }
3315 break;
3316 case ICmpInst::ICMP_UGT:
3317 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003318 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00003319 case ICmpInst::ICMP_EQ: // (X u> 13 | X == 15) -> X u> 13
3320 case ICmpInst::ICMP_UGT: // (X u> 13 | X u> 15) -> X u> 13
3321 return ReplaceInstUsesWith(I, LHS);
3322 case ICmpInst::ICMP_SGT: // (X u> 13 | X s> 15) -> no change
3323 break;
3324 case ICmpInst::ICMP_NE: // (X u> 13 | X != 15) -> true
3325 case ICmpInst::ICMP_ULT: // (X u> 13 | X u< 15) -> true
Chris Lattner4de84762010-01-04 07:02:48 +00003326 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getContext()));
Chris Lattner69d4ced2008-11-16 05:20:07 +00003327 case ICmpInst::ICMP_SLT: // (X u> 13 | X s< 15) -> no change
3328 break;
3329 }
3330 break;
3331 case ICmpInst::ICMP_SGT:
3332 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003333 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00003334 case ICmpInst::ICMP_EQ: // (X s> 13 | X == 15) -> X > 13
3335 case ICmpInst::ICMP_SGT: // (X s> 13 | X s> 15) -> X > 13
3336 return ReplaceInstUsesWith(I, LHS);
3337 case ICmpInst::ICMP_UGT: // (X s> 13 | X u> 15) -> no change
3338 break;
3339 case ICmpInst::ICMP_NE: // (X s> 13 | X != 15) -> true
3340 case ICmpInst::ICMP_SLT: // (X s> 13 | X s< 15) -> true
Chris Lattner4de84762010-01-04 07:02:48 +00003341 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getContext()));
Chris Lattner69d4ced2008-11-16 05:20:07 +00003342 case ICmpInst::ICMP_ULT: // (X s> 13 | X u< 15) -> no change
3343 break;
3344 }
3345 break;
3346 }
3347 return 0;
3348}
3349
Chris Lattner5414cc52009-07-23 05:46:22 +00003350Instruction *InstCombiner::FoldOrOfFCmps(Instruction &I, FCmpInst *LHS,
3351 FCmpInst *RHS) {
3352 if (LHS->getPredicate() == FCmpInst::FCMP_UNO &&
3353 RHS->getPredicate() == FCmpInst::FCMP_UNO &&
3354 LHS->getOperand(0)->getType() == RHS->getOperand(0)->getType()) {
3355 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
3356 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
3357 // If either of the constants are nans, then the whole thing returns
3358 // true.
3359 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Chris Lattner4de84762010-01-04 07:02:48 +00003360 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getContext()));
Chris Lattner5414cc52009-07-23 05:46:22 +00003361
3362 // Otherwise, no need to compare the two constants, compare the
3363 // rest.
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003364 return new FCmpInst(FCmpInst::FCMP_UNO,
Chris Lattner5414cc52009-07-23 05:46:22 +00003365 LHS->getOperand(0), RHS->getOperand(0));
3366 }
3367
3368 // Handle vector zeros. This occurs because the canonical form of
3369 // "fcmp uno x,x" is "fcmp uno x, 0".
3370 if (isa<ConstantAggregateZero>(LHS->getOperand(1)) &&
3371 isa<ConstantAggregateZero>(RHS->getOperand(1)))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003372 return new FCmpInst(FCmpInst::FCMP_UNO,
Chris Lattner5414cc52009-07-23 05:46:22 +00003373 LHS->getOperand(0), RHS->getOperand(0));
3374
3375 return 0;
3376 }
3377
3378 Value *Op0LHS = LHS->getOperand(0), *Op0RHS = LHS->getOperand(1);
3379 Value *Op1LHS = RHS->getOperand(0), *Op1RHS = RHS->getOperand(1);
3380 FCmpInst::Predicate Op0CC = LHS->getPredicate(), Op1CC = RHS->getPredicate();
3381
3382 if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
3383 // Swap RHS operands to match LHS.
3384 Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
3385 std::swap(Op1LHS, Op1RHS);
3386 }
3387 if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
3388 // Simplify (fcmp cc0 x, y) | (fcmp cc1 x, y).
3389 if (Op0CC == Op1CC)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003390 return new FCmpInst((FCmpInst::Predicate)Op0CC,
Chris Lattner5414cc52009-07-23 05:46:22 +00003391 Op0LHS, Op0RHS);
3392 if (Op0CC == FCmpInst::FCMP_TRUE || Op1CC == FCmpInst::FCMP_TRUE)
Chris Lattner4de84762010-01-04 07:02:48 +00003393 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getContext()));
Chris Lattner5414cc52009-07-23 05:46:22 +00003394 if (Op0CC == FCmpInst::FCMP_FALSE)
3395 return ReplaceInstUsesWith(I, RHS);
3396 if (Op1CC == FCmpInst::FCMP_FALSE)
3397 return ReplaceInstUsesWith(I, LHS);
3398 bool Op0Ordered;
3399 bool Op1Ordered;
3400 unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
3401 unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
3402 if (Op0Ordered == Op1Ordered) {
3403 // If both are ordered or unordered, return a new fcmp with
3404 // or'ed predicates.
Chris Lattner4de84762010-01-04 07:02:48 +00003405 Value *RV = getFCmpValue(Op0Ordered, Op0Pred|Op1Pred, Op0LHS, Op0RHS);
Chris Lattner5414cc52009-07-23 05:46:22 +00003406 if (Instruction *I = dyn_cast<Instruction>(RV))
3407 return I;
3408 // Otherwise, it's a constant boolean value...
3409 return ReplaceInstUsesWith(I, RV);
3410 }
3411 }
3412 return 0;
3413}
3414
Bill Wendlinga698a472008-12-01 08:23:25 +00003415/// FoldOrWithConstants - This helper function folds:
3416///
Bill Wendlinga8bb13f2008-12-02 05:09:00 +00003417/// ((A | B) & C1) | (B & C2)
Bill Wendlinga698a472008-12-01 08:23:25 +00003418///
3419/// into:
3420///
Bill Wendlinga8bb13f2008-12-02 05:09:00 +00003421/// (A & C1) | B
Bill Wendlingd54d8602008-12-01 08:32:40 +00003422///
Bill Wendlinga8bb13f2008-12-02 05:09:00 +00003423/// when the XOR of the two constants is "all ones" (-1).
Bill Wendlingd54d8602008-12-01 08:32:40 +00003424Instruction *InstCombiner::FoldOrWithConstants(BinaryOperator &I, Value *Op,
Bill Wendlinga698a472008-12-01 08:23:25 +00003425 Value *A, Value *B, Value *C) {
Bill Wendlingdda74e02008-12-02 05:06:43 +00003426 ConstantInt *CI1 = dyn_cast<ConstantInt>(C);
3427 if (!CI1) return 0;
Bill Wendlinga698a472008-12-01 08:23:25 +00003428
Bill Wendling286a0542008-12-02 06:24:20 +00003429 Value *V1 = 0;
3430 ConstantInt *CI2 = 0;
Dan Gohman4ae51262009-08-12 16:23:25 +00003431 if (!match(Op, m_And(m_Value(V1), m_ConstantInt(CI2)))) return 0;
Bill Wendlinga698a472008-12-01 08:23:25 +00003432
Bill Wendling29976b92008-12-02 06:18:11 +00003433 APInt Xor = CI1->getValue() ^ CI2->getValue();
3434 if (!Xor.isAllOnesValue()) return 0;
3435
Bill Wendling286a0542008-12-02 06:24:20 +00003436 if (V1 == A || V1 == B) {
Chris Lattner74381062009-08-30 07:44:24 +00003437 Value *NewOp = Builder->CreateAnd((V1 == A) ? B : A, CI1);
Bill Wendlingd16c6e92008-12-02 06:22:04 +00003438 return BinaryOperator::CreateOr(NewOp, V1);
Bill Wendlinga698a472008-12-01 08:23:25 +00003439 }
3440
3441 return 0;
3442}
3443
Chris Lattner7e708292002-06-25 16:13:24 +00003444Instruction *InstCombiner::visitOr(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00003445 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00003446 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00003447
Chris Lattnerd06094f2009-11-10 00:55:12 +00003448 if (Value *V = SimplifyOrInst(Op0, Op1, TD))
3449 return ReplaceInstUsesWith(I, V);
3450
3451
Chris Lattnerf8c36f52006-02-12 08:02:11 +00003452 // See if we can simplify any instructions used by the instruction whose sole
3453 // purpose is to compute bits we don't care about.
Dan Gohman6de29f82009-06-15 22:12:54 +00003454 if (SimplifyDemandedInstructionBits(I))
3455 return &I;
Chris Lattner041a6c92007-06-15 05:26:55 +00003456
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003457 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner4f637d42006-01-06 17:59:59 +00003458 ConstantInt *C1 = 0; Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +00003459 // (X & C1) | C2 --> (X | C2) & (C1|C2)
Dan Gohman4ae51262009-08-12 16:23:25 +00003460 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00003461 isOnlyUse(Op0)) {
Chris Lattner74381062009-08-30 07:44:24 +00003462 Value *Or = Builder->CreateOr(X, RHS);
Chris Lattner6934a042007-02-11 01:23:03 +00003463 Or->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003464 return BinaryOperator::CreateAnd(Or,
Chris Lattner4de84762010-01-04 07:02:48 +00003465 ConstantInt::get(I.getContext(),
3466 RHS->getValue() | C1->getValue()));
Chris Lattneracd1f0f2004-07-30 07:50:03 +00003467 }
Chris Lattnerad44ebf2003-07-23 18:29:44 +00003468
Chris Lattneracd1f0f2004-07-30 07:50:03 +00003469 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
Dan Gohman4ae51262009-08-12 16:23:25 +00003470 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00003471 isOnlyUse(Op0)) {
Chris Lattner74381062009-08-30 07:44:24 +00003472 Value *Or = Builder->CreateOr(X, RHS);
Chris Lattner6934a042007-02-11 01:23:03 +00003473 Or->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003474 return BinaryOperator::CreateXor(Or,
Chris Lattner4de84762010-01-04 07:02:48 +00003475 ConstantInt::get(I.getContext(),
3476 C1->getValue() & ~RHS->getValue()));
Chris Lattnerad44ebf2003-07-23 18:29:44 +00003477 }
Chris Lattner2eefe512004-04-09 19:05:30 +00003478
3479 // Try to fold constant and into select arguments.
3480 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00003481 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00003482 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00003483 if (isa<PHINode>(Op0))
3484 if (Instruction *NV = FoldOpIntoPhi(I))
3485 return NV;
Chris Lattnerad44ebf2003-07-23 18:29:44 +00003486 }
3487
Chris Lattner4f637d42006-01-06 17:59:59 +00003488 Value *A = 0, *B = 0;
3489 ConstantInt *C1 = 0, *C2 = 0;
Chris Lattnerf4d4c872005-05-07 23:49:08 +00003490
Chris Lattner6423d4c2006-07-10 20:25:24 +00003491 // (A | B) | C and A | (B | C) -> bswap if possible.
3492 // (A >> B) | (C << D) and (A << B) | (B >> C) -> bswap if possible.
Dan Gohman4ae51262009-08-12 16:23:25 +00003493 if (match(Op0, m_Or(m_Value(), m_Value())) ||
3494 match(Op1, m_Or(m_Value(), m_Value())) ||
3495 (match(Op0, m_Shift(m_Value(), m_Value())) &&
3496 match(Op1, m_Shift(m_Value(), m_Value())))) {
Chris Lattnerafe91a52006-06-15 19:07:26 +00003497 if (Instruction *BSwap = MatchBSwap(I))
3498 return BSwap;
3499 }
3500
Chris Lattner6e4c6492005-05-09 04:58:36 +00003501 // (X^C)|Y -> (X|Y)^C iff Y&C == 0
Owen Andersonc7d2ce72009-07-10 17:35:01 +00003502 if (Op0->hasOneUse() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00003503 match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Reid Spencera03d45f2007-03-22 22:19:58 +00003504 MaskedValueIsZero(Op1, C1->getValue())) {
Chris Lattner74381062009-08-30 07:44:24 +00003505 Value *NOr = Builder->CreateOr(A, Op1);
Chris Lattner6934a042007-02-11 01:23:03 +00003506 NOr->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003507 return BinaryOperator::CreateXor(NOr, C1);
Chris Lattner6e4c6492005-05-09 04:58:36 +00003508 }
3509
3510 // Y|(X^C) -> (X|Y)^C iff Y&C == 0
Owen Andersonc7d2ce72009-07-10 17:35:01 +00003511 if (Op1->hasOneUse() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00003512 match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Reid Spencera03d45f2007-03-22 22:19:58 +00003513 MaskedValueIsZero(Op0, C1->getValue())) {
Chris Lattner74381062009-08-30 07:44:24 +00003514 Value *NOr = Builder->CreateOr(A, Op0);
Chris Lattner6934a042007-02-11 01:23:03 +00003515 NOr->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003516 return BinaryOperator::CreateXor(NOr, C1);
Chris Lattner6e4c6492005-05-09 04:58:36 +00003517 }
3518
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00003519 // (A & C)|(B & D)
Chris Lattner2384d7b2007-06-19 05:43:49 +00003520 Value *C = 0, *D = 0;
Dan Gohman4ae51262009-08-12 16:23:25 +00003521 if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
3522 match(Op1, m_And(m_Value(B), m_Value(D)))) {
Chris Lattner6cae0e02007-04-08 07:55:22 +00003523 Value *V1 = 0, *V2 = 0, *V3 = 0;
3524 C1 = dyn_cast<ConstantInt>(C);
3525 C2 = dyn_cast<ConstantInt>(D);
3526 if (C1 && C2) { // (A & C1)|(B & C2)
3527 // If we have: ((V + N) & C1) | (V & C2)
3528 // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
3529 // replace with V+N.
3530 if (C1->getValue() == ~C2->getValue()) {
3531 if ((C2->getValue() & (C2->getValue()+1)) == 0 && // C2 == 0+1+
Dan Gohman4ae51262009-08-12 16:23:25 +00003532 match(A, m_Add(m_Value(V1), m_Value(V2)))) {
Chris Lattner6cae0e02007-04-08 07:55:22 +00003533 // Add commutes, try both ways.
3534 if (V1 == B && MaskedValueIsZero(V2, C2->getValue()))
3535 return ReplaceInstUsesWith(I, A);
3536 if (V2 == B && MaskedValueIsZero(V1, C2->getValue()))
3537 return ReplaceInstUsesWith(I, A);
3538 }
3539 // Or commutes, try both ways.
3540 if ((C1->getValue() & (C1->getValue()+1)) == 0 &&
Dan Gohman4ae51262009-08-12 16:23:25 +00003541 match(B, m_Add(m_Value(V1), m_Value(V2)))) {
Chris Lattner6cae0e02007-04-08 07:55:22 +00003542 // Add commutes, try both ways.
3543 if (V1 == A && MaskedValueIsZero(V2, C1->getValue()))
3544 return ReplaceInstUsesWith(I, B);
3545 if (V2 == A && MaskedValueIsZero(V1, C1->getValue()))
3546 return ReplaceInstUsesWith(I, B);
3547 }
3548 }
Chris Lattnere4412c12010-01-04 06:03:59 +00003549
3550 // ((V | N) & C1) | (V & C2) --> (V|N) & (C1|C2)
3551 // iff (C1&C2) == 0 and (N&~C1) == 0
3552 if ((C1->getValue() & C2->getValue()) == 0) {
3553 if (match(A, m_Or(m_Value(V1), m_Value(V2))) &&
3554 ((V1 == B && MaskedValueIsZero(V2, ~C1->getValue())) || // (V|N)
3555 (V2 == B && MaskedValueIsZero(V1, ~C1->getValue())))) // (N|V)
3556 return BinaryOperator::CreateAnd(A,
3557 ConstantInt::get(A->getContext(),
3558 C1->getValue()|C2->getValue()));
3559 // Or commutes, try both ways.
3560 if (match(B, m_Or(m_Value(V1), m_Value(V2))) &&
3561 ((V1 == A && MaskedValueIsZero(V2, ~C2->getValue())) || // (V|N)
3562 (V2 == A && MaskedValueIsZero(V1, ~C2->getValue())))) // (N|V)
3563 return BinaryOperator::CreateAnd(B,
3564 ConstantInt::get(B->getContext(),
3565 C1->getValue()|C2->getValue()));
3566 }
Chris Lattner6cae0e02007-04-08 07:55:22 +00003567 }
3568
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00003569 // Check to see if we have any common things being and'ed. If so, find the
3570 // terms for V1 & (V2|V3).
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00003571 if (isOnlyUse(Op0) || isOnlyUse(Op1)) {
Chris Lattnere4412c12010-01-04 06:03:59 +00003572 V1 = 0;
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00003573 if (A == B) // (A & C)|(A & D) == A & (C|D)
3574 V1 = A, V2 = C, V3 = D;
3575 else if (A == D) // (A & C)|(B & A) == A & (B|C)
3576 V1 = A, V2 = B, V3 = C;
3577 else if (C == B) // (A & C)|(C & D) == C & (A|D)
3578 V1 = C, V2 = A, V3 = D;
3579 else if (C == D) // (A & C)|(B & C) == C & (A|B)
3580 V1 = C, V2 = A, V3 = B;
3581
3582 if (V1) {
Chris Lattner74381062009-08-30 07:44:24 +00003583 Value *Or = Builder->CreateOr(V2, V3, "tmp");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003584 return BinaryOperator::CreateAnd(V1, Or);
Chris Lattner0b7c0bf2005-09-18 06:02:59 +00003585 }
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00003586 }
Dan Gohmanb493b272008-10-28 22:38:57 +00003587
Dan Gohman1975d032008-10-30 20:40:10 +00003588 // (A & (C0?-1:0)) | (B & ~(C0?-1:0)) -> C0 ? A : B, and commuted variants
Chris Lattner4de84762010-01-04 07:02:48 +00003589 if (Instruction *Match = MatchSelectFromAndOr(A, B, C, D))
Chris Lattnerfaaf9512008-11-16 04:24:12 +00003590 return Match;
Chris Lattner4de84762010-01-04 07:02:48 +00003591 if (Instruction *Match = MatchSelectFromAndOr(B, A, D, C))
Chris Lattnerfaaf9512008-11-16 04:24:12 +00003592 return Match;
Chris Lattner4de84762010-01-04 07:02:48 +00003593 if (Instruction *Match = MatchSelectFromAndOr(C, B, A, D))
Chris Lattnerfaaf9512008-11-16 04:24:12 +00003594 return Match;
Chris Lattner4de84762010-01-04 07:02:48 +00003595 if (Instruction *Match = MatchSelectFromAndOr(D, A, B, C))
Chris Lattnerfaaf9512008-11-16 04:24:12 +00003596 return Match;
Bill Wendlingb01865c2008-11-30 13:52:49 +00003597
Bill Wendlingb01865c2008-11-30 13:52:49 +00003598 // ((A&~B)|(~A&B)) -> A^B
Dan Gohman4ae51262009-08-12 16:23:25 +00003599 if ((match(C, m_Not(m_Specific(D))) &&
3600 match(B, m_Not(m_Specific(A)))))
Bill Wendling03aae5f2008-12-01 08:09:47 +00003601 return BinaryOperator::CreateXor(A, D);
Bill Wendlingb01865c2008-11-30 13:52:49 +00003602 // ((~B&A)|(~A&B)) -> A^B
Dan Gohman4ae51262009-08-12 16:23:25 +00003603 if ((match(A, m_Not(m_Specific(D))) &&
3604 match(B, m_Not(m_Specific(C)))))
Bill Wendling03aae5f2008-12-01 08:09:47 +00003605 return BinaryOperator::CreateXor(C, D);
Bill Wendlingb01865c2008-11-30 13:52:49 +00003606 // ((A&~B)|(B&~A)) -> A^B
Dan Gohman4ae51262009-08-12 16:23:25 +00003607 if ((match(C, m_Not(m_Specific(B))) &&
3608 match(D, m_Not(m_Specific(A)))))
Bill Wendling03aae5f2008-12-01 08:09:47 +00003609 return BinaryOperator::CreateXor(A, B);
Bill Wendlingb01865c2008-11-30 13:52:49 +00003610 // ((~B&A)|(B&~A)) -> A^B
Dan Gohman4ae51262009-08-12 16:23:25 +00003611 if ((match(A, m_Not(m_Specific(B))) &&
3612 match(D, m_Not(m_Specific(C)))))
Bill Wendling03aae5f2008-12-01 08:09:47 +00003613 return BinaryOperator::CreateXor(C, B);
Chris Lattnere9bed7d2005-09-18 03:42:07 +00003614 }
Chris Lattnere511b742006-11-14 07:46:50 +00003615
3616 // (X >> Z) | (Y >> Z) -> (X|Y) >> Z for all shifts.
Reid Spencer832254e2007-02-02 02:16:23 +00003617 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
3618 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
3619 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
Chris Lattnere511b742006-11-14 07:46:50 +00003620 SI0->getOperand(1) == SI1->getOperand(1) &&
3621 (SI0->hasOneUse() || SI1->hasOneUse())) {
Chris Lattner74381062009-08-30 07:44:24 +00003622 Value *NewOp = Builder->CreateOr(SI0->getOperand(0), SI1->getOperand(0),
3623 SI0->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003624 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
Reid Spencer832254e2007-02-02 02:16:23 +00003625 SI1->getOperand(1));
Chris Lattnere511b742006-11-14 07:46:50 +00003626 }
3627 }
Chris Lattner67ca7682003-08-12 19:11:07 +00003628
Bill Wendlingb3833d12008-12-01 01:07:11 +00003629 // ((A|B)&1)|(B&-2) -> (A&1) | B
Dan Gohman4ae51262009-08-12 16:23:25 +00003630 if (match(Op0, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C))) ||
3631 match(Op0, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))))) {
Bill Wendlingd54d8602008-12-01 08:32:40 +00003632 Instruction *Ret = FoldOrWithConstants(I, Op1, A, B, C);
Bill Wendlinga698a472008-12-01 08:23:25 +00003633 if (Ret) return Ret;
Bill Wendlingb3833d12008-12-01 01:07:11 +00003634 }
3635 // (B&-2)|((A|B)&1) -> (A&1) | B
Dan Gohman4ae51262009-08-12 16:23:25 +00003636 if (match(Op1, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C))) ||
3637 match(Op1, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))))) {
Bill Wendlingd54d8602008-12-01 08:32:40 +00003638 Instruction *Ret = FoldOrWithConstants(I, Op0, A, B, C);
Bill Wendlinga698a472008-12-01 08:23:25 +00003639 if (Ret) return Ret;
Bill Wendlingb3833d12008-12-01 01:07:11 +00003640 }
3641
Chris Lattnerd06094f2009-11-10 00:55:12 +00003642 // (~A | ~B) == (~(A & B)) - De Morgan's Law
3643 if (Value *Op0NotVal = dyn_castNotVal(Op0))
3644 if (Value *Op1NotVal = dyn_castNotVal(Op1))
3645 if (Op0->hasOneUse() && Op1->hasOneUse()) {
3646 Value *And = Builder->CreateAnd(Op0NotVal, Op1NotVal,
3647 I.getName()+".demorgan");
3648 return BinaryOperator::CreateNot(And);
3649 }
Chris Lattnera2881962003-02-18 19:28:33 +00003650
Reid Spencere4d87aa2006-12-23 06:05:41 +00003651 // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
3652 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1))) {
Dan Gohman186a6362009-08-12 16:04:34 +00003653 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003654 return R;
3655
Chris Lattner69d4ced2008-11-16 05:20:07 +00003656 if (ICmpInst *LHS = dyn_cast<ICmpInst>(I.getOperand(0)))
3657 if (Instruction *Res = FoldOrOfICmps(I, LHS, RHS))
3658 return Res;
Chris Lattnerb4f40d22004-09-28 22:33:08 +00003659 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00003660
3661 // fold (or (cast A), (cast B)) -> (cast (or A, B))
Chris Lattner99c65742007-10-24 05:38:08 +00003662 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Chris Lattner6fc205f2006-05-05 06:39:07 +00003663 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00003664 if (Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
Evan Chengb98a10e2008-03-24 00:21:34 +00003665 if (!isa<ICmpInst>(Op0C->getOperand(0)) ||
3666 !isa<ICmpInst>(Op1C->getOperand(0))) {
3667 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattnerf98d2532009-07-23 05:32:17 +00003668 if (SrcTy == Op1C->getOperand(0)->getType() &&
3669 SrcTy->isIntOrIntVector() &&
Evan Chengb98a10e2008-03-24 00:21:34 +00003670 // Only do this if the casts both really cause code to be
3671 // generated.
3672 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
3673 I.getType(), TD) &&
3674 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
3675 I.getType(), TD)) {
Chris Lattner74381062009-08-30 07:44:24 +00003676 Value *NewOp = Builder->CreateOr(Op0C->getOperand(0),
3677 Op1C->getOperand(0), I.getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003678 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Evan Chengb98a10e2008-03-24 00:21:34 +00003679 }
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00003680 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00003681 }
Chris Lattner99c65742007-10-24 05:38:08 +00003682 }
3683
3684
3685 // (fcmp uno x, c) | (fcmp uno y, c) -> (fcmp uno x, y)
3686 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
Chris Lattner5414cc52009-07-23 05:46:22 +00003687 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
3688 if (Instruction *Res = FoldOrOfFCmps(I, LHS, RHS))
3689 return Res;
Chris Lattner99c65742007-10-24 05:38:08 +00003690 }
Chris Lattnere9bed7d2005-09-18 03:42:07 +00003691
Chris Lattner7e708292002-06-25 16:13:24 +00003692 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00003693}
3694
Dan Gohman844731a2008-05-13 00:00:25 +00003695namespace {
3696
Chris Lattnerc317d392004-02-16 01:20:27 +00003697// XorSelf - Implements: X ^ X --> 0
3698struct XorSelf {
3699 Value *RHS;
3700 XorSelf(Value *rhs) : RHS(rhs) {}
3701 bool shouldApply(Value *LHS) const { return LHS == RHS; }
3702 Instruction *apply(BinaryOperator &Xor) const {
3703 return &Xor;
3704 }
3705};
Chris Lattner3f5b8772002-05-06 16:14:14 +00003706
Dan Gohman844731a2008-05-13 00:00:25 +00003707}
Chris Lattner3f5b8772002-05-06 16:14:14 +00003708
Chris Lattner7e708292002-06-25 16:13:24 +00003709Instruction *InstCombiner::visitXor(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00003710 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00003711 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00003712
Evan Chengd34af782008-03-25 20:07:13 +00003713 if (isa<UndefValue>(Op1)) {
3714 if (isa<UndefValue>(Op0))
3715 // Handle undef ^ undef -> 0 special case. This is a common
3716 // idiom (misuse).
Owen Andersona7235ea2009-07-31 20:28:14 +00003717 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00003718 return ReplaceInstUsesWith(I, Op1); // X ^ undef -> undef
Evan Chengd34af782008-03-25 20:07:13 +00003719 }
Chris Lattnere87597f2004-10-16 18:11:37 +00003720
Chris Lattnerc317d392004-02-16 01:20:27 +00003721 // xor X, X = 0, even if X is nested in a sequence of Xor's.
Dan Gohman186a6362009-08-12 16:04:34 +00003722 if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
Chris Lattnera9ff5eb2007-08-05 08:47:58 +00003723 assert(Result == &I && "AssociativeOpt didn't work?"); Result=Result;
Owen Andersona7235ea2009-07-31 20:28:14 +00003724 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerc317d392004-02-16 01:20:27 +00003725 }
Chris Lattnerf8c36f52006-02-12 08:02:11 +00003726
3727 // See if we can simplify any instructions used by the instruction whose sole
3728 // purpose is to compute bits we don't care about.
Dan Gohman6de29f82009-06-15 22:12:54 +00003729 if (SimplifyDemandedInstructionBits(I))
3730 return &I;
3731 if (isa<VectorType>(I.getType()))
3732 if (isa<ConstantAggregateZero>(Op1))
3733 return ReplaceInstUsesWith(I, Op0); // X ^ <0,0> -> X
Chris Lattner3f5b8772002-05-06 16:14:14 +00003734
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00003735 // Is this a ~ operation?
Dan Gohman186a6362009-08-12 16:04:34 +00003736 if (Value *NotOp = dyn_castNotVal(&I)) {
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00003737 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(NotOp)) {
3738 if (Op0I->getOpcode() == Instruction::And ||
3739 Op0I->getOpcode() == Instruction::Or) {
Chris Lattner48b59ec2009-10-26 15:40:07 +00003740 // ~(~X & Y) --> (X | ~Y) - De Morgan's Law
3741 // ~(~X | Y) === (X & ~Y) - De Morgan's Law
3742 if (dyn_castNotVal(Op0I->getOperand(1)))
3743 Op0I->swapOperands();
Dan Gohman186a6362009-08-12 16:04:34 +00003744 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
Chris Lattner74381062009-08-30 07:44:24 +00003745 Value *NotY =
3746 Builder->CreateNot(Op0I->getOperand(1),
3747 Op0I->getOperand(1)->getName()+".not");
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00003748 if (Op0I->getOpcode() == Instruction::And)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003749 return BinaryOperator::CreateOr(Op0NotVal, NotY);
Chris Lattner74381062009-08-30 07:44:24 +00003750 return BinaryOperator::CreateAnd(Op0NotVal, NotY);
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00003751 }
Chris Lattner48b59ec2009-10-26 15:40:07 +00003752
3753 // ~(X & Y) --> (~X | ~Y) - De Morgan's Law
3754 // ~(X | Y) === (~X & ~Y) - De Morgan's Law
3755 if (isFreeToInvert(Op0I->getOperand(0)) &&
3756 isFreeToInvert(Op0I->getOperand(1))) {
3757 Value *NotX =
3758 Builder->CreateNot(Op0I->getOperand(0), "notlhs");
3759 Value *NotY =
3760 Builder->CreateNot(Op0I->getOperand(1), "notrhs");
3761 if (Op0I->getOpcode() == Instruction::And)
3762 return BinaryOperator::CreateOr(NotX, NotY);
3763 return BinaryOperator::CreateAnd(NotX, NotY);
3764 }
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00003765 }
3766 }
3767 }
3768
3769
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003770 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner7acdf1d2009-10-11 22:00:32 +00003771 if (RHS->isOne() && Op0->hasOneUse()) {
Bill Wendling3479be92009-01-01 01:18:23 +00003772 // xor (cmp A, B), true = not (cmp A, B) = !cmp A, B
Nick Lewyckyf947b3e2007-08-06 20:04:16 +00003773 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Op0))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003774 return new ICmpInst(ICI->getInversePredicate(),
Reid Spencere4d87aa2006-12-23 06:05:41 +00003775 ICI->getOperand(0), ICI->getOperand(1));
Chris Lattnerad5b4fb2003-11-04 23:50:51 +00003776
Nick Lewyckyf947b3e2007-08-06 20:04:16 +00003777 if (FCmpInst *FCI = dyn_cast<FCmpInst>(Op0))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003778 return new FCmpInst(FCI->getInversePredicate(),
Nick Lewyckyf947b3e2007-08-06 20:04:16 +00003779 FCI->getOperand(0), FCI->getOperand(1));
3780 }
3781
Nick Lewycky517e1f52008-05-31 19:01:33 +00003782 // fold (xor(zext(cmp)), 1) and (xor(sext(cmp)), -1) to ext(!cmp).
3783 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
3784 if (CmpInst *CI = dyn_cast<CmpInst>(Op0C->getOperand(0))) {
3785 if (CI->hasOneUse() && Op0C->hasOneUse()) {
3786 Instruction::CastOps Opcode = Op0C->getOpcode();
Chris Lattner74381062009-08-30 07:44:24 +00003787 if ((Opcode == Instruction::ZExt || Opcode == Instruction::SExt) &&
3788 (RHS == ConstantExpr::getCast(Opcode,
Chris Lattner4de84762010-01-04 07:02:48 +00003789 ConstantInt::getTrue(I.getContext()),
Chris Lattner74381062009-08-30 07:44:24 +00003790 Op0C->getDestTy()))) {
3791 CI->setPredicate(CI->getInversePredicate());
3792 return CastInst::Create(Opcode, CI, Op0C->getType());
Nick Lewycky517e1f52008-05-31 19:01:33 +00003793 }
3794 }
3795 }
3796 }
3797
Reid Spencere4d87aa2006-12-23 06:05:41 +00003798 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Chris Lattnerd65460f2003-11-05 01:06:05 +00003799 // ~(c-X) == X-c-1 == X+(-c-1)
Chris Lattner7c4049c2004-01-12 19:35:11 +00003800 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
3801 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00003802 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
3803 Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
Owen Andersoneed707b2009-07-24 23:12:02 +00003804 ConstantInt::get(I.getType(), 1));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003805 return BinaryOperator::CreateAdd(Op0I->getOperand(1), ConstantRHS);
Chris Lattner7c4049c2004-01-12 19:35:11 +00003806 }
Chris Lattner5c6e2db2007-04-02 05:36:22 +00003807
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00003808 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
Chris Lattnerf8c36f52006-02-12 08:02:11 +00003809 if (Op0I->getOpcode() == Instruction::Add) {
Chris Lattner689d24b2003-11-04 23:37:10 +00003810 // ~(X-c) --> (-c-1)-X
Chris Lattner7c4049c2004-01-12 19:35:11 +00003811 if (RHS->isAllOnesValue()) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00003812 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003813 return BinaryOperator::CreateSub(
Owen Andersonbaf3c402009-07-29 18:55:55 +00003814 ConstantExpr::getSub(NegOp0CI,
Owen Andersoneed707b2009-07-24 23:12:02 +00003815 ConstantInt::get(I.getType(), 1)),
Owen Andersond672ecb2009-07-03 00:17:18 +00003816 Op0I->getOperand(0));
Chris Lattneracf4e072007-04-02 05:42:22 +00003817 } else if (RHS->getValue().isSignBit()) {
Chris Lattner5c6e2db2007-04-02 05:36:22 +00003818 // (X + C) ^ signbit -> (X + C + signbit)
Chris Lattner4de84762010-01-04 07:02:48 +00003819 Constant *C = ConstantInt::get(I.getContext(),
Owen Andersoneed707b2009-07-24 23:12:02 +00003820 RHS->getValue() + Op0CI->getValue());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003821 return BinaryOperator::CreateAdd(Op0I->getOperand(0), C);
Chris Lattnercd1d6d52007-04-02 05:48:58 +00003822
Chris Lattner7c4049c2004-01-12 19:35:11 +00003823 }
Chris Lattner02bd1b32006-02-26 19:57:54 +00003824 } else if (Op0I->getOpcode() == Instruction::Or) {
3825 // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
Reid Spencera03d45f2007-03-22 22:19:58 +00003826 if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue())) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00003827 Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
Chris Lattner02bd1b32006-02-26 19:57:54 +00003828 // Anything in both C1 and C2 is known to be zero, remove it from
3829 // NewRHS.
Owen Andersonbaf3c402009-07-29 18:55:55 +00003830 Constant *CommonBits = ConstantExpr::getAnd(Op0CI, RHS);
3831 NewRHS = ConstantExpr::getAnd(NewRHS,
3832 ConstantExpr::getNot(CommonBits));
Chris Lattner7a1e9242009-08-30 06:13:40 +00003833 Worklist.Add(Op0I);
Chris Lattner02bd1b32006-02-26 19:57:54 +00003834 I.setOperand(0, Op0I->getOperand(0));
3835 I.setOperand(1, NewRHS);
3836 return &I;
3837 }
Chris Lattnereca0c5c2003-07-23 21:37:07 +00003838 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00003839 }
Chris Lattner05bd1b22002-08-20 18:24:26 +00003840 }
Chris Lattner2eefe512004-04-09 19:05:30 +00003841
3842 // Try to fold constant and into select arguments.
3843 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00003844 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00003845 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00003846 if (isa<PHINode>(Op0))
3847 if (Instruction *NV = FoldOpIntoPhi(I))
3848 return NV;
Chris Lattner3f5b8772002-05-06 16:14:14 +00003849 }
3850
Dan Gohman186a6362009-08-12 16:04:34 +00003851 if (Value *X = dyn_castNotVal(Op0)) // ~A ^ A == -1
Chris Lattnera2881962003-02-18 19:28:33 +00003852 if (X == Op1)
Owen Andersona7235ea2009-07-31 20:28:14 +00003853 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00003854
Dan Gohman186a6362009-08-12 16:04:34 +00003855 if (Value *X = dyn_castNotVal(Op1)) // A ^ ~A == -1
Chris Lattnera2881962003-02-18 19:28:33 +00003856 if (X == Op0)
Owen Andersona7235ea2009-07-31 20:28:14 +00003857 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00003858
Chris Lattner318bf792007-03-18 22:51:34 +00003859
3860 BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1);
3861 if (Op1I) {
3862 Value *A, *B;
Dan Gohman4ae51262009-08-12 16:23:25 +00003863 if (match(Op1I, m_Or(m_Value(A), m_Value(B)))) {
Chris Lattner318bf792007-03-18 22:51:34 +00003864 if (A == Op0) { // B^(B|A) == (A|B)^B
Chris Lattner64daab52006-04-01 08:03:55 +00003865 Op1I->swapOperands();
Chris Lattnercb40a372003-03-10 18:24:17 +00003866 I.swapOperands();
3867 std::swap(Op0, Op1);
Chris Lattner318bf792007-03-18 22:51:34 +00003868 } else if (B == Op0) { // B^(A|B) == (A|B)^B
Chris Lattner64daab52006-04-01 08:03:55 +00003869 I.swapOperands(); // Simplified below.
Chris Lattnercb40a372003-03-10 18:24:17 +00003870 std::swap(Op0, Op1);
Misha Brukmanfd939082005-04-21 23:48:37 +00003871 }
Dan Gohman4ae51262009-08-12 16:23:25 +00003872 } else if (match(Op1I, m_Xor(m_Specific(Op0), m_Value(B)))) {
Chris Lattnercb504b92008-11-16 05:38:51 +00003873 return ReplaceInstUsesWith(I, B); // A^(A^B) == B
Dan Gohman4ae51262009-08-12 16:23:25 +00003874 } else if (match(Op1I, m_Xor(m_Value(A), m_Specific(Op0)))) {
Chris Lattnercb504b92008-11-16 05:38:51 +00003875 return ReplaceInstUsesWith(I, A); // A^(B^A) == B
Dan Gohman4ae51262009-08-12 16:23:25 +00003876 } else if (match(Op1I, m_And(m_Value(A), m_Value(B))) &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00003877 Op1I->hasOneUse()){
Chris Lattner6abbdf92007-04-01 05:36:37 +00003878 if (A == Op0) { // A^(A&B) -> A^(B&A)
Chris Lattner64daab52006-04-01 08:03:55 +00003879 Op1I->swapOperands();
Chris Lattner6abbdf92007-04-01 05:36:37 +00003880 std::swap(A, B);
3881 }
Chris Lattner318bf792007-03-18 22:51:34 +00003882 if (B == Op0) { // A^(B&A) -> (B&A)^A
Chris Lattner64daab52006-04-01 08:03:55 +00003883 I.swapOperands(); // Simplified below.
3884 std::swap(Op0, Op1);
3885 }
Chris Lattner26ca7e12004-02-16 03:54:20 +00003886 }
Chris Lattner318bf792007-03-18 22:51:34 +00003887 }
3888
3889 BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0);
3890 if (Op0I) {
3891 Value *A, *B;
Dan Gohman4ae51262009-08-12 16:23:25 +00003892 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00003893 Op0I->hasOneUse()) {
Chris Lattner318bf792007-03-18 22:51:34 +00003894 if (A == Op1) // (B|A)^B == (A|B)^B
3895 std::swap(A, B);
Chris Lattner74381062009-08-30 07:44:24 +00003896 if (B == Op1) // (A|B)^B == A & ~B
3897 return BinaryOperator::CreateAnd(A, Builder->CreateNot(Op1, "tmp"));
Dan Gohman4ae51262009-08-12 16:23:25 +00003898 } else if (match(Op0I, m_Xor(m_Specific(Op1), m_Value(B)))) {
Chris Lattnercb504b92008-11-16 05:38:51 +00003899 return ReplaceInstUsesWith(I, B); // (A^B)^A == B
Dan Gohman4ae51262009-08-12 16:23:25 +00003900 } else if (match(Op0I, m_Xor(m_Value(A), m_Specific(Op1)))) {
Chris Lattnercb504b92008-11-16 05:38:51 +00003901 return ReplaceInstUsesWith(I, A); // (B^A)^A == B
Dan Gohman4ae51262009-08-12 16:23:25 +00003902 } else if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00003903 Op0I->hasOneUse()){
Chris Lattner318bf792007-03-18 22:51:34 +00003904 if (A == Op1) // (A&B)^A -> (B&A)^A
3905 std::swap(A, B);
3906 if (B == Op1 && // (B&A)^A == ~B & A
Chris Lattnerae1ab392006-04-01 22:05:01 +00003907 !isa<ConstantInt>(Op1)) { // Canonical form is (B&C)^C
Chris Lattner74381062009-08-30 07:44:24 +00003908 return BinaryOperator::CreateAnd(Builder->CreateNot(A, "tmp"), Op1);
Chris Lattner64daab52006-04-01 08:03:55 +00003909 }
Chris Lattnercb40a372003-03-10 18:24:17 +00003910 }
Chris Lattner318bf792007-03-18 22:51:34 +00003911 }
3912
3913 // (X >> Z) ^ (Y >> Z) -> (X^Y) >> Z for all shifts.
3914 if (Op0I && Op1I && Op0I->isShift() &&
3915 Op0I->getOpcode() == Op1I->getOpcode() &&
3916 Op0I->getOperand(1) == Op1I->getOperand(1) &&
3917 (Op1I->hasOneUse() || Op1I->hasOneUse())) {
Chris Lattner74381062009-08-30 07:44:24 +00003918 Value *NewOp =
3919 Builder->CreateXor(Op0I->getOperand(0), Op1I->getOperand(0),
3920 Op0I->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003921 return BinaryOperator::Create(Op1I->getOpcode(), NewOp,
Chris Lattner318bf792007-03-18 22:51:34 +00003922 Op1I->getOperand(1));
3923 }
3924
3925 if (Op0I && Op1I) {
3926 Value *A, *B, *C, *D;
3927 // (A & B)^(A | B) -> A ^ B
Dan Gohman4ae51262009-08-12 16:23:25 +00003928 if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
3929 match(Op1I, m_Or(m_Value(C), m_Value(D)))) {
Chris Lattner318bf792007-03-18 22:51:34 +00003930 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003931 return BinaryOperator::CreateXor(A, B);
Chris Lattner318bf792007-03-18 22:51:34 +00003932 }
3933 // (A | B)^(A & B) -> A ^ B
Dan Gohman4ae51262009-08-12 16:23:25 +00003934 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
3935 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
Chris Lattner318bf792007-03-18 22:51:34 +00003936 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003937 return BinaryOperator::CreateXor(A, B);
Chris Lattner318bf792007-03-18 22:51:34 +00003938 }
3939
3940 // (A & B)^(C & D)
3941 if ((Op0I->hasOneUse() || Op1I->hasOneUse()) &&
Dan Gohman4ae51262009-08-12 16:23:25 +00003942 match(Op0I, m_And(m_Value(A), m_Value(B))) &&
3943 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
Chris Lattner318bf792007-03-18 22:51:34 +00003944 // (X & Y)^(X & Y) -> (Y^Z) & X
3945 Value *X = 0, *Y = 0, *Z = 0;
3946 if (A == C)
3947 X = A, Y = B, Z = D;
3948 else if (A == D)
3949 X = A, Y = B, Z = C;
3950 else if (B == C)
3951 X = B, Y = A, Z = D;
3952 else if (B == D)
3953 X = B, Y = A, Z = C;
3954
3955 if (X) {
Chris Lattner74381062009-08-30 07:44:24 +00003956 Value *NewOp = Builder->CreateXor(Y, Z, Op0->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003957 return BinaryOperator::CreateAnd(NewOp, X);
Chris Lattner318bf792007-03-18 22:51:34 +00003958 }
3959 }
3960 }
3961
Reid Spencere4d87aa2006-12-23 06:05:41 +00003962 // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
3963 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
Dan Gohman186a6362009-08-12 16:04:34 +00003964 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003965 return R;
3966
Chris Lattner6fc205f2006-05-05 06:39:07 +00003967 // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
Chris Lattner99c65742007-10-24 05:38:08 +00003968 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Chris Lattner6fc205f2006-05-05 06:39:07 +00003969 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00003970 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
3971 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner42a75512007-01-15 02:27:26 +00003972 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00003973 // Only do this if the casts both really cause code to be generated.
Reid Spencere4d87aa2006-12-23 06:05:41 +00003974 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
3975 I.getType(), TD) &&
3976 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
3977 I.getType(), TD)) {
Chris Lattner74381062009-08-30 07:44:24 +00003978 Value *NewOp = Builder->CreateXor(Op0C->getOperand(0),
3979 Op1C->getOperand(0), I.getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003980 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00003981 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00003982 }
Chris Lattner99c65742007-10-24 05:38:08 +00003983 }
Nick Lewycky517e1f52008-05-31 19:01:33 +00003984
Chris Lattner7e708292002-06-25 16:13:24 +00003985 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00003986}
3987
Chris Lattner3f5b8772002-05-06 16:14:14 +00003988
Reid Spencer832254e2007-02-02 02:16:23 +00003989Instruction *InstCombiner::visitShl(BinaryOperator &I) {
3990 return commonShiftTransforms(I);
3991}
3992
3993Instruction *InstCombiner::visitLShr(BinaryOperator &I) {
3994 return commonShiftTransforms(I);
3995}
3996
3997Instruction *InstCombiner::visitAShr(BinaryOperator &I) {
Chris Lattner348f6652007-12-06 01:59:46 +00003998 if (Instruction *R = commonShiftTransforms(I))
3999 return R;
4000
4001 Value *Op0 = I.getOperand(0);
4002
4003 // ashr int -1, X = -1 (for any arithmetic shift rights of ~0)
4004 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
4005 if (CSI->isAllOnesValue())
4006 return ReplaceInstUsesWith(I, CSI);
Dan Gohman0001e562009-02-24 02:00:40 +00004007
Dan Gohmanc6ac3222009-06-16 19:55:29 +00004008 // See if we can turn a signed shr into an unsigned shr.
4009 if (MaskedValueIsZero(Op0,
4010 APInt::getSignBit(I.getType()->getScalarSizeInBits())))
4011 return BinaryOperator::CreateLShr(Op0, I.getOperand(1));
4012
4013 // Arithmetic shifting an all-sign-bit value is a no-op.
4014 unsigned NumSignBits = ComputeNumSignBits(Op0);
4015 if (NumSignBits == Op0->getType()->getScalarSizeInBits())
4016 return ReplaceInstUsesWith(I, Op0);
Dan Gohman0001e562009-02-24 02:00:40 +00004017
Chris Lattner348f6652007-12-06 01:59:46 +00004018 return 0;
Reid Spencer832254e2007-02-02 02:16:23 +00004019}
4020
4021Instruction *InstCombiner::commonShiftTransforms(BinaryOperator &I) {
4022 assert(I.getOperand(1)->getType() == I.getOperand(0)->getType());
Chris Lattner7e708292002-06-25 16:13:24 +00004023 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00004024
4025 // shl X, 0 == X and shr X, 0 == X
4026 // shl 0, X == 0 and shr 0, X == 0
Owen Andersona7235ea2009-07-31 20:28:14 +00004027 if (Op1 == Constant::getNullValue(Op1->getType()) ||
4028 Op0 == Constant::getNullValue(Op0->getType()))
Chris Lattner233f7dc2002-08-12 21:17:25 +00004029 return ReplaceInstUsesWith(I, Op0);
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00004030
Reid Spencere4d87aa2006-12-23 06:05:41 +00004031 if (isa<UndefValue>(Op0)) {
4032 if (I.getOpcode() == Instruction::AShr) // undef >>s X -> undef
Chris Lattner79a564c2004-10-16 23:28:04 +00004033 return ReplaceInstUsesWith(I, Op0);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004034 else // undef << X -> 0, undef >>u X -> 0
Owen Andersona7235ea2009-07-31 20:28:14 +00004035 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00004036 }
4037 if (isa<UndefValue>(Op1)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00004038 if (I.getOpcode() == Instruction::AShr) // X >>s undef -> X
4039 return ReplaceInstUsesWith(I, Op0);
4040 else // X << undef, X >>u undef -> 0
Owen Andersona7235ea2009-07-31 20:28:14 +00004041 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00004042 }
4043
Dan Gohman9004c8a2009-05-21 02:28:33 +00004044 // See if we can fold away this shift.
Dan Gohman6de29f82009-06-15 22:12:54 +00004045 if (SimplifyDemandedInstructionBits(I))
Dan Gohman9004c8a2009-05-21 02:28:33 +00004046 return &I;
4047
Chris Lattner2eefe512004-04-09 19:05:30 +00004048 // Try to fold constant and into select arguments.
4049 if (isa<Constant>(Op0))
4050 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner6e7ba452005-01-01 16:22:27 +00004051 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00004052 return R;
4053
Reid Spencerb83eb642006-10-20 07:07:24 +00004054 if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
Reid Spencerc5b206b2006-12-31 05:48:39 +00004055 if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
4056 return Res;
Chris Lattner4d5542c2006-01-06 07:12:35 +00004057 return 0;
4058}
4059
Reid Spencerb83eb642006-10-20 07:07:24 +00004060Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
Reid Spencer832254e2007-02-02 02:16:23 +00004061 BinaryOperator &I) {
Chris Lattner4598c942009-01-31 08:24:16 +00004062 bool isLeftShift = I.getOpcode() == Instruction::Shl;
Chris Lattner4d5542c2006-01-06 07:12:35 +00004063
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00004064 // See if we can simplify any instructions used by the instruction whose sole
4065 // purpose is to compute bits we don't care about.
Dan Gohmanc6ac3222009-06-16 19:55:29 +00004066 uint32_t TypeBits = Op0->getType()->getScalarSizeInBits();
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00004067
Dan Gohmana119de82009-06-14 23:30:43 +00004068 // shl i32 X, 32 = 0 and srl i8 Y, 9 = 0, ... just don't eliminate
4069 // a signed shift.
Chris Lattner4d5542c2006-01-06 07:12:35 +00004070 //
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00004071 if (Op1->uge(TypeBits)) {
Chris Lattner0737c242007-02-02 05:29:55 +00004072 if (I.getOpcode() != Instruction::AShr)
Owen Andersona7235ea2009-07-31 20:28:14 +00004073 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
Chris Lattner4d5542c2006-01-06 07:12:35 +00004074 else {
Owen Andersoneed707b2009-07-24 23:12:02 +00004075 I.setOperand(1, ConstantInt::get(I.getType(), TypeBits-1));
Chris Lattner4d5542c2006-01-06 07:12:35 +00004076 return &I;
Chris Lattner8adac752004-02-23 20:30:06 +00004077 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00004078 }
4079
4080 // ((X*C1) << C2) == (X * (C1 << C2))
4081 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
4082 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
4083 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004084 return BinaryOperator::CreateMul(BO->getOperand(0),
Owen Andersonbaf3c402009-07-29 18:55:55 +00004085 ConstantExpr::getShl(BOOp, Op1));
Chris Lattner4d5542c2006-01-06 07:12:35 +00004086
4087 // Try to fold constant and into select arguments.
4088 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
4089 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
4090 return R;
4091 if (isa<PHINode>(Op0))
4092 if (Instruction *NV = FoldOpIntoPhi(I))
4093 return NV;
4094
Chris Lattner8999dd32007-12-22 09:07:47 +00004095 // Fold shift2(trunc(shift1(x,c1)), c2) -> trunc(shift2(shift1(x,c1),c2))
4096 if (TruncInst *TI = dyn_cast<TruncInst>(Op0)) {
4097 Instruction *TrOp = dyn_cast<Instruction>(TI->getOperand(0));
4098 // If 'shift2' is an ashr, we would have to get the sign bit into a funny
4099 // place. Don't try to do this transformation in this case. Also, we
4100 // require that the input operand is a shift-by-constant so that we have
4101 // confidence that the shifts will get folded together. We could do this
4102 // xform in more cases, but it is unlikely to be profitable.
4103 if (TrOp && I.isLogicalShift() && TrOp->isShift() &&
4104 isa<ConstantInt>(TrOp->getOperand(1))) {
4105 // Okay, we'll do this xform. Make the shift of shift.
Owen Andersonbaf3c402009-07-29 18:55:55 +00004106 Constant *ShAmt = ConstantExpr::getZExt(Op1, TrOp->getType());
Chris Lattner74381062009-08-30 07:44:24 +00004107 // (shift2 (shift1 & 0x00FF), c2)
4108 Value *NSh = Builder->CreateBinOp(I.getOpcode(), TrOp, ShAmt,I.getName());
Chris Lattner8999dd32007-12-22 09:07:47 +00004109
4110 // For logical shifts, the truncation has the effect of making the high
4111 // part of the register be zeros. Emulate this by inserting an AND to
4112 // clear the top bits as needed. This 'and' will usually be zapped by
4113 // other xforms later if dead.
Dan Gohmanc6ac3222009-06-16 19:55:29 +00004114 unsigned SrcSize = TrOp->getType()->getScalarSizeInBits();
4115 unsigned DstSize = TI->getType()->getScalarSizeInBits();
Chris Lattner8999dd32007-12-22 09:07:47 +00004116 APInt MaskV(APInt::getLowBitsSet(SrcSize, DstSize));
4117
4118 // The mask we constructed says what the trunc would do if occurring
4119 // between the shifts. We want to know the effect *after* the second
4120 // shift. We know that it is a logical shift by a constant, so adjust the
4121 // mask as appropriate.
4122 if (I.getOpcode() == Instruction::Shl)
4123 MaskV <<= Op1->getZExtValue();
4124 else {
4125 assert(I.getOpcode() == Instruction::LShr && "Unknown logical shift");
4126 MaskV = MaskV.lshr(Op1->getZExtValue());
4127 }
4128
Chris Lattner74381062009-08-30 07:44:24 +00004129 // shift1 & 0x00FF
Chris Lattner4de84762010-01-04 07:02:48 +00004130 Value *And = Builder->CreateAnd(NSh,
4131 ConstantInt::get(I.getContext(), MaskV),
Chris Lattner74381062009-08-30 07:44:24 +00004132 TI->getName());
Chris Lattner8999dd32007-12-22 09:07:47 +00004133
4134 // Return the value truncated to the interesting size.
4135 return new TruncInst(And, I.getType());
4136 }
4137 }
4138
Chris Lattner4d5542c2006-01-06 07:12:35 +00004139 if (Op0->hasOneUse()) {
Chris Lattner4d5542c2006-01-06 07:12:35 +00004140 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
4141 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
4142 Value *V1, *V2;
4143 ConstantInt *CC;
4144 switch (Op0BO->getOpcode()) {
Chris Lattner11021cb2005-09-18 05:12:10 +00004145 default: break;
4146 case Instruction::Add:
4147 case Instruction::And:
4148 case Instruction::Or:
Reid Spencera07cb7d2007-02-02 14:41:37 +00004149 case Instruction::Xor: {
Chris Lattner11021cb2005-09-18 05:12:10 +00004150 // These operators commute.
4151 // Turn (Y + (X >> C)) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00004152 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004153 match(Op0BO->getOperand(1), m_Shr(m_Value(V1),
Chris Lattnerf925cbd2009-08-30 18:50:58 +00004154 m_Specific(Op1)))) {
4155 Value *YS = // (Y << C)
4156 Builder->CreateShl(Op0BO->getOperand(0), Op1, Op0BO->getName());
4157 // (X + (Y << C))
4158 Value *X = Builder->CreateBinOp(Op0BO->getOpcode(), YS, V1,
4159 Op0BO->getOperand(1)->getName());
Zhou Sheng302748d2007-03-30 17:20:39 +00004160 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
Chris Lattner4de84762010-01-04 07:02:48 +00004161 return BinaryOperator::CreateAnd(X, ConstantInt::get(I.getContext(),
Zhou Sheng90b96812007-03-30 05:45:18 +00004162 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
Chris Lattner150f12a2005-09-18 06:30:59 +00004163 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00004164
Chris Lattner150f12a2005-09-18 06:30:59 +00004165 // Turn (Y + ((X >> C) & CC)) << C -> ((X & (CC << C)) + (Y << C))
Reid Spencera07cb7d2007-02-02 14:41:37 +00004166 Value *Op0BOOp1 = Op0BO->getOperand(1);
Chris Lattner3c698492007-03-05 00:11:19 +00004167 if (isLeftShift && Op0BOOp1->hasOneUse() &&
Reid Spencera07cb7d2007-02-02 14:41:37 +00004168 match(Op0BOOp1,
Chris Lattnercb504b92008-11-16 05:38:51 +00004169 m_And(m_Shr(m_Value(V1), m_Specific(Op1)),
Dan Gohman4ae51262009-08-12 16:23:25 +00004170 m_ConstantInt(CC))) &&
Chris Lattnercb504b92008-11-16 05:38:51 +00004171 cast<BinaryOperator>(Op0BOOp1)->getOperand(0)->hasOneUse()) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +00004172 Value *YS = // (Y << C)
4173 Builder->CreateShl(Op0BO->getOperand(0), Op1,
4174 Op0BO->getName());
4175 // X & (CC << C)
4176 Value *XM = Builder->CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
4177 V1->getName()+".mask");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004178 return BinaryOperator::Create(Op0BO->getOpcode(), YS, XM);
Chris Lattner150f12a2005-09-18 06:30:59 +00004179 }
Reid Spencera07cb7d2007-02-02 14:41:37 +00004180 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00004181
Reid Spencera07cb7d2007-02-02 14:41:37 +00004182 // FALL THROUGH.
4183 case Instruction::Sub: {
Chris Lattner11021cb2005-09-18 05:12:10 +00004184 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00004185 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004186 match(Op0BO->getOperand(0), m_Shr(m_Value(V1),
Dan Gohman4ae51262009-08-12 16:23:25 +00004187 m_Specific(Op1)))) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +00004188 Value *YS = // (Y << C)
4189 Builder->CreateShl(Op0BO->getOperand(1), Op1, Op0BO->getName());
4190 // (X + (Y << C))
4191 Value *X = Builder->CreateBinOp(Op0BO->getOpcode(), V1, YS,
4192 Op0BO->getOperand(0)->getName());
Zhou Sheng302748d2007-03-30 17:20:39 +00004193 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
Chris Lattner4de84762010-01-04 07:02:48 +00004194 return BinaryOperator::CreateAnd(X, ConstantInt::get(I.getContext(),
Zhou Sheng90b96812007-03-30 05:45:18 +00004195 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
Chris Lattner150f12a2005-09-18 06:30:59 +00004196 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00004197
Chris Lattner13d4ab42006-05-31 21:14:00 +00004198 // Turn (((X >> C)&CC) + Y) << C -> (X + (Y << C)) & (CC << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00004199 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
4200 match(Op0BO->getOperand(0),
4201 m_And(m_Shr(m_Value(V1), m_Value(V2)),
Dan Gohman4ae51262009-08-12 16:23:25 +00004202 m_ConstantInt(CC))) && V2 == Op1 &&
Chris Lattner9a4cacb2006-02-09 07:41:14 +00004203 cast<BinaryOperator>(Op0BO->getOperand(0))
4204 ->getOperand(0)->hasOneUse()) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +00004205 Value *YS = // (Y << C)
4206 Builder->CreateShl(Op0BO->getOperand(1), Op1, Op0BO->getName());
4207 // X & (CC << C)
4208 Value *XM = Builder->CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
4209 V1->getName()+".mask");
Chris Lattner150f12a2005-09-18 06:30:59 +00004210
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004211 return BinaryOperator::Create(Op0BO->getOpcode(), XM, YS);
Chris Lattner150f12a2005-09-18 06:30:59 +00004212 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00004213
Chris Lattner11021cb2005-09-18 05:12:10 +00004214 break;
Reid Spencera07cb7d2007-02-02 14:41:37 +00004215 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00004216 }
4217
4218
4219 // If the operand is an bitwise operator with a constant RHS, and the
4220 // shift is the only use, we can pull it out of the shift.
4221 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
4222 bool isValid = true; // Valid only for And, Or, Xor
4223 bool highBitSet = false; // Transform if high bit of constant set?
4224
4225 switch (Op0BO->getOpcode()) {
Chris Lattnerdf17af12003-08-12 21:53:41 +00004226 default: isValid = false; break; // Do not perform transform!
Chris Lattner1f7e1602004-10-08 03:46:20 +00004227 case Instruction::Add:
4228 isValid = isLeftShift;
4229 break;
Chris Lattnerdf17af12003-08-12 21:53:41 +00004230 case Instruction::Or:
4231 case Instruction::Xor:
4232 highBitSet = false;
4233 break;
4234 case Instruction::And:
4235 highBitSet = true;
4236 break;
Chris Lattner4d5542c2006-01-06 07:12:35 +00004237 }
4238
4239 // If this is a signed shift right, and the high bit is modified
4240 // by the logical operation, do not perform the transformation.
4241 // The highBitSet boolean indicates the value of the high bit of
4242 // the constant which would cause it to be modified for this
4243 // operation.
4244 //
Chris Lattnerc95ba442007-12-06 06:25:04 +00004245 if (isValid && I.getOpcode() == Instruction::AShr)
Zhou Shenge9e03f62007-03-28 15:02:20 +00004246 isValid = Op0C->getValue()[TypeBits-1] == highBitSet;
Chris Lattner4d5542c2006-01-06 07:12:35 +00004247
4248 if (isValid) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00004249 Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
Chris Lattner4d5542c2006-01-06 07:12:35 +00004250
Chris Lattnerf925cbd2009-08-30 18:50:58 +00004251 Value *NewShift =
4252 Builder->CreateBinOp(I.getOpcode(), Op0BO->getOperand(0), Op1);
Chris Lattner6934a042007-02-11 01:23:03 +00004253 NewShift->takeName(Op0BO);
Chris Lattner4d5542c2006-01-06 07:12:35 +00004254
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004255 return BinaryOperator::Create(Op0BO->getOpcode(), NewShift,
Chris Lattner4d5542c2006-01-06 07:12:35 +00004256 NewRHS);
4257 }
4258 }
4259 }
4260 }
4261
Chris Lattnerad0124c2006-01-06 07:52:12 +00004262 // Find out if this is a shift of a shift by a constant.
Reid Spencer832254e2007-02-02 02:16:23 +00004263 BinaryOperator *ShiftOp = dyn_cast<BinaryOperator>(Op0);
4264 if (ShiftOp && !ShiftOp->isShift())
4265 ShiftOp = 0;
Chris Lattnerad0124c2006-01-06 07:52:12 +00004266
Reid Spencerb83eb642006-10-20 07:07:24 +00004267 if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
Reid Spencerb83eb642006-10-20 07:07:24 +00004268 ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00004269 uint32_t ShiftAmt1 = ShiftAmt1C->getLimitedValue(TypeBits);
4270 uint32_t ShiftAmt2 = Op1->getLimitedValue(TypeBits);
Chris Lattnerb87056f2007-02-05 00:57:54 +00004271 assert(ShiftAmt2 != 0 && "Should have been simplified earlier");
4272 if (ShiftAmt1 == 0) return 0; // Will be simplified in the future.
4273 Value *X = ShiftOp->getOperand(0);
Chris Lattnerad0124c2006-01-06 07:52:12 +00004274
Zhou Sheng4351c642007-04-02 08:20:41 +00004275 uint32_t AmtSum = ShiftAmt1+ShiftAmt2; // Fold into one big shift.
Chris Lattnerb87056f2007-02-05 00:57:54 +00004276
4277 const IntegerType *Ty = cast<IntegerType>(I.getType());
4278
4279 // Check for (X << c1) << c2 and (X >> c1) >> c2
Chris Lattner7f3da2d2007-02-03 23:28:07 +00004280 if (I.getOpcode() == ShiftOp->getOpcode()) {
Chris Lattner344c7c52009-03-20 22:41:15 +00004281 // If this is oversized composite shift, then unsigned shifts get 0, ashr
4282 // saturates.
4283 if (AmtSum >= TypeBits) {
4284 if (I.getOpcode() != Instruction::AShr)
Owen Andersona7235ea2009-07-31 20:28:14 +00004285 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner344c7c52009-03-20 22:41:15 +00004286 AmtSum = TypeBits-1; // Saturate to 31 for i32 ashr.
4287 }
4288
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004289 return BinaryOperator::Create(I.getOpcode(), X,
Owen Andersoneed707b2009-07-24 23:12:02 +00004290 ConstantInt::get(Ty, AmtSum));
Chris Lattnerf925cbd2009-08-30 18:50:58 +00004291 }
4292
4293 if (ShiftOp->getOpcode() == Instruction::LShr &&
4294 I.getOpcode() == Instruction::AShr) {
Chris Lattner344c7c52009-03-20 22:41:15 +00004295 if (AmtSum >= TypeBits)
Owen Andersona7235ea2009-07-31 20:28:14 +00004296 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner344c7c52009-03-20 22:41:15 +00004297
Chris Lattnerb87056f2007-02-05 00:57:54 +00004298 // ((X >>u C1) >>s C2) -> (X >>u (C1+C2)) since C1 != 0.
Owen Andersoneed707b2009-07-24 23:12:02 +00004299 return BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, AmtSum));
Chris Lattnerf925cbd2009-08-30 18:50:58 +00004300 }
4301
4302 if (ShiftOp->getOpcode() == Instruction::AShr &&
4303 I.getOpcode() == Instruction::LShr) {
Chris Lattnerb87056f2007-02-05 00:57:54 +00004304 // ((X >>s C1) >>u C2) -> ((X >>s (C1+C2)) & mask) since C1 != 0.
Chris Lattner344c7c52009-03-20 22:41:15 +00004305 if (AmtSum >= TypeBits)
4306 AmtSum = TypeBits-1;
4307
Chris Lattnerf925cbd2009-08-30 18:50:58 +00004308 Value *Shift = Builder->CreateAShr(X, ConstantInt::get(Ty, AmtSum));
Chris Lattnerb87056f2007-02-05 00:57:54 +00004309
Zhou Shenge9e03f62007-03-28 15:02:20 +00004310 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Chris Lattner4de84762010-01-04 07:02:48 +00004311 return BinaryOperator::CreateAnd(Shift,
4312 ConstantInt::get(I.getContext(), Mask));
Chris Lattnerad0124c2006-01-06 07:52:12 +00004313 }
4314
Chris Lattnerb87056f2007-02-05 00:57:54 +00004315 // Okay, if we get here, one shift must be left, and the other shift must be
4316 // right. See if the amounts are equal.
4317 if (ShiftAmt1 == ShiftAmt2) {
4318 // If we have ((X >>? C) << C), turn this into X & (-1 << C).
4319 if (I.getOpcode() == Instruction::Shl) {
Reid Spencer55702aa2007-03-25 21:11:44 +00004320 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt1));
Chris Lattner4de84762010-01-04 07:02:48 +00004321 return BinaryOperator::CreateAnd(X,
4322 ConstantInt::get(I.getContext(),Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00004323 }
4324 // If we have ((X << C) >>u C), turn this into X & (-1 >>u C).
4325 if (I.getOpcode() == Instruction::LShr) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00004326 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt1));
Chris Lattner4de84762010-01-04 07:02:48 +00004327 return BinaryOperator::CreateAnd(X,
4328 ConstantInt::get(I.getContext(), Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00004329 }
4330 // We can simplify ((X << C) >>s C) into a trunc + sext.
4331 // NOTE: we could do this for any C, but that would make 'unusual' integer
4332 // types. For now, just stick to ones well-supported by the code
4333 // generators.
4334 const Type *SExtType = 0;
4335 switch (Ty->getBitWidth() - ShiftAmt1) {
Zhou Shenge9e03f62007-03-28 15:02:20 +00004336 case 1 :
4337 case 8 :
4338 case 16 :
4339 case 32 :
4340 case 64 :
4341 case 128:
Chris Lattner4de84762010-01-04 07:02:48 +00004342 SExtType = IntegerType::get(I.getContext(),
4343 Ty->getBitWidth() - ShiftAmt1);
Zhou Shenge9e03f62007-03-28 15:02:20 +00004344 break;
Chris Lattnerb87056f2007-02-05 00:57:54 +00004345 default: break;
4346 }
Chris Lattnerf925cbd2009-08-30 18:50:58 +00004347 if (SExtType)
4348 return new SExtInst(Builder->CreateTrunc(X, SExtType, "sext"), Ty);
Chris Lattnerb87056f2007-02-05 00:57:54 +00004349 // Otherwise, we can't handle it yet.
4350 } else if (ShiftAmt1 < ShiftAmt2) {
Zhou Sheng4351c642007-04-02 08:20:41 +00004351 uint32_t ShiftDiff = ShiftAmt2-ShiftAmt1;
Chris Lattnerad0124c2006-01-06 07:52:12 +00004352
Chris Lattnerb0b991a2007-02-05 05:57:49 +00004353 // (X >>? C1) << C2 --> X << (C2-C1) & (-1 << C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00004354 if (I.getOpcode() == Instruction::Shl) {
4355 assert(ShiftOp->getOpcode() == Instruction::LShr ||
4356 ShiftOp->getOpcode() == Instruction::AShr);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00004357 Value *Shift = Builder->CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
Chris Lattnere8d56c52006-01-07 01:32:28 +00004358
Reid Spencer55702aa2007-03-25 21:11:44 +00004359 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersoneed707b2009-07-24 23:12:02 +00004360 return BinaryOperator::CreateAnd(Shift,
Chris Lattner4de84762010-01-04 07:02:48 +00004361 ConstantInt::get(I.getContext(),Mask));
Chris Lattnerad0124c2006-01-06 07:52:12 +00004362 }
Chris Lattnerb87056f2007-02-05 00:57:54 +00004363
Chris Lattnerb0b991a2007-02-05 05:57:49 +00004364 // (X << C1) >>u C2 --> X >>u (C2-C1) & (-1 >> C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00004365 if (I.getOpcode() == Instruction::LShr) {
4366 assert(ShiftOp->getOpcode() == Instruction::Shl);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00004367 Value *Shift = Builder->CreateLShr(X, ConstantInt::get(Ty, ShiftDiff));
Chris Lattnerad0124c2006-01-06 07:52:12 +00004368
Reid Spencerd5e30f02007-03-26 17:18:58 +00004369 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersoneed707b2009-07-24 23:12:02 +00004370 return BinaryOperator::CreateAnd(Shift,
Chris Lattner4de84762010-01-04 07:02:48 +00004371 ConstantInt::get(I.getContext(),Mask));
Chris Lattner11021cb2005-09-18 05:12:10 +00004372 }
Chris Lattnerb87056f2007-02-05 00:57:54 +00004373
4374 // We can't handle (X << C1) >>s C2, it shifts arbitrary bits in.
4375 } else {
4376 assert(ShiftAmt2 < ShiftAmt1);
Zhou Sheng4351c642007-04-02 08:20:41 +00004377 uint32_t ShiftDiff = ShiftAmt1-ShiftAmt2;
Chris Lattnerb87056f2007-02-05 00:57:54 +00004378
Chris Lattnerb0b991a2007-02-05 05:57:49 +00004379 // (X >>? C1) << C2 --> X >>? (C1-C2) & (-1 << C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00004380 if (I.getOpcode() == Instruction::Shl) {
4381 assert(ShiftOp->getOpcode() == Instruction::LShr ||
4382 ShiftOp->getOpcode() == Instruction::AShr);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00004383 Value *Shift = Builder->CreateBinOp(ShiftOp->getOpcode(), X,
4384 ConstantInt::get(Ty, ShiftDiff));
Chris Lattnerb87056f2007-02-05 00:57:54 +00004385
Reid Spencer55702aa2007-03-25 21:11:44 +00004386 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersoneed707b2009-07-24 23:12:02 +00004387 return BinaryOperator::CreateAnd(Shift,
Chris Lattner4de84762010-01-04 07:02:48 +00004388 ConstantInt::get(I.getContext(),Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00004389 }
4390
Chris Lattnerb0b991a2007-02-05 05:57:49 +00004391 // (X << C1) >>u C2 --> X << (C1-C2) & (-1 >> C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00004392 if (I.getOpcode() == Instruction::LShr) {
4393 assert(ShiftOp->getOpcode() == Instruction::Shl);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00004394 Value *Shift = Builder->CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
Chris Lattnerb87056f2007-02-05 00:57:54 +00004395
Reid Spencer68d27cf2007-03-26 23:45:51 +00004396 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersoneed707b2009-07-24 23:12:02 +00004397 return BinaryOperator::CreateAnd(Shift,
Chris Lattner4de84762010-01-04 07:02:48 +00004398 ConstantInt::get(I.getContext(),Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00004399 }
4400
4401 // We can't handle (X << C1) >>a C2, it shifts arbitrary bits in.
Chris Lattner6e7ba452005-01-01 16:22:27 +00004402 }
Chris Lattnerad0124c2006-01-06 07:52:12 +00004403 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00004404 return 0;
4405}
4406
Chris Lattnera1be5662002-05-02 17:06:02 +00004407
Chris Lattnercfd65102005-10-29 04:36:15 +00004408/// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
4409/// expression. If so, decompose it, returning some value X, such that Val is
4410/// X*Scale+Offset.
4411///
4412static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
Chris Lattner4de84762010-01-04 07:02:48 +00004413 int &Offset) {
4414 assert(Val->getType() == Type::getInt32Ty(Val->getContext()) &&
Chris Lattnerf925cbd2009-08-30 18:50:58 +00004415 "Unexpected allocation size type!");
Reid Spencerb83eb642006-10-20 07:07:24 +00004416 if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00004417 Offset = CI->getZExtValue();
Chris Lattner6a94de22007-10-12 05:30:59 +00004418 Scale = 0;
Chris Lattner4de84762010-01-04 07:02:48 +00004419 return ConstantInt::get(Type::getInt32Ty(Val->getContext()), 0);
Chris Lattner6a94de22007-10-12 05:30:59 +00004420 } else if (BinaryOperator *I = dyn_cast<BinaryOperator>(Val)) {
4421 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
4422 if (I->getOpcode() == Instruction::Shl) {
4423 // This is a value scaled by '1 << the shift amt'.
4424 Scale = 1U << RHS->getZExtValue();
4425 Offset = 0;
4426 return I->getOperand(0);
4427 } else if (I->getOpcode() == Instruction::Mul) {
4428 // This value is scaled by 'RHS'.
4429 Scale = RHS->getZExtValue();
4430 Offset = 0;
4431 return I->getOperand(0);
4432 } else if (I->getOpcode() == Instruction::Add) {
4433 // We have X+C. Check to see if we really have (X*C2)+C1,
4434 // where C1 is divisible by C2.
4435 unsigned SubScale;
4436 Value *SubVal =
Chris Lattner4de84762010-01-04 07:02:48 +00004437 DecomposeSimpleLinearExpr(I->getOperand(0), SubScale, Offset);
Chris Lattner6a94de22007-10-12 05:30:59 +00004438 Offset += RHS->getZExtValue();
4439 Scale = SubScale;
4440 return SubVal;
Chris Lattnercfd65102005-10-29 04:36:15 +00004441 }
4442 }
4443 }
4444
4445 // Otherwise, we can't look past this.
4446 Scale = 1;
4447 Offset = 0;
4448 return Val;
4449}
4450
4451
Chris Lattnerb3f83972005-10-24 06:03:58 +00004452/// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
4453/// try to eliminate the cast by moving the type information into the alloc.
Chris Lattnerd3e28342007-04-27 17:44:50 +00004454Instruction *InstCombiner::PromoteCastOfAllocation(BitCastInst &CI,
Victor Hernandez7b929da2009-10-23 21:09:37 +00004455 AllocaInst &AI) {
Chris Lattnerd3e28342007-04-27 17:44:50 +00004456 const PointerType *PTy = cast<PointerType>(CI.getType());
Chris Lattnerb3f83972005-10-24 06:03:58 +00004457
Chris Lattnerf925cbd2009-08-30 18:50:58 +00004458 BuilderTy AllocaBuilder(*Builder);
4459 AllocaBuilder.SetInsertPoint(AI.getParent(), &AI);
4460
Chris Lattnerb53c2382005-10-24 06:22:12 +00004461 // Remove any uses of AI that are dead.
4462 assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
Chris Lattner535014f2007-02-15 22:52:10 +00004463
Chris Lattnerb53c2382005-10-24 06:22:12 +00004464 for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
4465 Instruction *User = cast<Instruction>(*UI++);
4466 if (isInstructionTriviallyDead(User)) {
4467 while (UI != E && *UI == User)
4468 ++UI; // If this instruction uses AI more than once, don't break UI.
4469
Chris Lattnerb53c2382005-10-24 06:22:12 +00004470 ++NumDeadInst;
Chris Lattnerbdff5482009-08-23 04:37:46 +00004471 DEBUG(errs() << "IC: DCE: " << *User << '\n');
Chris Lattnerf22a5c62007-03-02 19:59:19 +00004472 EraseInstFromFunction(*User);
Chris Lattnerb53c2382005-10-24 06:22:12 +00004473 }
4474 }
Dan Gohmance9fe9f2009-07-21 23:21:54 +00004475
4476 // This requires TargetData to get the alloca alignment and size information.
4477 if (!TD) return 0;
4478
Chris Lattnerb3f83972005-10-24 06:03:58 +00004479 // Get the type really allocated and the type casted to.
4480 const Type *AllocElTy = AI.getAllocatedType();
4481 const Type *CastElTy = PTy->getElementType();
4482 if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
Chris Lattner18e78bb2005-10-24 06:26:18 +00004483
Chris Lattnerd2b7cec2007-02-14 05:52:17 +00004484 unsigned AllocElTyAlign = TD->getABITypeAlignment(AllocElTy);
4485 unsigned CastElTyAlign = TD->getABITypeAlignment(CastElTy);
Chris Lattner18e78bb2005-10-24 06:26:18 +00004486 if (CastElTyAlign < AllocElTyAlign) return 0;
4487
Chris Lattner39387a52005-10-24 06:35:18 +00004488 // If the allocation has multiple uses, only promote it if we are strictly
4489 // increasing the alignment of the resultant allocation. If we keep it the
Dale Johannesena0a66372009-03-05 00:39:02 +00004490 // same, we open the door to infinite loops of various kinds. (A reference
4491 // from a dbg.declare doesn't count as a use for this purpose.)
4492 if (!AI.hasOneUse() && !hasOneUsePlusDeclare(&AI) &&
4493 CastElTyAlign == AllocElTyAlign) return 0;
Chris Lattner39387a52005-10-24 06:35:18 +00004494
Duncan Sands777d2302009-05-09 07:06:46 +00004495 uint64_t AllocElTySize = TD->getTypeAllocSize(AllocElTy);
4496 uint64_t CastElTySize = TD->getTypeAllocSize(CastElTy);
Chris Lattner0ddac2a2005-10-27 05:53:56 +00004497 if (CastElTySize == 0 || AllocElTySize == 0) return 0;
Chris Lattner18e78bb2005-10-24 06:26:18 +00004498
Chris Lattner455fcc82005-10-29 03:19:53 +00004499 // See if we can satisfy the modulus by pulling a scale out of the array
4500 // size argument.
Jeff Cohen86796be2007-04-04 16:58:57 +00004501 unsigned ArraySizeScale;
4502 int ArrayOffset;
Chris Lattnercfd65102005-10-29 04:36:15 +00004503 Value *NumElements = // See if the array size is a decomposable linear expr.
Chris Lattner4de84762010-01-04 07:02:48 +00004504 DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale, ArrayOffset);
Chris Lattnercfd65102005-10-29 04:36:15 +00004505
Chris Lattner455fcc82005-10-29 03:19:53 +00004506 // If we can now satisfy the modulus, by using a non-1 scale, we really can
4507 // do the xform.
Chris Lattnercfd65102005-10-29 04:36:15 +00004508 if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
4509 (AllocElTySize*ArrayOffset ) % CastElTySize != 0) return 0;
Chris Lattner8142b0a2005-10-27 06:12:00 +00004510
Chris Lattner455fcc82005-10-29 03:19:53 +00004511 unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
4512 Value *Amt = 0;
4513 if (Scale == 1) {
4514 Amt = NumElements;
4515 } else {
Chris Lattner4de84762010-01-04 07:02:48 +00004516 Amt = ConstantInt::get(Type::getInt32Ty(CI.getContext()), Scale);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00004517 // Insert before the alloca, not before the cast.
4518 Amt = AllocaBuilder.CreateMul(Amt, NumElements, "tmp");
Chris Lattner0ddac2a2005-10-27 05:53:56 +00004519 }
4520
Jeff Cohen86796be2007-04-04 16:58:57 +00004521 if (int Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
Chris Lattner4de84762010-01-04 07:02:48 +00004522 Value *Off = ConstantInt::get(Type::getInt32Ty(CI.getContext()),
4523 Offset, true);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00004524 Amt = AllocaBuilder.CreateAdd(Amt, Off, "tmp");
Chris Lattnercfd65102005-10-29 04:36:15 +00004525 }
4526
Victor Hernandez7b929da2009-10-23 21:09:37 +00004527 AllocaInst *New = AllocaBuilder.CreateAlloca(CastElTy, Amt);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00004528 New->setAlignment(AI.getAlignment());
Chris Lattner6934a042007-02-11 01:23:03 +00004529 New->takeName(&AI);
Chris Lattner39387a52005-10-24 06:35:18 +00004530
Dale Johannesena0a66372009-03-05 00:39:02 +00004531 // If the allocation has one real use plus a dbg.declare, just remove the
4532 // declare.
4533 if (DbgDeclareInst *DI = hasOneUsePlusDeclare(&AI)) {
4534 EraseInstFromFunction(*DI);
4535 }
4536 // If the allocation has multiple real uses, insert a cast and change all
4537 // things that used it to use the new cast. This will also hack on CI, but it
4538 // will die soon.
4539 else if (!AI.hasOneUse()) {
Reid Spencer3da59db2006-11-27 01:05:10 +00004540 // New is the allocation instruction, pointer typed. AI is the original
4541 // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
Chris Lattnerf925cbd2009-08-30 18:50:58 +00004542 Value *NewCast = AllocaBuilder.CreateBitCast(New, AI.getType(), "tmpcast");
Chris Lattner39387a52005-10-24 06:35:18 +00004543 AI.replaceAllUsesWith(NewCast);
4544 }
Chris Lattnerb3f83972005-10-24 06:03:58 +00004545 return ReplaceInstUsesWith(CI, New);
4546}
4547
Chris Lattner70074e02006-05-13 02:06:03 +00004548/// CanEvaluateInDifferentType - Return true if we can take the specified value
Chris Lattnerc739cd62007-03-03 05:27:34 +00004549/// and return it as type Ty without inserting any new casts and without
4550/// changing the computed value. This is used by code that tries to decide
4551/// whether promoting or shrinking integer operations to wider or smaller types
4552/// will allow us to eliminate a truncate or extend.
4553///
4554/// This is a truncation operation if Ty is smaller than V->getType(), or an
4555/// extension operation if Ty is larger.
Chris Lattner8114b712008-06-18 04:00:49 +00004556///
4557/// If CastOpc is a truncation, then Ty will be a type smaller than V. We
4558/// should return true if trunc(V) can be computed by computing V in the smaller
4559/// type. If V is an instruction, then trunc(inst(x,y)) can be computed as
4560/// inst(trunc(x),trunc(y)), which only makes sense if x and y can be
4561/// efficiently truncated.
4562///
4563/// If CastOpc is a sext or zext, we are asking if the low bits of the value can
4564/// bit computed in a larger type, which is then and'd or sext_in_reg'd to get
4565/// the final result.
Dan Gohman6de29f82009-06-15 22:12:54 +00004566bool InstCombiner::CanEvaluateInDifferentType(Value *V, const Type *Ty,
Evan Cheng4e56ab22009-01-16 02:11:43 +00004567 unsigned CastOpc,
4568 int &NumCastsRemoved){
Chris Lattnerc739cd62007-03-03 05:27:34 +00004569 // We can always evaluate constants in another type.
Dan Gohman6de29f82009-06-15 22:12:54 +00004570 if (isa<Constant>(V))
Chris Lattnerc739cd62007-03-03 05:27:34 +00004571 return true;
Chris Lattner70074e02006-05-13 02:06:03 +00004572
4573 Instruction *I = dyn_cast<Instruction>(V);
Chris Lattnerc739cd62007-03-03 05:27:34 +00004574 if (!I) return false;
4575
Dan Gohman6de29f82009-06-15 22:12:54 +00004576 const Type *OrigTy = V->getType();
Chris Lattner70074e02006-05-13 02:06:03 +00004577
Chris Lattner951626b2007-08-02 06:11:14 +00004578 // If this is an extension or truncate, we can often eliminate it.
4579 if (isa<TruncInst>(I) || isa<ZExtInst>(I) || isa<SExtInst>(I)) {
4580 // If this is a cast from the destination type, we can trivially eliminate
4581 // it, and this will remove a cast overall.
4582 if (I->getOperand(0)->getType() == Ty) {
4583 // If the first operand is itself a cast, and is eliminable, do not count
4584 // this as an eliminable cast. We would prefer to eliminate those two
4585 // casts first.
Chris Lattner8114b712008-06-18 04:00:49 +00004586 if (!isa<CastInst>(I->getOperand(0)) && I->hasOneUse())
Chris Lattner951626b2007-08-02 06:11:14 +00004587 ++NumCastsRemoved;
4588 return true;
4589 }
4590 }
4591
4592 // We can't extend or shrink something that has multiple uses: doing so would
4593 // require duplicating the instruction in general, which isn't profitable.
4594 if (!I->hasOneUse()) return false;
4595
Evan Chengf35fd542009-01-15 17:01:23 +00004596 unsigned Opc = I->getOpcode();
4597 switch (Opc) {
Chris Lattnerc739cd62007-03-03 05:27:34 +00004598 case Instruction::Add:
4599 case Instruction::Sub:
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00004600 case Instruction::Mul:
Chris Lattner70074e02006-05-13 02:06:03 +00004601 case Instruction::And:
4602 case Instruction::Or:
4603 case Instruction::Xor:
4604 // These operators can all arbitrarily be extended or truncated.
Chris Lattner951626b2007-08-02 06:11:14 +00004605 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00004606 NumCastsRemoved) &&
Chris Lattner951626b2007-08-02 06:11:14 +00004607 CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00004608 NumCastsRemoved);
Chris Lattnerc739cd62007-03-03 05:27:34 +00004609
Eli Friedman070a9812009-07-13 22:46:01 +00004610 case Instruction::UDiv:
4611 case Instruction::URem: {
4612 // UDiv and URem can be truncated if all the truncated bits are zero.
4613 uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
4614 uint32_t BitWidth = Ty->getScalarSizeInBits();
4615 if (BitWidth < OrigBitWidth) {
4616 APInt Mask = APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth);
4617 if (MaskedValueIsZero(I->getOperand(0), Mask) &&
4618 MaskedValueIsZero(I->getOperand(1), Mask)) {
4619 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
4620 NumCastsRemoved) &&
4621 CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
4622 NumCastsRemoved);
4623 }
4624 }
4625 break;
4626 }
Chris Lattner46b96052006-11-29 07:18:39 +00004627 case Instruction::Shl:
Chris Lattnerc739cd62007-03-03 05:27:34 +00004628 // If we are truncating the result of this SHL, and if it's a shift of a
4629 // constant amount, we can always perform a SHL in a smaller type.
4630 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
Dan Gohman6de29f82009-06-15 22:12:54 +00004631 uint32_t BitWidth = Ty->getScalarSizeInBits();
4632 if (BitWidth < OrigTy->getScalarSizeInBits() &&
Zhou Sheng302748d2007-03-30 17:20:39 +00004633 CI->getLimitedValue(BitWidth) < BitWidth)
Chris Lattner951626b2007-08-02 06:11:14 +00004634 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00004635 NumCastsRemoved);
Chris Lattnerc739cd62007-03-03 05:27:34 +00004636 }
4637 break;
4638 case Instruction::LShr:
Chris Lattnerc739cd62007-03-03 05:27:34 +00004639 // If this is a truncate of a logical shr, we can truncate it to a smaller
4640 // lshr iff we know that the bits we would otherwise be shifting in are
4641 // already zeros.
4642 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
Dan Gohman6de29f82009-06-15 22:12:54 +00004643 uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
4644 uint32_t BitWidth = Ty->getScalarSizeInBits();
Zhou Sheng302748d2007-03-30 17:20:39 +00004645 if (BitWidth < OrigBitWidth &&
Chris Lattnerc739cd62007-03-03 05:27:34 +00004646 MaskedValueIsZero(I->getOperand(0),
Zhou Sheng302748d2007-03-30 17:20:39 +00004647 APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth)) &&
4648 CI->getLimitedValue(BitWidth) < BitWidth) {
Chris Lattner951626b2007-08-02 06:11:14 +00004649 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00004650 NumCastsRemoved);
Chris Lattnerc739cd62007-03-03 05:27:34 +00004651 }
4652 }
Chris Lattner46b96052006-11-29 07:18:39 +00004653 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00004654 case Instruction::ZExt:
4655 case Instruction::SExt:
Chris Lattner951626b2007-08-02 06:11:14 +00004656 case Instruction::Trunc:
4657 // If this is the same kind of case as our original (e.g. zext+zext), we
Chris Lattner5543a852007-08-02 17:23:38 +00004658 // can safely replace it. Note that replacing it does not reduce the number
4659 // of casts in the input.
Evan Chengf35fd542009-01-15 17:01:23 +00004660 if (Opc == CastOpc)
4661 return true;
4662
4663 // sext (zext ty1), ty2 -> zext ty2
Evan Cheng661d9c32009-01-15 17:09:07 +00004664 if (CastOpc == Instruction::SExt && Opc == Instruction::ZExt)
Chris Lattner70074e02006-05-13 02:06:03 +00004665 return true;
Reid Spencer3da59db2006-11-27 01:05:10 +00004666 break;
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00004667 case Instruction::Select: {
4668 SelectInst *SI = cast<SelectInst>(I);
4669 return CanEvaluateInDifferentType(SI->getTrueValue(), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00004670 NumCastsRemoved) &&
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00004671 CanEvaluateInDifferentType(SI->getFalseValue(), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00004672 NumCastsRemoved);
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00004673 }
Chris Lattner8114b712008-06-18 04:00:49 +00004674 case Instruction::PHI: {
4675 // We can change a phi if we can change all operands.
4676 PHINode *PN = cast<PHINode>(I);
4677 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
4678 if (!CanEvaluateInDifferentType(PN->getIncomingValue(i), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00004679 NumCastsRemoved))
Chris Lattner8114b712008-06-18 04:00:49 +00004680 return false;
4681 return true;
4682 }
Reid Spencer3da59db2006-11-27 01:05:10 +00004683 default:
Chris Lattner70074e02006-05-13 02:06:03 +00004684 // TODO: Can handle more cases here.
4685 break;
4686 }
4687
4688 return false;
4689}
4690
4691/// EvaluateInDifferentType - Given an expression that
4692/// CanEvaluateInDifferentType returns true for, actually insert the code to
4693/// evaluate the expression.
Reid Spencerc55b2432006-12-13 18:21:21 +00004694Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty,
Chris Lattnerc739cd62007-03-03 05:27:34 +00004695 bool isSigned) {
Chris Lattner70074e02006-05-13 02:06:03 +00004696 if (Constant *C = dyn_cast<Constant>(V))
Chris Lattner9956c052009-11-08 19:23:30 +00004697 return ConstantExpr::getIntegerCast(C, Ty, isSigned /*Sext or ZExt*/);
Chris Lattner70074e02006-05-13 02:06:03 +00004698
4699 // Otherwise, it must be an instruction.
4700 Instruction *I = cast<Instruction>(V);
Chris Lattner01859e82006-05-20 23:14:03 +00004701 Instruction *Res = 0;
Evan Chengf35fd542009-01-15 17:01:23 +00004702 unsigned Opc = I->getOpcode();
4703 switch (Opc) {
Chris Lattnerc739cd62007-03-03 05:27:34 +00004704 case Instruction::Add:
4705 case Instruction::Sub:
Nick Lewyckye6b0c002008-01-22 05:08:48 +00004706 case Instruction::Mul:
Chris Lattner70074e02006-05-13 02:06:03 +00004707 case Instruction::And:
4708 case Instruction::Or:
Chris Lattnerc739cd62007-03-03 05:27:34 +00004709 case Instruction::Xor:
Chris Lattner46b96052006-11-29 07:18:39 +00004710 case Instruction::AShr:
4711 case Instruction::LShr:
Eli Friedman070a9812009-07-13 22:46:01 +00004712 case Instruction::Shl:
4713 case Instruction::UDiv:
4714 case Instruction::URem: {
Reid Spencerc55b2432006-12-13 18:21:21 +00004715 Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
Chris Lattnerc739cd62007-03-03 05:27:34 +00004716 Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
Evan Chengf35fd542009-01-15 17:01:23 +00004717 Res = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
Chris Lattner46b96052006-11-29 07:18:39 +00004718 break;
4719 }
Reid Spencer3da59db2006-11-27 01:05:10 +00004720 case Instruction::Trunc:
4721 case Instruction::ZExt:
4722 case Instruction::SExt:
Reid Spencer3da59db2006-11-27 01:05:10 +00004723 // If the source type of the cast is the type we're trying for then we can
Chris Lattner951626b2007-08-02 06:11:14 +00004724 // just return the source. There's no need to insert it because it is not
4725 // new.
Chris Lattner70074e02006-05-13 02:06:03 +00004726 if (I->getOperand(0)->getType() == Ty)
4727 return I->getOperand(0);
4728
Chris Lattner8114b712008-06-18 04:00:49 +00004729 // Otherwise, must be the same type of cast, so just reinsert a new one.
Chris Lattner9956c052009-11-08 19:23:30 +00004730 Res = CastInst::Create(cast<CastInst>(I)->getOpcode(), I->getOperand(0),Ty);
Chris Lattner951626b2007-08-02 06:11:14 +00004731 break;
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00004732 case Instruction::Select: {
4733 Value *True = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
4734 Value *False = EvaluateInDifferentType(I->getOperand(2), Ty, isSigned);
4735 Res = SelectInst::Create(I->getOperand(0), True, False);
4736 break;
4737 }
Chris Lattner8114b712008-06-18 04:00:49 +00004738 case Instruction::PHI: {
4739 PHINode *OPN = cast<PHINode>(I);
4740 PHINode *NPN = PHINode::Create(Ty);
4741 for (unsigned i = 0, e = OPN->getNumIncomingValues(); i != e; ++i) {
4742 Value *V =EvaluateInDifferentType(OPN->getIncomingValue(i), Ty, isSigned);
4743 NPN->addIncoming(V, OPN->getIncomingBlock(i));
4744 }
4745 Res = NPN;
4746 break;
4747 }
Reid Spencer3da59db2006-11-27 01:05:10 +00004748 default:
Chris Lattner70074e02006-05-13 02:06:03 +00004749 // TODO: Can handle more cases here.
Torok Edwinc23197a2009-07-14 16:55:14 +00004750 llvm_unreachable("Unreachable!");
Chris Lattner70074e02006-05-13 02:06:03 +00004751 break;
4752 }
4753
Chris Lattner8114b712008-06-18 04:00:49 +00004754 Res->takeName(I);
Chris Lattner70074e02006-05-13 02:06:03 +00004755 return InsertNewInstBefore(Res, *I);
4756}
4757
Reid Spencer3da59db2006-11-27 01:05:10 +00004758/// @brief Implement the transforms common to all CastInst visitors.
4759Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
Chris Lattner79d35b32003-06-23 21:59:52 +00004760 Value *Src = CI.getOperand(0);
4761
Dan Gohman23d9d272007-05-11 21:10:54 +00004762 // Many cases of "cast of a cast" are eliminable. If it's eliminable we just
Reid Spencer3da59db2006-11-27 01:05:10 +00004763 // eliminate it now.
Chris Lattner6e7ba452005-01-01 16:22:27 +00004764 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
Reid Spencer3da59db2006-11-27 01:05:10 +00004765 if (Instruction::CastOps opc =
4766 isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
4767 // The first cast (CSrc) is eliminable so we need to fix up or replace
4768 // the second cast (CI). CSrc will then have a good chance of being dead.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004769 return CastInst::Create(opc, CSrc->getOperand(0), CI.getType());
Chris Lattner8fd217c2002-08-02 20:00:25 +00004770 }
4771 }
Chris Lattnera710ddc2004-05-25 04:29:21 +00004772
Reid Spencer3da59db2006-11-27 01:05:10 +00004773 // If we are casting a select then fold the cast into the select
Chris Lattner6e7ba452005-01-01 16:22:27 +00004774 if (SelectInst *SI = dyn_cast<SelectInst>(Src))
4775 if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
4776 return NV;
Reid Spencer3da59db2006-11-27 01:05:10 +00004777
4778 // If we are casting a PHI then fold the cast into the PHI
Chris Lattner9956c052009-11-08 19:23:30 +00004779 if (isa<PHINode>(Src)) {
4780 // We don't do this if this would create a PHI node with an illegal type if
4781 // it is currently legal.
4782 if (!isa<IntegerType>(Src->getType()) ||
4783 !isa<IntegerType>(CI.getType()) ||
Chris Lattnerc22d4d12009-11-10 07:23:37 +00004784 ShouldChangeType(CI.getType(), Src->getType(), TD))
Chris Lattner9956c052009-11-08 19:23:30 +00004785 if (Instruction *NV = FoldOpIntoPhi(CI))
4786 return NV;
Chris Lattner9956c052009-11-08 19:23:30 +00004787 }
Chris Lattner9fb92132006-04-12 18:09:35 +00004788
Reid Spencer3da59db2006-11-27 01:05:10 +00004789 return 0;
4790}
4791
Chris Lattner46cd5a12009-01-09 05:44:56 +00004792/// FindElementAtOffset - Given a type and a constant offset, determine whether
4793/// or not there is a sequence of GEP indices into the type that will land us at
Chris Lattner3914f722009-01-24 01:00:13 +00004794/// the specified offset. If so, fill them into NewIndices and return the
4795/// resultant element type, otherwise return null.
4796static const Type *FindElementAtOffset(const Type *Ty, int64_t Offset,
4797 SmallVectorImpl<Value*> &NewIndices,
Chris Lattner4de84762010-01-04 07:02:48 +00004798 const TargetData *TD) {
Dan Gohmance9fe9f2009-07-21 23:21:54 +00004799 if (!TD) return 0;
Chris Lattner3914f722009-01-24 01:00:13 +00004800 if (!Ty->isSized()) return 0;
Chris Lattner46cd5a12009-01-09 05:44:56 +00004801
4802 // Start with the index over the outer type. Note that the type size
4803 // might be zero (even if the offset isn't zero) if the indexed type
4804 // is something like [0 x {int, int}]
Chris Lattner4de84762010-01-04 07:02:48 +00004805 const Type *IntPtrTy = TD->getIntPtrType(Ty->getContext());
Chris Lattner46cd5a12009-01-09 05:44:56 +00004806 int64_t FirstIdx = 0;
Duncan Sands777d2302009-05-09 07:06:46 +00004807 if (int64_t TySize = TD->getTypeAllocSize(Ty)) {
Chris Lattner46cd5a12009-01-09 05:44:56 +00004808 FirstIdx = Offset/TySize;
Chris Lattner31a69cb2009-01-11 20:41:36 +00004809 Offset -= FirstIdx*TySize;
Chris Lattner46cd5a12009-01-09 05:44:56 +00004810
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00004811 // Handle hosts where % returns negative instead of values [0..TySize).
Chris Lattner46cd5a12009-01-09 05:44:56 +00004812 if (Offset < 0) {
4813 --FirstIdx;
4814 Offset += TySize;
4815 assert(Offset >= 0);
4816 }
4817 assert((uint64_t)Offset < (uint64_t)TySize && "Out of range offset");
4818 }
4819
Owen Andersoneed707b2009-07-24 23:12:02 +00004820 NewIndices.push_back(ConstantInt::get(IntPtrTy, FirstIdx));
Chris Lattner46cd5a12009-01-09 05:44:56 +00004821
4822 // Index into the types. If we fail, set OrigBase to null.
4823 while (Offset) {
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00004824 // Indexing into tail padding between struct/array elements.
4825 if (uint64_t(Offset*8) >= TD->getTypeSizeInBits(Ty))
Chris Lattner3914f722009-01-24 01:00:13 +00004826 return 0;
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00004827
Chris Lattner46cd5a12009-01-09 05:44:56 +00004828 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
4829 const StructLayout *SL = TD->getStructLayout(STy);
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00004830 assert(Offset < (int64_t)SL->getSizeInBytes() &&
4831 "Offset must stay within the indexed type");
4832
Chris Lattner46cd5a12009-01-09 05:44:56 +00004833 unsigned Elt = SL->getElementContainingOffset(Offset);
Chris Lattner4de84762010-01-04 07:02:48 +00004834 NewIndices.push_back(ConstantInt::get(Type::getInt32Ty(Ty->getContext()),
4835 Elt));
Chris Lattner46cd5a12009-01-09 05:44:56 +00004836
4837 Offset -= SL->getElementOffset(Elt);
4838 Ty = STy->getElementType(Elt);
Chris Lattner1c412d92009-01-11 20:23:52 +00004839 } else if (const ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
Duncan Sands777d2302009-05-09 07:06:46 +00004840 uint64_t EltSize = TD->getTypeAllocSize(AT->getElementType());
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00004841 assert(EltSize && "Cannot index into a zero-sized array");
Owen Andersoneed707b2009-07-24 23:12:02 +00004842 NewIndices.push_back(ConstantInt::get(IntPtrTy,Offset/EltSize));
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00004843 Offset %= EltSize;
Chris Lattner1c412d92009-01-11 20:23:52 +00004844 Ty = AT->getElementType();
Chris Lattner46cd5a12009-01-09 05:44:56 +00004845 } else {
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00004846 // Otherwise, we can't index into the middle of this atomic type, bail.
Chris Lattner3914f722009-01-24 01:00:13 +00004847 return 0;
Chris Lattner46cd5a12009-01-09 05:44:56 +00004848 }
4849 }
4850
Chris Lattner3914f722009-01-24 01:00:13 +00004851 return Ty;
Chris Lattner46cd5a12009-01-09 05:44:56 +00004852}
4853
Chris Lattnerd3e28342007-04-27 17:44:50 +00004854/// @brief Implement the transforms for cast of pointer (bitcast/ptrtoint)
4855Instruction *InstCombiner::commonPointerCastTransforms(CastInst &CI) {
4856 Value *Src = CI.getOperand(0);
4857
Chris Lattnerd3e28342007-04-27 17:44:50 +00004858 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
Chris Lattner9bc14642007-04-28 00:57:34 +00004859 // If casting the result of a getelementptr instruction with no offset, turn
4860 // this into a cast of the original pointer!
Chris Lattnerd3e28342007-04-27 17:44:50 +00004861 if (GEP->hasAllZeroIndices()) {
4862 // Changing the cast operand is usually not a good idea but it is safe
4863 // here because the pointer operand is being replaced with another
4864 // pointer operand so the opcode doesn't need to change.
Chris Lattner7a1e9242009-08-30 06:13:40 +00004865 Worklist.Add(GEP);
Chris Lattnerd3e28342007-04-27 17:44:50 +00004866 CI.setOperand(0, GEP->getOperand(0));
4867 return &CI;
4868 }
Chris Lattner9bc14642007-04-28 00:57:34 +00004869
4870 // If the GEP has a single use, and the base pointer is a bitcast, and the
4871 // GEP computes a constant offset, see if we can convert these three
4872 // instructions into fewer. This typically happens with unions and other
4873 // non-type-safe code.
Dan Gohmance9fe9f2009-07-21 23:21:54 +00004874 if (TD && GEP->hasOneUse() && isa<BitCastInst>(GEP->getOperand(0))) {
Chris Lattner9bc14642007-04-28 00:57:34 +00004875 if (GEP->hasAllConstantIndices()) {
4876 // We are guaranteed to get a constant from EmitGEPOffset.
Chris Lattner02446fc2010-01-04 07:37:31 +00004877 ConstantInt *OffsetV = cast<ConstantInt>(EmitGEPOffset(GEP));
Chris Lattner9bc14642007-04-28 00:57:34 +00004878 int64_t Offset = OffsetV->getSExtValue();
4879
4880 // Get the base pointer input of the bitcast, and the type it points to.
4881 Value *OrigBase = cast<BitCastInst>(GEP->getOperand(0))->getOperand(0);
4882 const Type *GEPIdxTy =
4883 cast<PointerType>(OrigBase->getType())->getElementType();
Chris Lattner46cd5a12009-01-09 05:44:56 +00004884 SmallVector<Value*, 8> NewIndices;
Chris Lattner4de84762010-01-04 07:02:48 +00004885 if (FindElementAtOffset(GEPIdxTy, Offset, NewIndices, TD)) {
Chris Lattner46cd5a12009-01-09 05:44:56 +00004886 // If we were able to index down into an element, create the GEP
4887 // and bitcast the result. This eliminates one bitcast, potentially
4888 // two.
Dan Gohmanf8dbee72009-09-07 23:54:19 +00004889 Value *NGEP = cast<GEPOperator>(GEP)->isInBounds() ?
4890 Builder->CreateInBoundsGEP(OrigBase,
4891 NewIndices.begin(), NewIndices.end()) :
4892 Builder->CreateGEP(OrigBase, NewIndices.begin(), NewIndices.end());
Chris Lattner46cd5a12009-01-09 05:44:56 +00004893 NGEP->takeName(GEP);
Chris Lattner9bc14642007-04-28 00:57:34 +00004894
Chris Lattner46cd5a12009-01-09 05:44:56 +00004895 if (isa<BitCastInst>(CI))
4896 return new BitCastInst(NGEP, CI.getType());
4897 assert(isa<PtrToIntInst>(CI));
4898 return new PtrToIntInst(NGEP, CI.getType());
Chris Lattner9bc14642007-04-28 00:57:34 +00004899 }
4900 }
4901 }
Chris Lattnerd3e28342007-04-27 17:44:50 +00004902 }
4903
4904 return commonCastTransforms(CI);
4905}
4906
Eli Friedmaneb7f7a82009-07-13 20:58:59 +00004907/// commonIntCastTransforms - This function implements the common transforms
4908/// for trunc, zext, and sext.
Reid Spencer3da59db2006-11-27 01:05:10 +00004909Instruction *InstCombiner::commonIntCastTransforms(CastInst &CI) {
4910 if (Instruction *Result = commonCastTransforms(CI))
4911 return Result;
4912
4913 Value *Src = CI.getOperand(0);
4914 const Type *SrcTy = Src->getType();
4915 const Type *DestTy = CI.getType();
Dan Gohman6de29f82009-06-15 22:12:54 +00004916 uint32_t SrcBitSize = SrcTy->getScalarSizeInBits();
4917 uint32_t DestBitSize = DestTy->getScalarSizeInBits();
Reid Spencer3da59db2006-11-27 01:05:10 +00004918
Reid Spencer3da59db2006-11-27 01:05:10 +00004919 // See if we can simplify any instructions used by the LHS whose sole
4920 // purpose is to compute bits we don't care about.
Chris Lattner886ab6c2009-01-31 08:15:18 +00004921 if (SimplifyDemandedInstructionBits(CI))
Reid Spencer3da59db2006-11-27 01:05:10 +00004922 return &CI;
4923
4924 // If the source isn't an instruction or has more than one use then we
4925 // can't do anything more.
Reid Spencere4d87aa2006-12-23 06:05:41 +00004926 Instruction *SrcI = dyn_cast<Instruction>(Src);
4927 if (!SrcI || !Src->hasOneUse())
Reid Spencer3da59db2006-11-27 01:05:10 +00004928 return 0;
4929
Chris Lattnerc739cd62007-03-03 05:27:34 +00004930 // Attempt to propagate the cast into the instruction for int->int casts.
Reid Spencer3da59db2006-11-27 01:05:10 +00004931 int NumCastsRemoved = 0;
Eli Friedman65445c52009-07-13 21:45:57 +00004932 // Only do this if the dest type is a simple type, don't convert the
4933 // expression tree to something weird like i93 unless the source is also
4934 // strange.
Chris Lattner6b583912009-11-10 17:00:47 +00004935 if ((isa<VectorType>(DestTy) ||
4936 ShouldChangeType(SrcI->getType(), DestTy, TD)) &&
4937 CanEvaluateInDifferentType(SrcI, DestTy,
4938 CI.getOpcode(), NumCastsRemoved)) {
Reid Spencer3da59db2006-11-27 01:05:10 +00004939 // If this cast is a truncate, evaluting in a different type always
Chris Lattner951626b2007-08-02 06:11:14 +00004940 // eliminates the cast, so it is always a win. If this is a zero-extension,
4941 // we need to do an AND to maintain the clear top-part of the computation,
4942 // so we require that the input have eliminated at least one cast. If this
4943 // is a sign extension, we insert two new casts (to do the extension) so we
Reid Spencer3da59db2006-11-27 01:05:10 +00004944 // require that two casts have been eliminated.
Evan Chengf35fd542009-01-15 17:01:23 +00004945 bool DoXForm = false;
4946 bool JustReplace = false;
Chris Lattnerc739cd62007-03-03 05:27:34 +00004947 switch (CI.getOpcode()) {
4948 default:
4949 // All the others use floating point so we shouldn't actually
4950 // get here because of the check above.
Torok Edwinc23197a2009-07-14 16:55:14 +00004951 llvm_unreachable("Unknown cast type");
Chris Lattnerc739cd62007-03-03 05:27:34 +00004952 case Instruction::Trunc:
4953 DoXForm = true;
4954 break;
Evan Cheng4e56ab22009-01-16 02:11:43 +00004955 case Instruction::ZExt: {
Chris Lattnerc739cd62007-03-03 05:27:34 +00004956 DoXForm = NumCastsRemoved >= 1;
Chris Lattner918871e2009-11-07 19:11:46 +00004957
Chris Lattner39c27ed2009-01-31 19:05:27 +00004958 if (!DoXForm && 0) {
Evan Cheng4e56ab22009-01-16 02:11:43 +00004959 // If it's unnecessary to issue an AND to clear the high bits, it's
4960 // always profitable to do this xform.
Chris Lattner39c27ed2009-01-31 19:05:27 +00004961 Value *TryRes = EvaluateInDifferentType(SrcI, DestTy, false);
Evan Cheng4e56ab22009-01-16 02:11:43 +00004962 APInt Mask(APInt::getBitsSet(DestBitSize, SrcBitSize, DestBitSize));
4963 if (MaskedValueIsZero(TryRes, Mask))
4964 return ReplaceInstUsesWith(CI, TryRes);
Chris Lattner39c27ed2009-01-31 19:05:27 +00004965
4966 if (Instruction *TryI = dyn_cast<Instruction>(TryRes))
Evan Cheng4e56ab22009-01-16 02:11:43 +00004967 if (TryI->use_empty())
4968 EraseInstFromFunction(*TryI);
4969 }
Chris Lattnerc739cd62007-03-03 05:27:34 +00004970 break;
Evan Cheng4e56ab22009-01-16 02:11:43 +00004971 }
Evan Chengf35fd542009-01-15 17:01:23 +00004972 case Instruction::SExt: {
Chris Lattnerc739cd62007-03-03 05:27:34 +00004973 DoXForm = NumCastsRemoved >= 2;
Chris Lattner39c27ed2009-01-31 19:05:27 +00004974 if (!DoXForm && !isa<TruncInst>(SrcI) && 0) {
Evan Cheng4e56ab22009-01-16 02:11:43 +00004975 // If we do not have to emit the truncate + sext pair, then it's always
4976 // profitable to do this xform.
Evan Chengf35fd542009-01-15 17:01:23 +00004977 //
4978 // It's not safe to eliminate the trunc + sext pair if one of the
4979 // eliminated cast is a truncate. e.g.
4980 // t2 = trunc i32 t1 to i16
4981 // t3 = sext i16 t2 to i32
4982 // !=
4983 // i32 t1
Chris Lattner39c27ed2009-01-31 19:05:27 +00004984 Value *TryRes = EvaluateInDifferentType(SrcI, DestTy, true);
Evan Cheng4e56ab22009-01-16 02:11:43 +00004985 unsigned NumSignBits = ComputeNumSignBits(TryRes);
4986 if (NumSignBits > (DestBitSize - SrcBitSize))
4987 return ReplaceInstUsesWith(CI, TryRes);
Chris Lattner39c27ed2009-01-31 19:05:27 +00004988
4989 if (Instruction *TryI = dyn_cast<Instruction>(TryRes))
Evan Cheng4e56ab22009-01-16 02:11:43 +00004990 if (TryI->use_empty())
4991 EraseInstFromFunction(*TryI);
Evan Chengf35fd542009-01-15 17:01:23 +00004992 }
Chris Lattnerc739cd62007-03-03 05:27:34 +00004993 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00004994 }
Evan Chengf35fd542009-01-15 17:01:23 +00004995 }
Reid Spencer3da59db2006-11-27 01:05:10 +00004996
4997 if (DoXForm) {
Chris Lattnerbdff5482009-08-23 04:37:46 +00004998 DEBUG(errs() << "ICE: EvaluateInDifferentType converting expression type"
4999 " to avoid cast: " << CI);
Reid Spencerc55b2432006-12-13 18:21:21 +00005000 Value *Res = EvaluateInDifferentType(SrcI, DestTy,
5001 CI.getOpcode() == Instruction::SExt);
Evan Cheng4e56ab22009-01-16 02:11:43 +00005002 if (JustReplace)
Chris Lattner39c27ed2009-01-31 19:05:27 +00005003 // Just replace this cast with the result.
5004 return ReplaceInstUsesWith(CI, Res);
Evan Cheng4e56ab22009-01-16 02:11:43 +00005005
Reid Spencer3da59db2006-11-27 01:05:10 +00005006 assert(Res->getType() == DestTy);
5007 switch (CI.getOpcode()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00005008 default: llvm_unreachable("Unknown cast type!");
Reid Spencer3da59db2006-11-27 01:05:10 +00005009 case Instruction::Trunc:
Reid Spencer3da59db2006-11-27 01:05:10 +00005010 // Just replace this cast with the result.
5011 return ReplaceInstUsesWith(CI, Res);
5012 case Instruction::ZExt: {
Reid Spencer3da59db2006-11-27 01:05:10 +00005013 assert(SrcBitSize < DestBitSize && "Not a zext?");
Evan Cheng4e56ab22009-01-16 02:11:43 +00005014
5015 // If the high bits are already zero, just replace this cast with the
5016 // result.
5017 APInt Mask(APInt::getBitsSet(DestBitSize, SrcBitSize, DestBitSize));
5018 if (MaskedValueIsZero(Res, Mask))
5019 return ReplaceInstUsesWith(CI, Res);
5020
5021 // We need to emit an AND to clear the high bits.
Chris Lattner4de84762010-01-04 07:02:48 +00005022 Constant *C = ConstantInt::get(CI.getContext(),
Owen Andersoneed707b2009-07-24 23:12:02 +00005023 APInt::getLowBitsSet(DestBitSize, SrcBitSize));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005024 return BinaryOperator::CreateAnd(Res, C);
Reid Spencer3da59db2006-11-27 01:05:10 +00005025 }
Evan Cheng4e56ab22009-01-16 02:11:43 +00005026 case Instruction::SExt: {
5027 // If the high bits are already filled with sign bit, just replace this
5028 // cast with the result.
5029 unsigned NumSignBits = ComputeNumSignBits(Res);
5030 if (NumSignBits > (DestBitSize - SrcBitSize))
Evan Chengf35fd542009-01-15 17:01:23 +00005031 return ReplaceInstUsesWith(CI, Res);
5032
Reid Spencer3da59db2006-11-27 01:05:10 +00005033 // We need to emit a cast to truncate, then a cast to sext.
Chris Lattner2345d1d2009-08-30 20:01:10 +00005034 return new SExtInst(Builder->CreateTrunc(Res, Src->getType()), DestTy);
Reid Spencer3da59db2006-11-27 01:05:10 +00005035 }
Evan Cheng4e56ab22009-01-16 02:11:43 +00005036 }
Reid Spencer3da59db2006-11-27 01:05:10 +00005037 }
5038 }
5039
5040 Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
5041 Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
5042
5043 switch (SrcI->getOpcode()) {
5044 case Instruction::Add:
5045 case Instruction::Mul:
5046 case Instruction::And:
5047 case Instruction::Or:
5048 case Instruction::Xor:
Chris Lattner01deb9d2007-04-03 17:43:25 +00005049 // If we are discarding information, rewrite.
Eli Friedman65445c52009-07-13 21:45:57 +00005050 if (DestBitSize < SrcBitSize && DestBitSize != 1) {
5051 // Don't insert two casts unless at least one can be eliminated.
5052 if (!ValueRequiresCast(CI.getOpcode(), Op1, DestTy, TD) ||
Reid Spencere4d87aa2006-12-23 06:05:41 +00005053 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
Chris Lattner2345d1d2009-08-30 20:01:10 +00005054 Value *Op0c = Builder->CreateTrunc(Op0, DestTy, Op0->getName());
5055 Value *Op1c = Builder->CreateTrunc(Op1, DestTy, Op1->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005056 return BinaryOperator::Create(
Reid Spencer17212df2006-12-12 09:18:51 +00005057 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
Reid Spencer3da59db2006-11-27 01:05:10 +00005058 }
5059 }
5060
5061 // cast (xor bool X, true) to int --> xor (cast bool X to int), 1
5062 if (isa<ZExtInst>(CI) && SrcBitSize == 1 &&
5063 SrcI->getOpcode() == Instruction::Xor &&
Chris Lattner4de84762010-01-04 07:02:48 +00005064 Op1 == ConstantInt::getTrue(CI.getContext()) &&
Reid Spencere4d87aa2006-12-23 06:05:41 +00005065 (!Op0->hasOneUse() || !isa<CmpInst>(Op0))) {
Chris Lattner2345d1d2009-08-30 20:01:10 +00005066 Value *New = Builder->CreateZExt(Op0, DestTy, Op0->getName());
Owen Andersond672ecb2009-07-03 00:17:18 +00005067 return BinaryOperator::CreateXor(New,
Owen Andersoneed707b2009-07-24 23:12:02 +00005068 ConstantInt::get(CI.getType(), 1));
Reid Spencer3da59db2006-11-27 01:05:10 +00005069 }
5070 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00005071
Eli Friedman65445c52009-07-13 21:45:57 +00005072 case Instruction::Shl: {
5073 // Canonicalize trunc inside shl, if we can.
5074 ConstantInt *CI = dyn_cast<ConstantInt>(Op1);
5075 if (CI && DestBitSize < SrcBitSize &&
5076 CI->getLimitedValue(DestBitSize) < DestBitSize) {
Chris Lattner2345d1d2009-08-30 20:01:10 +00005077 Value *Op0c = Builder->CreateTrunc(Op0, DestTy, Op0->getName());
5078 Value *Op1c = Builder->CreateTrunc(Op1, DestTy, Op1->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005079 return BinaryOperator::CreateShl(Op0c, Op1c);
Reid Spencer3da59db2006-11-27 01:05:10 +00005080 }
5081 break;
Eli Friedman65445c52009-07-13 21:45:57 +00005082 }
Reid Spencer3da59db2006-11-27 01:05:10 +00005083 }
5084 return 0;
5085}
5086
Chris Lattner8a9f5712007-04-11 06:57:46 +00005087Instruction *InstCombiner::visitTrunc(TruncInst &CI) {
Chris Lattner6aa5eb12006-11-29 07:04:07 +00005088 if (Instruction *Result = commonIntCastTransforms(CI))
5089 return Result;
5090
5091 Value *Src = CI.getOperand(0);
5092 const Type *Ty = CI.getType();
Dan Gohman6de29f82009-06-15 22:12:54 +00005093 uint32_t DestBitWidth = Ty->getScalarSizeInBits();
5094 uint32_t SrcBitWidth = Src->getType()->getScalarSizeInBits();
Chris Lattner4f9797d2009-03-24 18:15:30 +00005095
5096 // Canonicalize trunc x to i1 -> (icmp ne (and x, 1), 0)
Eli Friedman191a0ae2009-07-18 09:21:25 +00005097 if (DestBitWidth == 1) {
Owen Andersoneed707b2009-07-24 23:12:02 +00005098 Constant *One = ConstantInt::get(Src->getType(), 1);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00005099 Src = Builder->CreateAnd(Src, One, "tmp");
Owen Andersona7235ea2009-07-31 20:28:14 +00005100 Value *Zero = Constant::getNullValue(Src->getType());
Dan Gohman1c8a23c2009-08-25 23:17:54 +00005101 return new ICmpInst(ICmpInst::ICMP_NE, Src, Zero);
Chris Lattner4f9797d2009-03-24 18:15:30 +00005102 }
Dan Gohman6de29f82009-06-15 22:12:54 +00005103
Chris Lattner4f9797d2009-03-24 18:15:30 +00005104 // Optimize trunc(lshr(), c) to pull the shift through the truncate.
5105 ConstantInt *ShAmtV = 0;
5106 Value *ShiftOp = 0;
5107 if (Src->hasOneUse() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00005108 match(Src, m_LShr(m_Value(ShiftOp), m_ConstantInt(ShAmtV)))) {
Chris Lattner4f9797d2009-03-24 18:15:30 +00005109 uint32_t ShAmt = ShAmtV->getLimitedValue(SrcBitWidth);
5110
5111 // Get a mask for the bits shifting in.
5112 APInt Mask(APInt::getLowBitsSet(SrcBitWidth, ShAmt).shl(DestBitWidth));
5113 if (MaskedValueIsZero(ShiftOp, Mask)) {
5114 if (ShAmt >= DestBitWidth) // All zeros.
Owen Andersona7235ea2009-07-31 20:28:14 +00005115 return ReplaceInstUsesWith(CI, Constant::getNullValue(Ty));
Chris Lattner4f9797d2009-03-24 18:15:30 +00005116
5117 // Okay, we can shrink this. Truncate the input, then return a new
5118 // shift.
Chris Lattner2345d1d2009-08-30 20:01:10 +00005119 Value *V1 = Builder->CreateTrunc(ShiftOp, Ty, ShiftOp->getName());
Owen Andersonbaf3c402009-07-29 18:55:55 +00005120 Value *V2 = ConstantExpr::getTrunc(ShAmtV, Ty);
Chris Lattner4f9797d2009-03-24 18:15:30 +00005121 return BinaryOperator::CreateLShr(V1, V2);
Chris Lattner6aa5eb12006-11-29 07:04:07 +00005122 }
5123 }
Chris Lattner9956c052009-11-08 19:23:30 +00005124
Chris Lattner6aa5eb12006-11-29 07:04:07 +00005125 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00005126}
5127
Evan Chengb98a10e2008-03-24 00:21:34 +00005128/// transformZExtICmp - Transform (zext icmp) to bitwise / integer operations
5129/// in order to eliminate the icmp.
5130Instruction *InstCombiner::transformZExtICmp(ICmpInst *ICI, Instruction &CI,
5131 bool DoXform) {
5132 // If we are just checking for a icmp eq of a single bit and zext'ing it
5133 // to an integer, then shift the bit to the appropriate place and then
5134 // cast to integer to avoid the comparison.
5135 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
5136 const APInt &Op1CV = Op1C->getValue();
5137
5138 // zext (x <s 0) to i32 --> x>>u31 true if signbit set.
5139 // zext (x >s -1) to i32 --> (x>>u31)^1 true if signbit clear.
5140 if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
5141 (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())) {
5142 if (!DoXform) return ICI;
5143
5144 Value *In = ICI->getOperand(0);
Owen Andersoneed707b2009-07-24 23:12:02 +00005145 Value *Sh = ConstantInt::get(In->getType(),
Dan Gohman6de29f82009-06-15 22:12:54 +00005146 In->getType()->getScalarSizeInBits()-1);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00005147 In = Builder->CreateLShr(In, Sh, In->getName()+".lobit");
Evan Chengb98a10e2008-03-24 00:21:34 +00005148 if (In->getType() != CI.getType())
Chris Lattnerf925cbd2009-08-30 18:50:58 +00005149 In = Builder->CreateIntCast(In, CI.getType(), false/*ZExt*/, "tmp");
Evan Chengb98a10e2008-03-24 00:21:34 +00005150
5151 if (ICI->getPredicate() == ICmpInst::ICMP_SGT) {
Owen Andersoneed707b2009-07-24 23:12:02 +00005152 Constant *One = ConstantInt::get(In->getType(), 1);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00005153 In = Builder->CreateXor(In, One, In->getName()+".not");
Evan Chengb98a10e2008-03-24 00:21:34 +00005154 }
5155
5156 return ReplaceInstUsesWith(CI, In);
5157 }
5158
5159
5160
5161 // zext (X == 0) to i32 --> X^1 iff X has only the low bit set.
5162 // zext (X == 0) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
5163 // zext (X == 1) to i32 --> X iff X has only the low bit set.
5164 // zext (X == 2) to i32 --> X>>1 iff X has only the 2nd bit set.
5165 // zext (X != 0) to i32 --> X iff X has only the low bit set.
5166 // zext (X != 0) to i32 --> X>>1 iff X has only the 2nd bit set.
5167 // zext (X != 1) to i32 --> X^1 iff X has only the low bit set.
5168 // zext (X != 2) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
5169 if ((Op1CV == 0 || Op1CV.isPowerOf2()) &&
5170 // This only works for EQ and NE
5171 ICI->isEquality()) {
5172 // If Op1C some other power of two, convert:
5173 uint32_t BitWidth = Op1C->getType()->getBitWidth();
5174 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
5175 APInt TypeMask(APInt::getAllOnesValue(BitWidth));
5176 ComputeMaskedBits(ICI->getOperand(0), TypeMask, KnownZero, KnownOne);
5177
5178 APInt KnownZeroMask(~KnownZero);
5179 if (KnownZeroMask.isPowerOf2()) { // Exactly 1 possible 1?
5180 if (!DoXform) return ICI;
5181
5182 bool isNE = ICI->getPredicate() == ICmpInst::ICMP_NE;
5183 if (Op1CV != 0 && (Op1CV != KnownZeroMask)) {
5184 // (X&4) == 2 --> false
5185 // (X&4) != 2 --> true
Chris Lattner4de84762010-01-04 07:02:48 +00005186 Constant *Res = ConstantInt::get(Type::getInt1Ty(CI.getContext()),
5187 isNE);
Owen Andersonbaf3c402009-07-29 18:55:55 +00005188 Res = ConstantExpr::getZExt(Res, CI.getType());
Evan Chengb98a10e2008-03-24 00:21:34 +00005189 return ReplaceInstUsesWith(CI, Res);
5190 }
5191
5192 uint32_t ShiftAmt = KnownZeroMask.logBase2();
5193 Value *In = ICI->getOperand(0);
5194 if (ShiftAmt) {
5195 // Perform a logical shr by shiftamt.
5196 // Insert the shift to put the result in the low bit.
Chris Lattnerf925cbd2009-08-30 18:50:58 +00005197 In = Builder->CreateLShr(In, ConstantInt::get(In->getType(),ShiftAmt),
5198 In->getName()+".lobit");
Evan Chengb98a10e2008-03-24 00:21:34 +00005199 }
5200
5201 if ((Op1CV != 0) == isNE) { // Toggle the low bit.
Owen Andersoneed707b2009-07-24 23:12:02 +00005202 Constant *One = ConstantInt::get(In->getType(), 1);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00005203 In = Builder->CreateXor(In, One, "tmp");
Evan Chengb98a10e2008-03-24 00:21:34 +00005204 }
5205
5206 if (CI.getType() == In->getType())
5207 return ReplaceInstUsesWith(CI, In);
5208 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005209 return CastInst::CreateIntegerCast(In, CI.getType(), false/*ZExt*/);
Evan Chengb98a10e2008-03-24 00:21:34 +00005210 }
5211 }
5212 }
5213
Nick Lewycky55bd8bd2009-11-23 03:17:33 +00005214 // icmp ne A, B is equal to xor A, B when A and B only really have one bit.
5215 // It is also profitable to transform icmp eq into not(xor(A, B)) because that
5216 // may lead to additional simplifications.
5217 if (ICI->isEquality() && CI.getType() == ICI->getOperand(0)->getType()) {
5218 if (const IntegerType *ITy = dyn_cast<IntegerType>(CI.getType())) {
5219 uint32_t BitWidth = ITy->getBitWidth();
Nick Lewycky83e8ec72009-12-05 05:00:00 +00005220 Value *LHS = ICI->getOperand(0);
5221 Value *RHS = ICI->getOperand(1);
Nick Lewycky55bd8bd2009-11-23 03:17:33 +00005222
Nick Lewycky83e8ec72009-12-05 05:00:00 +00005223 APInt KnownZeroLHS(BitWidth, 0), KnownOneLHS(BitWidth, 0);
5224 APInt KnownZeroRHS(BitWidth, 0), KnownOneRHS(BitWidth, 0);
5225 APInt TypeMask(APInt::getAllOnesValue(BitWidth));
5226 ComputeMaskedBits(LHS, TypeMask, KnownZeroLHS, KnownOneLHS);
5227 ComputeMaskedBits(RHS, TypeMask, KnownZeroRHS, KnownOneRHS);
Nick Lewycky55bd8bd2009-11-23 03:17:33 +00005228
Nick Lewycky83e8ec72009-12-05 05:00:00 +00005229 if (KnownZeroLHS == KnownZeroRHS && KnownOneLHS == KnownOneRHS) {
5230 APInt KnownBits = KnownZeroLHS | KnownOneLHS;
5231 APInt UnknownBit = ~KnownBits;
5232 if (UnknownBit.countPopulation() == 1) {
Nick Lewycky55bd8bd2009-11-23 03:17:33 +00005233 if (!DoXform) return ICI;
5234
Nick Lewycky83e8ec72009-12-05 05:00:00 +00005235 Value *Result = Builder->CreateXor(LHS, RHS);
5236
5237 // Mask off any bits that are set and won't be shifted away.
5238 if (KnownOneLHS.uge(UnknownBit))
5239 Result = Builder->CreateAnd(Result,
5240 ConstantInt::get(ITy, UnknownBit));
5241
5242 // Shift the bit we're testing down to the lsb.
5243 Result = Builder->CreateLShr(
5244 Result, ConstantInt::get(ITy, UnknownBit.countTrailingZeros()));
5245
Nick Lewycky55bd8bd2009-11-23 03:17:33 +00005246 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
Nick Lewycky83e8ec72009-12-05 05:00:00 +00005247 Result = Builder->CreateXor(Result, ConstantInt::get(ITy, 1));
5248 Result->takeName(ICI);
5249 return ReplaceInstUsesWith(CI, Result);
Nick Lewycky55bd8bd2009-11-23 03:17:33 +00005250 }
5251 }
5252 }
5253 }
5254
Evan Chengb98a10e2008-03-24 00:21:34 +00005255 return 0;
5256}
5257
Chris Lattner8a9f5712007-04-11 06:57:46 +00005258Instruction *InstCombiner::visitZExt(ZExtInst &CI) {
Chris Lattnerdffbef02010-01-04 06:23:24 +00005259 // If one of the common conversion will work, do it.
Reid Spencer3da59db2006-11-27 01:05:10 +00005260 if (Instruction *Result = commonIntCastTransforms(CI))
5261 return Result;
5262
5263 Value *Src = CI.getOperand(0);
5264
Chris Lattnera84f47c2009-02-17 20:47:23 +00005265 // If this is a TRUNC followed by a ZEXT then we are dealing with integral
5266 // types and if the sizes are just right we can convert this into a logical
5267 // 'and' which will be much cheaper than the pair of casts.
5268 if (TruncInst *CSrc = dyn_cast<TruncInst>(Src)) { // A->B->C cast
5269 // Get the sizes of the types involved. We know that the intermediate type
5270 // will be smaller than A or C, but don't know the relation between A and C.
5271 Value *A = CSrc->getOperand(0);
Dan Gohman6de29f82009-06-15 22:12:54 +00005272 unsigned SrcSize = A->getType()->getScalarSizeInBits();
5273 unsigned MidSize = CSrc->getType()->getScalarSizeInBits();
5274 unsigned DstSize = CI.getType()->getScalarSizeInBits();
Chris Lattnera84f47c2009-02-17 20:47:23 +00005275 // If we're actually extending zero bits, then if
5276 // SrcSize < DstSize: zext(a & mask)
5277 // SrcSize == DstSize: a & mask
5278 // SrcSize > DstSize: trunc(a) & mask
5279 if (SrcSize < DstSize) {
5280 APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
Owen Andersoneed707b2009-07-24 23:12:02 +00005281 Constant *AndConst = ConstantInt::get(A->getType(), AndValue);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00005282 Value *And = Builder->CreateAnd(A, AndConst, CSrc->getName()+".mask");
Chris Lattnera84f47c2009-02-17 20:47:23 +00005283 return new ZExtInst(And, CI.getType());
Chris Lattnerf925cbd2009-08-30 18:50:58 +00005284 }
5285
5286 if (SrcSize == DstSize) {
Chris Lattnera84f47c2009-02-17 20:47:23 +00005287 APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
Owen Andersoneed707b2009-07-24 23:12:02 +00005288 return BinaryOperator::CreateAnd(A, ConstantInt::get(A->getType(),
Dan Gohman6de29f82009-06-15 22:12:54 +00005289 AndValue));
Chris Lattnerf925cbd2009-08-30 18:50:58 +00005290 }
5291 if (SrcSize > DstSize) {
5292 Value *Trunc = Builder->CreateTrunc(A, CI.getType(), "tmp");
Chris Lattnera84f47c2009-02-17 20:47:23 +00005293 APInt AndValue(APInt::getLowBitsSet(DstSize, MidSize));
Owen Andersond672ecb2009-07-03 00:17:18 +00005294 return BinaryOperator::CreateAnd(Trunc,
Owen Andersoneed707b2009-07-24 23:12:02 +00005295 ConstantInt::get(Trunc->getType(),
Dan Gohman6de29f82009-06-15 22:12:54 +00005296 AndValue));
Reid Spencer3da59db2006-11-27 01:05:10 +00005297 }
5298 }
5299
Evan Chengb98a10e2008-03-24 00:21:34 +00005300 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src))
5301 return transformZExtICmp(ICI, CI);
Chris Lattnera2e2c9b2007-04-11 06:53:04 +00005302
Evan Chengb98a10e2008-03-24 00:21:34 +00005303 BinaryOperator *SrcI = dyn_cast<BinaryOperator>(Src);
5304 if (SrcI && SrcI->getOpcode() == Instruction::Or) {
5305 // zext (or icmp, icmp) --> or (zext icmp), (zext icmp) if at least one
5306 // of the (zext icmp) will be transformed.
5307 ICmpInst *LHS = dyn_cast<ICmpInst>(SrcI->getOperand(0));
5308 ICmpInst *RHS = dyn_cast<ICmpInst>(SrcI->getOperand(1));
5309 if (LHS && RHS && LHS->hasOneUse() && RHS->hasOneUse() &&
5310 (transformZExtICmp(LHS, CI, false) ||
5311 transformZExtICmp(RHS, CI, false))) {
Chris Lattner2345d1d2009-08-30 20:01:10 +00005312 Value *LCast = Builder->CreateZExt(LHS, CI.getType(), LHS->getName());
5313 Value *RCast = Builder->CreateZExt(RHS, CI.getType(), RHS->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005314 return BinaryOperator::Create(Instruction::Or, LCast, RCast);
Chris Lattner66bc3252007-04-11 05:45:39 +00005315 }
Evan Chengb98a10e2008-03-24 00:21:34 +00005316 }
5317
Dan Gohmanfd3daa72009-06-18 16:30:21 +00005318 // zext(trunc(t) & C) -> (t & zext(C)).
Dan Gohmana392c782009-06-17 23:17:05 +00005319 if (SrcI && SrcI->getOpcode() == Instruction::And && SrcI->hasOneUse())
5320 if (ConstantInt *C = dyn_cast<ConstantInt>(SrcI->getOperand(1)))
5321 if (TruncInst *TI = dyn_cast<TruncInst>(SrcI->getOperand(0))) {
5322 Value *TI0 = TI->getOperand(0);
Dan Gohmanfd3daa72009-06-18 16:30:21 +00005323 if (TI0->getType() == CI.getType())
5324 return
5325 BinaryOperator::CreateAnd(TI0,
Owen Andersonbaf3c402009-07-29 18:55:55 +00005326 ConstantExpr::getZExt(C, CI.getType()));
Dan Gohmana392c782009-06-17 23:17:05 +00005327 }
5328
Dan Gohmanfd3daa72009-06-18 16:30:21 +00005329 // zext((trunc(t) & C) ^ C) -> ((t & zext(C)) ^ zext(C)).
5330 if (SrcI && SrcI->getOpcode() == Instruction::Xor && SrcI->hasOneUse())
5331 if (ConstantInt *C = dyn_cast<ConstantInt>(SrcI->getOperand(1)))
5332 if (BinaryOperator *And = dyn_cast<BinaryOperator>(SrcI->getOperand(0)))
5333 if (And->getOpcode() == Instruction::And && And->hasOneUse() &&
5334 And->getOperand(1) == C)
5335 if (TruncInst *TI = dyn_cast<TruncInst>(And->getOperand(0))) {
5336 Value *TI0 = TI->getOperand(0);
5337 if (TI0->getType() == CI.getType()) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00005338 Constant *ZC = ConstantExpr::getZExt(C, CI.getType());
Chris Lattnerf925cbd2009-08-30 18:50:58 +00005339 Value *NewAnd = Builder->CreateAnd(TI0, ZC, "tmp");
Dan Gohmanfd3daa72009-06-18 16:30:21 +00005340 return BinaryOperator::CreateXor(NewAnd, ZC);
5341 }
5342 }
5343
Reid Spencer3da59db2006-11-27 01:05:10 +00005344 return 0;
5345}
5346
Chris Lattner8a9f5712007-04-11 06:57:46 +00005347Instruction *InstCombiner::visitSExt(SExtInst &CI) {
Chris Lattnerba417832007-04-11 06:12:58 +00005348 if (Instruction *I = commonIntCastTransforms(CI))
5349 return I;
5350
Chris Lattner8a9f5712007-04-11 06:57:46 +00005351 Value *Src = CI.getOperand(0);
5352
Dan Gohman1975d032008-10-30 20:40:10 +00005353 // Canonicalize sign-extend from i1 to a select.
Chris Lattner4de84762010-01-04 07:02:48 +00005354 if (Src->getType() == Type::getInt1Ty(CI.getContext()))
Dan Gohman1975d032008-10-30 20:40:10 +00005355 return SelectInst::Create(Src,
Owen Andersona7235ea2009-07-31 20:28:14 +00005356 Constant::getAllOnesValue(CI.getType()),
5357 Constant::getNullValue(CI.getType()));
Dan Gohmanf35c8822008-05-20 21:01:12 +00005358
5359 // See if the value being truncated is already sign extended. If so, just
5360 // eliminate the trunc/sext pair.
Dan Gohmanca178902009-07-17 20:47:02 +00005361 if (Operator::getOpcode(Src) == Instruction::Trunc) {
Dan Gohmanf35c8822008-05-20 21:01:12 +00005362 Value *Op = cast<User>(Src)->getOperand(0);
Dan Gohman6de29f82009-06-15 22:12:54 +00005363 unsigned OpBits = Op->getType()->getScalarSizeInBits();
5364 unsigned MidBits = Src->getType()->getScalarSizeInBits();
5365 unsigned DestBits = CI.getType()->getScalarSizeInBits();
Dan Gohmanf35c8822008-05-20 21:01:12 +00005366 unsigned NumSignBits = ComputeNumSignBits(Op);
5367
5368 if (OpBits == DestBits) {
5369 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign
5370 // bits, it is already ready.
5371 if (NumSignBits > DestBits-MidBits)
5372 return ReplaceInstUsesWith(CI, Op);
5373 } else if (OpBits < DestBits) {
5374 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign
5375 // bits, just sext from i32.
5376 if (NumSignBits > OpBits-MidBits)
5377 return new SExtInst(Op, CI.getType(), "tmp");
5378 } else {
5379 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign
5380 // bits, just truncate to i32.
5381 if (NumSignBits > OpBits-MidBits)
5382 return new TruncInst(Op, CI.getType(), "tmp");
5383 }
5384 }
Chris Lattner46bbad22008-08-06 07:35:52 +00005385
5386 // If the input is a shl/ashr pair of a same constant, then this is a sign
5387 // extension from a smaller value. If we could trust arbitrary bitwidth
5388 // integers, we could turn this into a truncate to the smaller bit and then
5389 // use a sext for the whole extension. Since we don't, look deeper and check
5390 // for a truncate. If the source and dest are the same type, eliminate the
5391 // trunc and extend and just do shifts. For example, turn:
5392 // %a = trunc i32 %i to i8
5393 // %b = shl i8 %a, 6
5394 // %c = ashr i8 %b, 6
5395 // %d = sext i8 %c to i32
5396 // into:
5397 // %a = shl i32 %i, 30
5398 // %d = ashr i32 %a, 30
5399 Value *A = 0;
5400 ConstantInt *BA = 0, *CA = 0;
5401 if (match(Src, m_AShr(m_Shl(m_Value(A), m_ConstantInt(BA)),
Dan Gohman4ae51262009-08-12 16:23:25 +00005402 m_ConstantInt(CA))) &&
Chris Lattner46bbad22008-08-06 07:35:52 +00005403 BA == CA && isa<TruncInst>(A)) {
5404 Value *I = cast<TruncInst>(A)->getOperand(0);
5405 if (I->getType() == CI.getType()) {
Dan Gohman6de29f82009-06-15 22:12:54 +00005406 unsigned MidSize = Src->getType()->getScalarSizeInBits();
5407 unsigned SrcDstSize = CI.getType()->getScalarSizeInBits();
Chris Lattner46bbad22008-08-06 07:35:52 +00005408 unsigned ShAmt = CA->getZExtValue()+SrcDstSize-MidSize;
Owen Andersoneed707b2009-07-24 23:12:02 +00005409 Constant *ShAmtV = ConstantInt::get(CI.getType(), ShAmt);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00005410 I = Builder->CreateShl(I, ShAmtV, CI.getName());
Chris Lattner46bbad22008-08-06 07:35:52 +00005411 return BinaryOperator::CreateAShr(I, ShAmtV);
5412 }
5413 }
5414
Chris Lattnerba417832007-04-11 06:12:58 +00005415 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00005416}
5417
Chris Lattnerb7530652008-01-27 05:29:54 +00005418/// FitsInFPType - Return a Constant* for the specified FP constant if it fits
5419/// in the specified FP type without changing its value.
Chris Lattner4de84762010-01-04 07:02:48 +00005420static Constant *FitsInFPType(ConstantFP *CFP, const fltSemantics &Sem) {
Dale Johannesen23a98552008-10-09 23:00:39 +00005421 bool losesInfo;
Chris Lattnerb7530652008-01-27 05:29:54 +00005422 APFloat F = CFP->getValueAPF();
Dale Johannesen23a98552008-10-09 23:00:39 +00005423 (void)F.convert(Sem, APFloat::rmNearestTiesToEven, &losesInfo);
5424 if (!losesInfo)
Chris Lattner4de84762010-01-04 07:02:48 +00005425 return ConstantFP::get(CFP->getContext(), F);
Chris Lattnerb7530652008-01-27 05:29:54 +00005426 return 0;
5427}
5428
5429/// LookThroughFPExtensions - If this is an fp extension instruction, look
5430/// through it until we get the source value.
Chris Lattner4de84762010-01-04 07:02:48 +00005431static Value *LookThroughFPExtensions(Value *V) {
Chris Lattnerb7530652008-01-27 05:29:54 +00005432 if (Instruction *I = dyn_cast<Instruction>(V))
5433 if (I->getOpcode() == Instruction::FPExt)
Chris Lattner4de84762010-01-04 07:02:48 +00005434 return LookThroughFPExtensions(I->getOperand(0));
Chris Lattnerb7530652008-01-27 05:29:54 +00005435
5436 // If this value is a constant, return the constant in the smallest FP type
5437 // that can accurately represent it. This allows us to turn
5438 // (float)((double)X+2.0) into x+2.0f.
5439 if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
Chris Lattner4de84762010-01-04 07:02:48 +00005440 if (CFP->getType() == Type::getPPC_FP128Ty(V->getContext()))
Chris Lattnerb7530652008-01-27 05:29:54 +00005441 return V; // No constant folding of this.
5442 // See if the value can be truncated to float and then reextended.
Chris Lattner4de84762010-01-04 07:02:48 +00005443 if (Value *V = FitsInFPType(CFP, APFloat::IEEEsingle))
Chris Lattnerb7530652008-01-27 05:29:54 +00005444 return V;
Chris Lattner4de84762010-01-04 07:02:48 +00005445 if (CFP->getType() == Type::getDoubleTy(V->getContext()))
Chris Lattnerb7530652008-01-27 05:29:54 +00005446 return V; // Won't shrink.
Chris Lattner4de84762010-01-04 07:02:48 +00005447 if (Value *V = FitsInFPType(CFP, APFloat::IEEEdouble))
Chris Lattnerb7530652008-01-27 05:29:54 +00005448 return V;
5449 // Don't try to shrink to various long double types.
5450 }
5451
5452 return V;
5453}
5454
5455Instruction *InstCombiner::visitFPTrunc(FPTruncInst &CI) {
5456 if (Instruction *I = commonCastTransforms(CI))
5457 return I;
5458
Dan Gohmanae3a0be2009-06-04 22:49:04 +00005459 // If we have fptrunc(fadd (fpextend x), (fpextend y)), where x and y are
Chris Lattnerb7530652008-01-27 05:29:54 +00005460 // smaller than the destination type, we can eliminate the truncate by doing
Dan Gohmanae3a0be2009-06-04 22:49:04 +00005461 // the add as the smaller type. This applies to fadd/fsub/fmul/fdiv as well as
Chris Lattnerb7530652008-01-27 05:29:54 +00005462 // many builtins (sqrt, etc).
5463 BinaryOperator *OpI = dyn_cast<BinaryOperator>(CI.getOperand(0));
5464 if (OpI && OpI->hasOneUse()) {
5465 switch (OpI->getOpcode()) {
5466 default: break;
Dan Gohmanae3a0be2009-06-04 22:49:04 +00005467 case Instruction::FAdd:
5468 case Instruction::FSub:
5469 case Instruction::FMul:
Chris Lattnerb7530652008-01-27 05:29:54 +00005470 case Instruction::FDiv:
5471 case Instruction::FRem:
5472 const Type *SrcTy = OpI->getType();
Chris Lattner4de84762010-01-04 07:02:48 +00005473 Value *LHSTrunc = LookThroughFPExtensions(OpI->getOperand(0));
5474 Value *RHSTrunc = LookThroughFPExtensions(OpI->getOperand(1));
Chris Lattnerb7530652008-01-27 05:29:54 +00005475 if (LHSTrunc->getType() != SrcTy &&
5476 RHSTrunc->getType() != SrcTy) {
Dan Gohman6de29f82009-06-15 22:12:54 +00005477 unsigned DstSize = CI.getType()->getScalarSizeInBits();
Chris Lattnerb7530652008-01-27 05:29:54 +00005478 // If the source types were both smaller than the destination type of
5479 // the cast, do this xform.
Dan Gohman6de29f82009-06-15 22:12:54 +00005480 if (LHSTrunc->getType()->getScalarSizeInBits() <= DstSize &&
5481 RHSTrunc->getType()->getScalarSizeInBits() <= DstSize) {
Chris Lattner2345d1d2009-08-30 20:01:10 +00005482 LHSTrunc = Builder->CreateFPExt(LHSTrunc, CI.getType());
5483 RHSTrunc = Builder->CreateFPExt(RHSTrunc, CI.getType());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005484 return BinaryOperator::Create(OpI->getOpcode(), LHSTrunc, RHSTrunc);
Chris Lattnerb7530652008-01-27 05:29:54 +00005485 }
5486 }
5487 break;
5488 }
5489 }
5490 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00005491}
5492
5493Instruction *InstCombiner::visitFPExt(CastInst &CI) {
5494 return commonCastTransforms(CI);
5495}
5496
Chris Lattner0c7a9a02008-05-19 20:25:04 +00005497Instruction *InstCombiner::visitFPToUI(FPToUIInst &FI) {
Chris Lattner5af5f462008-08-06 05:13:06 +00005498 Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
5499 if (OpI == 0)
5500 return commonCastTransforms(FI);
5501
5502 // fptoui(uitofp(X)) --> X
5503 // fptoui(sitofp(X)) --> X
5504 // This is safe if the intermediate type has enough bits in its mantissa to
5505 // accurately represent all values of X. For example, do not do this with
5506 // i64->float->i64. This is also safe for sitofp case, because any negative
5507 // 'X' value would cause an undefined result for the fptoui.
5508 if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
5509 OpI->getOperand(0)->getType() == FI.getType() &&
Dan Gohman6de29f82009-06-15 22:12:54 +00005510 (int)FI.getType()->getScalarSizeInBits() < /*extra bit for sign */
Chris Lattner5af5f462008-08-06 05:13:06 +00005511 OpI->getType()->getFPMantissaWidth())
5512 return ReplaceInstUsesWith(FI, OpI->getOperand(0));
Chris Lattner0c7a9a02008-05-19 20:25:04 +00005513
5514 return commonCastTransforms(FI);
Reid Spencer3da59db2006-11-27 01:05:10 +00005515}
5516
Chris Lattner0c7a9a02008-05-19 20:25:04 +00005517Instruction *InstCombiner::visitFPToSI(FPToSIInst &FI) {
Chris Lattner5af5f462008-08-06 05:13:06 +00005518 Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
5519 if (OpI == 0)
5520 return commonCastTransforms(FI);
5521
5522 // fptosi(sitofp(X)) --> X
5523 // fptosi(uitofp(X)) --> X
5524 // This is safe if the intermediate type has enough bits in its mantissa to
5525 // accurately represent all values of X. For example, do not do this with
5526 // i64->float->i64. This is also safe for sitofp case, because any negative
5527 // 'X' value would cause an undefined result for the fptoui.
5528 if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
5529 OpI->getOperand(0)->getType() == FI.getType() &&
Dan Gohman6de29f82009-06-15 22:12:54 +00005530 (int)FI.getType()->getScalarSizeInBits() <=
Chris Lattner5af5f462008-08-06 05:13:06 +00005531 OpI->getType()->getFPMantissaWidth())
5532 return ReplaceInstUsesWith(FI, OpI->getOperand(0));
Chris Lattner0c7a9a02008-05-19 20:25:04 +00005533
5534 return commonCastTransforms(FI);
Reid Spencer3da59db2006-11-27 01:05:10 +00005535}
5536
5537Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
5538 return commonCastTransforms(CI);
5539}
5540
5541Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
5542 return commonCastTransforms(CI);
5543}
5544
Chris Lattnera0e69692009-03-24 18:35:40 +00005545Instruction *InstCombiner::visitPtrToInt(PtrToIntInst &CI) {
5546 // If the destination integer type is smaller than the intptr_t type for
5547 // this target, do a ptrtoint to intptr_t then do a trunc. This allows the
5548 // trunc to be exposed to other transforms. Don't do this for extending
5549 // ptrtoint's, because we don't know if the target sign or zero extends its
5550 // pointers.
Dan Gohmance9fe9f2009-07-21 23:21:54 +00005551 if (TD &&
5552 CI.getType()->getScalarSizeInBits() < TD->getPointerSizeInBits()) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +00005553 Value *P = Builder->CreatePtrToInt(CI.getOperand(0),
5554 TD->getIntPtrType(CI.getContext()),
5555 "tmp");
Chris Lattnera0e69692009-03-24 18:35:40 +00005556 return new TruncInst(P, CI.getType());
5557 }
5558
Chris Lattnerd3e28342007-04-27 17:44:50 +00005559 return commonPointerCastTransforms(CI);
Reid Spencer3da59db2006-11-27 01:05:10 +00005560}
5561
Chris Lattnerf9d9e452008-01-08 07:23:51 +00005562Instruction *InstCombiner::visitIntToPtr(IntToPtrInst &CI) {
Chris Lattnera0e69692009-03-24 18:35:40 +00005563 // If the source integer type is larger than the intptr_t type for
5564 // this target, do a trunc to the intptr_t type, then inttoptr of it. This
5565 // allows the trunc to be exposed to other transforms. Don't do this for
5566 // extending inttoptr's, because we don't know if the target sign or zero
5567 // extends to pointers.
Chris Lattnerf925cbd2009-08-30 18:50:58 +00005568 if (TD && CI.getOperand(0)->getType()->getScalarSizeInBits() >
Chris Lattnera0e69692009-03-24 18:35:40 +00005569 TD->getPointerSizeInBits()) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +00005570 Value *P = Builder->CreateTrunc(CI.getOperand(0),
5571 TD->getIntPtrType(CI.getContext()), "tmp");
Chris Lattnera0e69692009-03-24 18:35:40 +00005572 return new IntToPtrInst(P, CI.getType());
5573 }
5574
Chris Lattnerf9d9e452008-01-08 07:23:51 +00005575 if (Instruction *I = commonCastTransforms(CI))
5576 return I;
Chris Lattnerf9d9e452008-01-08 07:23:51 +00005577
Chris Lattnerf9d9e452008-01-08 07:23:51 +00005578 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00005579}
5580
Chris Lattnerd3e28342007-04-27 17:44:50 +00005581Instruction *InstCombiner::visitBitCast(BitCastInst &CI) {
Reid Spencer3da59db2006-11-27 01:05:10 +00005582 // If the operands are integer typed then apply the integer transforms,
5583 // otherwise just apply the common ones.
5584 Value *Src = CI.getOperand(0);
5585 const Type *SrcTy = Src->getType();
5586 const Type *DestTy = CI.getType();
5587
Eli Friedman7e25d452009-07-13 20:53:00 +00005588 if (isa<PointerType>(SrcTy)) {
Chris Lattnerd3e28342007-04-27 17:44:50 +00005589 if (Instruction *I = commonPointerCastTransforms(CI))
5590 return I;
Reid Spencer3da59db2006-11-27 01:05:10 +00005591 } else {
5592 if (Instruction *Result = commonCastTransforms(CI))
5593 return Result;
5594 }
5595
5596
5597 // Get rid of casts from one type to the same type. These are useless and can
5598 // be replaced by the operand.
5599 if (DestTy == Src->getType())
5600 return ReplaceInstUsesWith(CI, Src);
5601
Reid Spencer3da59db2006-11-27 01:05:10 +00005602 if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
Chris Lattnerd3e28342007-04-27 17:44:50 +00005603 const PointerType *SrcPTy = cast<PointerType>(SrcTy);
5604 const Type *DstElTy = DstPTy->getElementType();
5605 const Type *SrcElTy = SrcPTy->getElementType();
5606
Nate Begeman83ad90a2008-03-31 00:22:16 +00005607 // If the address spaces don't match, don't eliminate the bitcast, which is
5608 // required for changing types.
5609 if (SrcPTy->getAddressSpace() != DstPTy->getAddressSpace())
5610 return 0;
5611
Victor Hernandez83d63912009-09-18 22:35:49 +00005612 // If we are casting a alloca to a pointer to a type of the same
Chris Lattnerd3e28342007-04-27 17:44:50 +00005613 // size, rewrite the allocation instruction to allocate the "right" type.
Victor Hernandez83d63912009-09-18 22:35:49 +00005614 // There is no need to modify malloc calls because it is their bitcast that
5615 // needs to be cleaned up.
Victor Hernandez7b929da2009-10-23 21:09:37 +00005616 if (AllocaInst *AI = dyn_cast<AllocaInst>(Src))
Chris Lattnerd3e28342007-04-27 17:44:50 +00005617 if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
5618 return V;
5619
Chris Lattnerd717c182007-05-05 22:32:24 +00005620 // If the source and destination are pointers, and this cast is equivalent
5621 // to a getelementptr X, 0, 0, 0... turn it into the appropriate gep.
Chris Lattnerd3e28342007-04-27 17:44:50 +00005622 // This can enhance SROA and other transforms that want type-safe pointers.
Chris Lattner4de84762010-01-04 07:02:48 +00005623 Constant *ZeroUInt =
5624 Constant::getNullValue(Type::getInt32Ty(CI.getContext()));
Chris Lattnerd3e28342007-04-27 17:44:50 +00005625 unsigned NumZeros = 0;
5626 while (SrcElTy != DstElTy &&
5627 isa<CompositeType>(SrcElTy) && !isa<PointerType>(SrcElTy) &&
5628 SrcElTy->getNumContainedTypes() /* not "{}" */) {
5629 SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
5630 ++NumZeros;
5631 }
Chris Lattner4e998b22004-09-29 05:07:12 +00005632
Chris Lattnerd3e28342007-04-27 17:44:50 +00005633 // If we found a path from the src to dest, create the getelementptr now.
5634 if (SrcElTy == DstElTy) {
5635 SmallVector<Value*, 8> Idxs(NumZeros+1, ZeroUInt);
Chris Lattner4de84762010-01-04 07:02:48 +00005636 return GetElementPtrInst::CreateInBounds(Src, Idxs.begin(), Idxs.end(),"",
Dan Gohmanf8dbee72009-09-07 23:54:19 +00005637 ((Instruction*) NULL));
Chris Lattner9fb92132006-04-12 18:09:35 +00005638 }
Reid Spencer3da59db2006-11-27 01:05:10 +00005639 }
Chris Lattner24c8e382003-07-24 17:35:25 +00005640
Eli Friedman2451a642009-07-18 23:06:53 +00005641 if (const VectorType *DestVTy = dyn_cast<VectorType>(DestTy)) {
5642 if (DestVTy->getNumElements() == 1) {
5643 if (!isa<VectorType>(SrcTy)) {
Chris Lattner2345d1d2009-08-30 20:01:10 +00005644 Value *Elem = Builder->CreateBitCast(Src, DestVTy->getElementType());
Owen Anderson9e9a0d52009-07-30 23:03:37 +00005645 return InsertElementInst::Create(UndefValue::get(DestTy), Elem,
Chris Lattner4de84762010-01-04 07:02:48 +00005646 Constant::getNullValue(Type::getInt32Ty(CI.getContext())));
Eli Friedman2451a642009-07-18 23:06:53 +00005647 }
5648 // FIXME: Canonicalize bitcast(insertelement) -> insertelement(bitcast)
5649 }
5650 }
5651
5652 if (const VectorType *SrcVTy = dyn_cast<VectorType>(SrcTy)) {
5653 if (SrcVTy->getNumElements() == 1) {
5654 if (!isa<VectorType>(DestTy)) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +00005655 Value *Elem =
5656 Builder->CreateExtractElement(Src,
Chris Lattner4de84762010-01-04 07:02:48 +00005657 Constant::getNullValue(Type::getInt32Ty(CI.getContext())));
Eli Friedman2451a642009-07-18 23:06:53 +00005658 return CastInst::Create(Instruction::BitCast, Elem, DestTy);
5659 }
5660 }
5661 }
5662
Reid Spencer3da59db2006-11-27 01:05:10 +00005663 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
5664 if (SVI->hasOneUse()) {
5665 // Okay, we have (bitconvert (shuffle ..)). Check to see if this is
5666 // a bitconvert to a vector with the same # elts.
Reid Spencer9d6565a2007-02-15 02:26:10 +00005667 if (isa<VectorType>(DestTy) &&
Mon P Wangaeb06d22008-11-10 04:46:22 +00005668 cast<VectorType>(DestTy)->getNumElements() ==
5669 SVI->getType()->getNumElements() &&
5670 SVI->getType()->getNumElements() ==
5671 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements()) {
Reid Spencer3da59db2006-11-27 01:05:10 +00005672 CastInst *Tmp;
5673 // If either of the operands is a cast from CI.getType(), then
5674 // evaluating the shuffle in the casted destination's type will allow
5675 // us to eliminate at least one cast.
5676 if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) &&
5677 Tmp->getOperand(0)->getType() == DestTy) ||
5678 ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) &&
5679 Tmp->getOperand(0)->getType() == DestTy)) {
Chris Lattner2345d1d2009-08-30 20:01:10 +00005680 Value *LHS = Builder->CreateBitCast(SVI->getOperand(0), DestTy);
5681 Value *RHS = Builder->CreateBitCast(SVI->getOperand(1), DestTy);
Reid Spencer3da59db2006-11-27 01:05:10 +00005682 // Return a new shuffle vector. Use the same element ID's, as we
5683 // know the vector types match #elts.
5684 return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
Chris Lattner01575b72006-05-25 23:24:33 +00005685 }
5686 }
5687 }
5688 }
Chris Lattnerdd841ae2002-04-18 17:39:14 +00005689 return 0;
Chris Lattner8a2a3112001-12-14 16:52:21 +00005690}
5691
Chris Lattnere576b912004-04-09 23:46:01 +00005692/// GetSelectFoldableOperands - We want to turn code that looks like this:
5693/// %C = or %A, %B
5694/// %D = select %cond, %C, %A
5695/// into:
5696/// %C = select %cond, %B, 0
5697/// %D = or %A, %C
5698///
5699/// Assuming that the specified instruction is an operand to the select, return
5700/// a bitmask indicating which operands of this instruction are foldable if they
5701/// equal the other incoming value of the select.
5702///
5703static unsigned GetSelectFoldableOperands(Instruction *I) {
5704 switch (I->getOpcode()) {
5705 case Instruction::Add:
5706 case Instruction::Mul:
5707 case Instruction::And:
5708 case Instruction::Or:
5709 case Instruction::Xor:
5710 return 3; // Can fold through either operand.
5711 case Instruction::Sub: // Can only fold on the amount subtracted.
5712 case Instruction::Shl: // Can only fold on the shift amount.
Reid Spencer3822ff52006-11-08 06:47:33 +00005713 case Instruction::LShr:
5714 case Instruction::AShr:
Misha Brukmanfd939082005-04-21 23:48:37 +00005715 return 1;
Chris Lattnere576b912004-04-09 23:46:01 +00005716 default:
5717 return 0; // Cannot fold
5718 }
5719}
5720
5721/// GetSelectFoldableConstant - For the same transformation as the previous
5722/// function, return the identity constant that goes into the select.
Chris Lattner4de84762010-01-04 07:02:48 +00005723static Constant *GetSelectFoldableConstant(Instruction *I) {
Chris Lattnere576b912004-04-09 23:46:01 +00005724 switch (I->getOpcode()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00005725 default: llvm_unreachable("This cannot happen!");
Chris Lattnere576b912004-04-09 23:46:01 +00005726 case Instruction::Add:
5727 case Instruction::Sub:
5728 case Instruction::Or:
5729 case Instruction::Xor:
Chris Lattnere576b912004-04-09 23:46:01 +00005730 case Instruction::Shl:
Reid Spencer3822ff52006-11-08 06:47:33 +00005731 case Instruction::LShr:
5732 case Instruction::AShr:
Owen Andersona7235ea2009-07-31 20:28:14 +00005733 return Constant::getNullValue(I->getType());
Chris Lattnere576b912004-04-09 23:46:01 +00005734 case Instruction::And:
Owen Andersona7235ea2009-07-31 20:28:14 +00005735 return Constant::getAllOnesValue(I->getType());
Chris Lattnere576b912004-04-09 23:46:01 +00005736 case Instruction::Mul:
Owen Andersoneed707b2009-07-24 23:12:02 +00005737 return ConstantInt::get(I->getType(), 1);
Chris Lattnere576b912004-04-09 23:46:01 +00005738 }
5739}
5740
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00005741/// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
5742/// have the same opcode and only one use each. Try to simplify this.
5743Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
5744 Instruction *FI) {
5745 if (TI->getNumOperands() == 1) {
5746 // If this is a non-volatile load or a cast from the same type,
5747 // merge.
Reid Spencer3da59db2006-11-27 01:05:10 +00005748 if (TI->isCast()) {
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00005749 if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
5750 return 0;
5751 } else {
5752 return 0; // unknown unary op.
5753 }
Misha Brukmanfd939082005-04-21 23:48:37 +00005754
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00005755 // Fold this by inserting a select from the input values.
Gabor Greif051a9502008-04-06 20:25:17 +00005756 SelectInst *NewSI = SelectInst::Create(SI.getCondition(), TI->getOperand(0),
Eric Christophera66297a2009-07-25 02:45:27 +00005757 FI->getOperand(0), SI.getName()+".v");
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00005758 InsertNewInstBefore(NewSI, SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005759 return CastInst::Create(Instruction::CastOps(TI->getOpcode()), NewSI,
Reid Spencer3da59db2006-11-27 01:05:10 +00005760 TI->getType());
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00005761 }
5762
Reid Spencer832254e2007-02-02 02:16:23 +00005763 // Only handle binary operators here.
5764 if (!isa<BinaryOperator>(TI))
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00005765 return 0;
5766
5767 // Figure out if the operations have any operands in common.
5768 Value *MatchOp, *OtherOpT, *OtherOpF;
5769 bool MatchIsOpZero;
5770 if (TI->getOperand(0) == FI->getOperand(0)) {
5771 MatchOp = TI->getOperand(0);
5772 OtherOpT = TI->getOperand(1);
5773 OtherOpF = FI->getOperand(1);
5774 MatchIsOpZero = true;
5775 } else if (TI->getOperand(1) == FI->getOperand(1)) {
5776 MatchOp = TI->getOperand(1);
5777 OtherOpT = TI->getOperand(0);
5778 OtherOpF = FI->getOperand(0);
5779 MatchIsOpZero = false;
5780 } else if (!TI->isCommutative()) {
5781 return 0;
5782 } else if (TI->getOperand(0) == FI->getOperand(1)) {
5783 MatchOp = TI->getOperand(0);
5784 OtherOpT = TI->getOperand(1);
5785 OtherOpF = FI->getOperand(0);
5786 MatchIsOpZero = true;
5787 } else if (TI->getOperand(1) == FI->getOperand(0)) {
5788 MatchOp = TI->getOperand(1);
5789 OtherOpT = TI->getOperand(0);
5790 OtherOpF = FI->getOperand(1);
5791 MatchIsOpZero = true;
5792 } else {
5793 return 0;
5794 }
5795
5796 // If we reach here, they do have operations in common.
Gabor Greif051a9502008-04-06 20:25:17 +00005797 SelectInst *NewSI = SelectInst::Create(SI.getCondition(), OtherOpT,
5798 OtherOpF, SI.getName()+".v");
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00005799 InsertNewInstBefore(NewSI, SI);
5800
5801 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
5802 if (MatchIsOpZero)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005803 return BinaryOperator::Create(BO->getOpcode(), MatchOp, NewSI);
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00005804 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005805 return BinaryOperator::Create(BO->getOpcode(), NewSI, MatchOp);
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00005806 }
Torok Edwinc23197a2009-07-14 16:55:14 +00005807 llvm_unreachable("Shouldn't get here");
Reid Spencera07cb7d2007-02-02 14:41:37 +00005808 return 0;
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00005809}
5810
Evan Chengde621922009-03-31 20:42:45 +00005811static bool isSelect01(Constant *C1, Constant *C2) {
5812 ConstantInt *C1I = dyn_cast<ConstantInt>(C1);
5813 if (!C1I)
5814 return false;
5815 ConstantInt *C2I = dyn_cast<ConstantInt>(C2);
5816 if (!C2I)
5817 return false;
5818 return (C1I->isZero() || C1I->isOne()) && (C2I->isZero() || C2I->isOne());
5819}
5820
5821/// FoldSelectIntoOp - Try fold the select into one of the operands to
5822/// facilitate further optimization.
5823Instruction *InstCombiner::FoldSelectIntoOp(SelectInst &SI, Value *TrueVal,
5824 Value *FalseVal) {
5825 // See the comment above GetSelectFoldableOperands for a description of the
5826 // transformation we are doing here.
5827 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal)) {
5828 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
5829 !isa<Constant>(FalseVal)) {
5830 if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
5831 unsigned OpToFold = 0;
5832 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
5833 OpToFold = 1;
5834 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
5835 OpToFold = 2;
5836 }
5837
5838 if (OpToFold) {
Chris Lattner4de84762010-01-04 07:02:48 +00005839 Constant *C = GetSelectFoldableConstant(TVI);
Evan Chengde621922009-03-31 20:42:45 +00005840 Value *OOp = TVI->getOperand(2-OpToFold);
5841 // Avoid creating select between 2 constants unless it's selecting
5842 // between 0 and 1.
5843 if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
5844 Instruction *NewSel = SelectInst::Create(SI.getCondition(), OOp, C);
5845 InsertNewInstBefore(NewSel, SI);
5846 NewSel->takeName(TVI);
5847 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
5848 return BinaryOperator::Create(BO->getOpcode(), FalseVal, NewSel);
Torok Edwinc23197a2009-07-14 16:55:14 +00005849 llvm_unreachable("Unknown instruction!!");
Evan Chengde621922009-03-31 20:42:45 +00005850 }
5851 }
5852 }
5853 }
5854 }
5855
5856 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal)) {
5857 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
5858 !isa<Constant>(TrueVal)) {
5859 if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
5860 unsigned OpToFold = 0;
5861 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
5862 OpToFold = 1;
5863 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
5864 OpToFold = 2;
5865 }
5866
5867 if (OpToFold) {
Chris Lattner4de84762010-01-04 07:02:48 +00005868 Constant *C = GetSelectFoldableConstant(FVI);
Evan Chengde621922009-03-31 20:42:45 +00005869 Value *OOp = FVI->getOperand(2-OpToFold);
5870 // Avoid creating select between 2 constants unless it's selecting
5871 // between 0 and 1.
5872 if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
5873 Instruction *NewSel = SelectInst::Create(SI.getCondition(), C, OOp);
5874 InsertNewInstBefore(NewSel, SI);
5875 NewSel->takeName(FVI);
5876 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
5877 return BinaryOperator::Create(BO->getOpcode(), TrueVal, NewSel);
Torok Edwinc23197a2009-07-14 16:55:14 +00005878 llvm_unreachable("Unknown instruction!!");
Evan Chengde621922009-03-31 20:42:45 +00005879 }
5880 }
5881 }
5882 }
5883 }
5884
5885 return 0;
5886}
5887
Dan Gohman81b28ce2008-09-16 18:46:06 +00005888/// visitSelectInstWithICmp - Visit a SelectInst that has an
5889/// ICmpInst as its first operand.
5890///
5891Instruction *InstCombiner::visitSelectInstWithICmp(SelectInst &SI,
5892 ICmpInst *ICI) {
5893 bool Changed = false;
5894 ICmpInst::Predicate Pred = ICI->getPredicate();
5895 Value *CmpLHS = ICI->getOperand(0);
5896 Value *CmpRHS = ICI->getOperand(1);
5897 Value *TrueVal = SI.getTrueValue();
5898 Value *FalseVal = SI.getFalseValue();
5899
5900 // Check cases where the comparison is with a constant that
5901 // can be adjusted to fit the min/max idiom. We may edit ICI in
5902 // place here, so make sure the select is the only user.
5903 if (ICI->hasOneUse())
Dan Gohman1975d032008-10-30 20:40:10 +00005904 if (ConstantInt *CI = dyn_cast<ConstantInt>(CmpRHS)) {
Dan Gohman81b28ce2008-09-16 18:46:06 +00005905 switch (Pred) {
5906 default: break;
5907 case ICmpInst::ICMP_ULT:
5908 case ICmpInst::ICMP_SLT: {
5909 // X < MIN ? T : F --> F
5910 if (CI->isMinValue(Pred == ICmpInst::ICMP_SLT))
5911 return ReplaceInstUsesWith(SI, FalseVal);
5912 // X < C ? X : C-1 --> X > C-1 ? C-1 : X
Dan Gohman186a6362009-08-12 16:04:34 +00005913 Constant *AdjustedRHS = SubOne(CI);
Dan Gohman81b28ce2008-09-16 18:46:06 +00005914 if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
5915 (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
5916 Pred = ICmpInst::getSwappedPredicate(Pred);
5917 CmpRHS = AdjustedRHS;
5918 std::swap(FalseVal, TrueVal);
5919 ICI->setPredicate(Pred);
5920 ICI->setOperand(1, CmpRHS);
5921 SI.setOperand(1, TrueVal);
5922 SI.setOperand(2, FalseVal);
5923 Changed = true;
5924 }
5925 break;
5926 }
5927 case ICmpInst::ICMP_UGT:
5928 case ICmpInst::ICMP_SGT: {
5929 // X > MAX ? T : F --> F
5930 if (CI->isMaxValue(Pred == ICmpInst::ICMP_SGT))
5931 return ReplaceInstUsesWith(SI, FalseVal);
5932 // X > C ? X : C+1 --> X < C+1 ? C+1 : X
Dan Gohman186a6362009-08-12 16:04:34 +00005933 Constant *AdjustedRHS = AddOne(CI);
Dan Gohman81b28ce2008-09-16 18:46:06 +00005934 if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
5935 (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
5936 Pred = ICmpInst::getSwappedPredicate(Pred);
5937 CmpRHS = AdjustedRHS;
5938 std::swap(FalseVal, TrueVal);
5939 ICI->setPredicate(Pred);
5940 ICI->setOperand(1, CmpRHS);
5941 SI.setOperand(1, TrueVal);
5942 SI.setOperand(2, FalseVal);
5943 Changed = true;
5944 }
5945 break;
5946 }
5947 }
5948
Dan Gohman1975d032008-10-30 20:40:10 +00005949 // (x <s 0) ? -1 : 0 -> ashr x, 31 -> all ones if signed
5950 // (x >s -1) ? -1 : 0 -> ashr x, 31 -> all ones if not signed
Chris Lattnercb504b92008-11-16 05:38:51 +00005951 CmpInst::Predicate Pred = CmpInst::BAD_ICMP_PREDICATE;
Dan Gohman4ae51262009-08-12 16:23:25 +00005952 if (match(TrueVal, m_ConstantInt<-1>()) &&
5953 match(FalseVal, m_ConstantInt<0>()))
Chris Lattnercb504b92008-11-16 05:38:51 +00005954 Pred = ICI->getPredicate();
Dan Gohman4ae51262009-08-12 16:23:25 +00005955 else if (match(TrueVal, m_ConstantInt<0>()) &&
5956 match(FalseVal, m_ConstantInt<-1>()))
Chris Lattnercb504b92008-11-16 05:38:51 +00005957 Pred = CmpInst::getInversePredicate(ICI->getPredicate());
5958
Dan Gohman1975d032008-10-30 20:40:10 +00005959 if (Pred != CmpInst::BAD_ICMP_PREDICATE) {
5960 // If we are just checking for a icmp eq of a single bit and zext'ing it
5961 // to an integer, then shift the bit to the appropriate place and then
5962 // cast to integer to avoid the comparison.
5963 const APInt &Op1CV = CI->getValue();
5964
5965 // sext (x <s 0) to i32 --> x>>s31 true if signbit set.
5966 // sext (x >s -1) to i32 --> (x>>s31)^-1 true if signbit clear.
5967 if ((Pred == ICmpInst::ICMP_SLT && Op1CV == 0) ||
Chris Lattnercb504b92008-11-16 05:38:51 +00005968 (Pred == ICmpInst::ICMP_SGT && Op1CV.isAllOnesValue())) {
Dan Gohman1975d032008-10-30 20:40:10 +00005969 Value *In = ICI->getOperand(0);
Owen Andersoneed707b2009-07-24 23:12:02 +00005970 Value *Sh = ConstantInt::get(In->getType(),
Dan Gohman6de29f82009-06-15 22:12:54 +00005971 In->getType()->getScalarSizeInBits()-1);
Dan Gohman1975d032008-10-30 20:40:10 +00005972 In = InsertNewInstBefore(BinaryOperator::CreateAShr(In, Sh,
Eric Christophera66297a2009-07-25 02:45:27 +00005973 In->getName()+".lobit"),
Dan Gohman1975d032008-10-30 20:40:10 +00005974 *ICI);
Dan Gohman21440ac2008-11-02 00:17:33 +00005975 if (In->getType() != SI.getType())
5976 In = CastInst::CreateIntegerCast(In, SI.getType(),
Dan Gohman1975d032008-10-30 20:40:10 +00005977 true/*SExt*/, "tmp", ICI);
5978
5979 if (Pred == ICmpInst::ICMP_SGT)
Dan Gohman4ae51262009-08-12 16:23:25 +00005980 In = InsertNewInstBefore(BinaryOperator::CreateNot(In,
Dan Gohman1975d032008-10-30 20:40:10 +00005981 In->getName()+".not"), *ICI);
5982
5983 return ReplaceInstUsesWith(SI, In);
5984 }
5985 }
5986 }
5987
Dan Gohman81b28ce2008-09-16 18:46:06 +00005988 if (CmpLHS == TrueVal && CmpRHS == FalseVal) {
5989 // Transform (X == Y) ? X : Y -> Y
5990 if (Pred == ICmpInst::ICMP_EQ)
5991 return ReplaceInstUsesWith(SI, FalseVal);
5992 // Transform (X != Y) ? X : Y -> X
5993 if (Pred == ICmpInst::ICMP_NE)
5994 return ReplaceInstUsesWith(SI, TrueVal);
5995 /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
5996
5997 } else if (CmpLHS == FalseVal && CmpRHS == TrueVal) {
5998 // Transform (X == Y) ? Y : X -> X
5999 if (Pred == ICmpInst::ICMP_EQ)
6000 return ReplaceInstUsesWith(SI, FalseVal);
6001 // Transform (X != Y) ? Y : X -> Y
6002 if (Pred == ICmpInst::ICMP_NE)
6003 return ReplaceInstUsesWith(SI, TrueVal);
6004 /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
6005 }
Dan Gohman81b28ce2008-09-16 18:46:06 +00006006 return Changed ? &SI : 0;
6007}
6008
Chris Lattnerc6df8f42009-09-27 20:18:49 +00006009
Chris Lattner7f239582009-10-22 00:17:26 +00006010/// CanSelectOperandBeMappingIntoPredBlock - SI is a select whose condition is a
6011/// PHI node (but the two may be in different blocks). See if the true/false
6012/// values (V) are live in all of the predecessor blocks of the PHI. For
6013/// example, cases like this cannot be mapped:
6014///
6015/// X = phi [ C1, BB1], [C2, BB2]
6016/// Y = add
6017/// Z = select X, Y, 0
6018///
6019/// because Y is not live in BB1/BB2.
6020///
6021static bool CanSelectOperandBeMappingIntoPredBlock(const Value *V,
6022 const SelectInst &SI) {
6023 // If the value is a non-instruction value like a constant or argument, it
6024 // can always be mapped.
6025 const Instruction *I = dyn_cast<Instruction>(V);
6026 if (I == 0) return true;
6027
6028 // If V is a PHI node defined in the same block as the condition PHI, we can
6029 // map the arguments.
6030 const PHINode *CondPHI = cast<PHINode>(SI.getCondition());
6031
6032 if (const PHINode *VP = dyn_cast<PHINode>(I))
6033 if (VP->getParent() == CondPHI->getParent())
6034 return true;
6035
6036 // Otherwise, if the PHI and select are defined in the same block and if V is
6037 // defined in a different block, then we can transform it.
6038 if (SI.getParent() == CondPHI->getParent() &&
6039 I->getParent() != CondPHI->getParent())
6040 return true;
6041
6042 // Otherwise we have a 'hard' case and we can't tell without doing more
6043 // detailed dominator based analysis, punt.
6044 return false;
6045}
Chris Lattnerc6df8f42009-09-27 20:18:49 +00006046
Chris Lattnerb109b5c2009-12-21 06:03:05 +00006047/// FoldSPFofSPF - We have an SPF (e.g. a min or max) of an SPF of the form:
6048/// SPF2(SPF1(A, B), C)
6049Instruction *InstCombiner::FoldSPFofSPF(Instruction *Inner,
6050 SelectPatternFlavor SPF1,
6051 Value *A, Value *B,
6052 Instruction &Outer,
6053 SelectPatternFlavor SPF2, Value *C) {
6054 if (C == A || C == B) {
6055 // MAX(MAX(A, B), B) -> MAX(A, B)
6056 // MIN(MIN(a, b), a) -> MIN(a, b)
6057 if (SPF1 == SPF2)
6058 return ReplaceInstUsesWith(Outer, Inner);
6059
6060 // MAX(MIN(a, b), a) -> a
6061 // MIN(MAX(a, b), a) -> a
Daniel Dunbareddfaaf2009-12-21 23:27:57 +00006062 if ((SPF1 == SPF_SMIN && SPF2 == SPF_SMAX) ||
6063 (SPF1 == SPF_SMAX && SPF2 == SPF_SMIN) ||
6064 (SPF1 == SPF_UMIN && SPF2 == SPF_UMAX) ||
6065 (SPF1 == SPF_UMAX && SPF2 == SPF_UMIN))
Chris Lattnerb109b5c2009-12-21 06:03:05 +00006066 return ReplaceInstUsesWith(Outer, C);
6067 }
6068
6069 // TODO: MIN(MIN(A, 23), 97)
6070 return 0;
6071}
6072
6073
6074
6075
Chris Lattner3d69f462004-03-12 05:52:32 +00006076Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
Chris Lattnerc32b30a2004-03-30 19:37:13 +00006077 Value *CondVal = SI.getCondition();
6078 Value *TrueVal = SI.getTrueValue();
6079 Value *FalseVal = SI.getFalseValue();
6080
6081 // select true, X, Y -> X
6082 // select false, X, Y -> Y
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00006083 if (ConstantInt *C = dyn_cast<ConstantInt>(CondVal))
Reid Spencer579dca12007-01-12 04:24:46 +00006084 return ReplaceInstUsesWith(SI, C->getZExtValue() ? TrueVal : FalseVal);
Chris Lattnerc32b30a2004-03-30 19:37:13 +00006085
6086 // select C, X, X -> X
6087 if (TrueVal == FalseVal)
6088 return ReplaceInstUsesWith(SI, TrueVal);
6089
Chris Lattnere87597f2004-10-16 18:11:37 +00006090 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
6091 return ReplaceInstUsesWith(SI, FalseVal);
6092 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
6093 return ReplaceInstUsesWith(SI, TrueVal);
6094 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
6095 if (isa<Constant>(TrueVal))
6096 return ReplaceInstUsesWith(SI, TrueVal);
6097 else
6098 return ReplaceInstUsesWith(SI, FalseVal);
6099 }
6100
Chris Lattner4de84762010-01-04 07:02:48 +00006101 if (SI.getType() == Type::getInt1Ty(SI.getContext())) {
Reid Spencera54b7cb2007-01-12 07:05:14 +00006102 if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) {
Reid Spencer579dca12007-01-12 04:24:46 +00006103 if (C->getZExtValue()) {
Chris Lattner0c199a72004-04-08 04:43:23 +00006104 // Change: A = select B, true, C --> A = or B, C
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006105 return BinaryOperator::CreateOr(CondVal, FalseVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00006106 } else {
6107 // Change: A = select B, false, C --> A = and !B, C
6108 Value *NotCond =
Dan Gohman4ae51262009-08-12 16:23:25 +00006109 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Chris Lattner0c199a72004-04-08 04:43:23 +00006110 "not."+CondVal->getName()), SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006111 return BinaryOperator::CreateAnd(NotCond, FalseVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00006112 }
Reid Spencera54b7cb2007-01-12 07:05:14 +00006113 } else if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) {
Reid Spencer579dca12007-01-12 04:24:46 +00006114 if (C->getZExtValue() == false) {
Chris Lattner0c199a72004-04-08 04:43:23 +00006115 // Change: A = select B, C, false --> A = and B, C
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006116 return BinaryOperator::CreateAnd(CondVal, TrueVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00006117 } else {
6118 // Change: A = select B, C, true --> A = or !B, C
6119 Value *NotCond =
Dan Gohman4ae51262009-08-12 16:23:25 +00006120 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Chris Lattner0c199a72004-04-08 04:43:23 +00006121 "not."+CondVal->getName()), SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006122 return BinaryOperator::CreateOr(NotCond, TrueVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00006123 }
6124 }
Chris Lattnercfa59752007-11-25 21:27:53 +00006125
6126 // select a, b, a -> a&b
6127 // select a, a, b -> a|b
6128 if (CondVal == TrueVal)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006129 return BinaryOperator::CreateOr(CondVal, FalseVal);
Chris Lattnercfa59752007-11-25 21:27:53 +00006130 else if (CondVal == FalseVal)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006131 return BinaryOperator::CreateAnd(CondVal, TrueVal);
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00006132 }
Chris Lattner0c199a72004-04-08 04:43:23 +00006133
Chris Lattner2eefe512004-04-09 19:05:30 +00006134 // Selecting between two integer constants?
6135 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
6136 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
Chris Lattnerba417832007-04-11 06:12:58 +00006137 // select C, 1, 0 -> zext C to int
Reid Spencer2ec619a2007-03-23 21:24:59 +00006138 if (FalseValC->isZero() && TrueValC->getValue() == 1) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006139 return CastInst::Create(Instruction::ZExt, CondVal, SI.getType());
Reid Spencer2ec619a2007-03-23 21:24:59 +00006140 } else if (TrueValC->isZero() && FalseValC->getValue() == 1) {
Chris Lattnerba417832007-04-11 06:12:58 +00006141 // select C, 0, 1 -> zext !C to int
Chris Lattner2eefe512004-04-09 19:05:30 +00006142 Value *NotCond =
Dan Gohman4ae51262009-08-12 16:23:25 +00006143 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Chris Lattner82e14fe2004-04-09 18:19:44 +00006144 "not."+CondVal->getName()), SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006145 return CastInst::Create(Instruction::ZExt, NotCond, SI.getType());
Chris Lattner82e14fe2004-04-09 18:19:44 +00006146 }
Chris Lattner457dd822004-06-09 07:59:58 +00006147
Reid Spencere4d87aa2006-12-23 06:05:41 +00006148 if (ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition())) {
Chris Lattnerb8456462006-09-20 04:44:59 +00006149 // If one of the constants is zero (we know they can't both be) and we
Chris Lattnerba417832007-04-11 06:12:58 +00006150 // have an icmp instruction with zero, and we have an 'and' with the
Chris Lattnerb8456462006-09-20 04:44:59 +00006151 // non-constant value, eliminate this whole mess. This corresponds to
6152 // cases like this: ((X & 27) ? 27 : 0)
Reid Spencer2ec619a2007-03-23 21:24:59 +00006153 if (TrueValC->isZero() || FalseValC->isZero())
Chris Lattner65b72ba2006-09-18 04:22:48 +00006154 if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
Chris Lattner457dd822004-06-09 07:59:58 +00006155 cast<Constant>(IC->getOperand(1))->isNullValue())
6156 if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
6157 if (ICA->getOpcode() == Instruction::And &&
Misha Brukmanfd939082005-04-21 23:48:37 +00006158 isa<ConstantInt>(ICA->getOperand(1)) &&
6159 (ICA->getOperand(1) == TrueValC ||
6160 ICA->getOperand(1) == FalseValC) &&
Chris Lattner457dd822004-06-09 07:59:58 +00006161 isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
6162 // Okay, now we know that everything is set up, we just don't
Reid Spencere4d87aa2006-12-23 06:05:41 +00006163 // know whether we have a icmp_ne or icmp_eq and whether the
6164 // true or false val is the zero.
Reid Spencer2ec619a2007-03-23 21:24:59 +00006165 bool ShouldNotVal = !TrueValC->isZero();
Reid Spencere4d87aa2006-12-23 06:05:41 +00006166 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
Chris Lattner457dd822004-06-09 07:59:58 +00006167 Value *V = ICA;
6168 if (ShouldNotVal)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006169 V = InsertNewInstBefore(BinaryOperator::Create(
Chris Lattner457dd822004-06-09 07:59:58 +00006170 Instruction::Xor, V, ICA->getOperand(1)), SI);
6171 return ReplaceInstUsesWith(SI, V);
6172 }
Chris Lattnerb8456462006-09-20 04:44:59 +00006173 }
Chris Lattnerc32b30a2004-03-30 19:37:13 +00006174 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00006175
6176 // See if we are selecting two values based on a comparison of the two values.
Reid Spencere4d87aa2006-12-23 06:05:41 +00006177 if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
6178 if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
Chris Lattnerd76956d2004-04-10 22:21:27 +00006179 // Transform (X == Y) ? X : Y -> Y
Dale Johannesen5a2174f2007-10-03 17:45:27 +00006180 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
6181 // This is not safe in general for floating point:
6182 // consider X== -0, Y== +0.
6183 // It becomes safe if either operand is a nonzero constant.
6184 ConstantFP *CFPt, *CFPf;
6185 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
6186 !CFPt->getValueAPF().isZero()) ||
6187 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
6188 !CFPf->getValueAPF().isZero()))
Chris Lattnerd76956d2004-04-10 22:21:27 +00006189 return ReplaceInstUsesWith(SI, FalseVal);
Dale Johannesen5a2174f2007-10-03 17:45:27 +00006190 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00006191 // Transform (X != Y) ? X : Y -> X
Reid Spencere4d87aa2006-12-23 06:05:41 +00006192 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
Chris Lattnerd76956d2004-04-10 22:21:27 +00006193 return ReplaceInstUsesWith(SI, TrueVal);
Dan Gohman81b28ce2008-09-16 18:46:06 +00006194 // NOTE: if we wanted to, this is where to detect MIN/MAX
Chris Lattnerd76956d2004-04-10 22:21:27 +00006195
Reid Spencere4d87aa2006-12-23 06:05:41 +00006196 } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
Chris Lattnerd76956d2004-04-10 22:21:27 +00006197 // Transform (X == Y) ? Y : X -> X
Dale Johannesen5a2174f2007-10-03 17:45:27 +00006198 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
6199 // This is not safe in general for floating point:
6200 // consider X== -0, Y== +0.
6201 // It becomes safe if either operand is a nonzero constant.
6202 ConstantFP *CFPt, *CFPf;
6203 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
6204 !CFPt->getValueAPF().isZero()) ||
6205 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
6206 !CFPf->getValueAPF().isZero()))
6207 return ReplaceInstUsesWith(SI, FalseVal);
6208 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00006209 // Transform (X != Y) ? Y : X -> Y
Reid Spencere4d87aa2006-12-23 06:05:41 +00006210 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
6211 return ReplaceInstUsesWith(SI, TrueVal);
Dan Gohman81b28ce2008-09-16 18:46:06 +00006212 // NOTE: if we wanted to, this is where to detect MIN/MAX
Reid Spencere4d87aa2006-12-23 06:05:41 +00006213 }
Dan Gohman81b28ce2008-09-16 18:46:06 +00006214 // NOTE: if we wanted to, this is where to detect ABS
Reid Spencere4d87aa2006-12-23 06:05:41 +00006215 }
6216
6217 // See if we are selecting two values based on a comparison of the two values.
Dan Gohman81b28ce2008-09-16 18:46:06 +00006218 if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal))
6219 if (Instruction *Result = visitSelectInstWithICmp(SI, ICI))
6220 return Result;
Misha Brukmanfd939082005-04-21 23:48:37 +00006221
Chris Lattner87875da2005-01-13 22:52:24 +00006222 if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
6223 if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
6224 if (TI->hasOneUse() && FI->hasOneUse()) {
Chris Lattner87875da2005-01-13 22:52:24 +00006225 Instruction *AddOp = 0, *SubOp = 0;
6226
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00006227 // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
6228 if (TI->getOpcode() == FI->getOpcode())
6229 if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
6230 return IV;
6231
6232 // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))). This is
6233 // even legal for FP.
Dan Gohmanae3a0be2009-06-04 22:49:04 +00006234 if ((TI->getOpcode() == Instruction::Sub &&
6235 FI->getOpcode() == Instruction::Add) ||
6236 (TI->getOpcode() == Instruction::FSub &&
6237 FI->getOpcode() == Instruction::FAdd)) {
Chris Lattner87875da2005-01-13 22:52:24 +00006238 AddOp = FI; SubOp = TI;
Dan Gohmanae3a0be2009-06-04 22:49:04 +00006239 } else if ((FI->getOpcode() == Instruction::Sub &&
6240 TI->getOpcode() == Instruction::Add) ||
6241 (FI->getOpcode() == Instruction::FSub &&
6242 TI->getOpcode() == Instruction::FAdd)) {
Chris Lattner87875da2005-01-13 22:52:24 +00006243 AddOp = TI; SubOp = FI;
6244 }
6245
6246 if (AddOp) {
6247 Value *OtherAddOp = 0;
6248 if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
6249 OtherAddOp = AddOp->getOperand(1);
6250 } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
6251 OtherAddOp = AddOp->getOperand(0);
6252 }
6253
6254 if (OtherAddOp) {
Chris Lattner97f37a42006-02-24 18:05:58 +00006255 // So at this point we know we have (Y -> OtherAddOp):
6256 // select C, (add X, Y), (sub X, Z)
6257 Value *NegVal; // Compute -Z
6258 if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00006259 NegVal = ConstantExpr::getNeg(C);
Chris Lattner97f37a42006-02-24 18:05:58 +00006260 } else {
6261 NegVal = InsertNewInstBefore(
Dan Gohman4ae51262009-08-12 16:23:25 +00006262 BinaryOperator::CreateNeg(SubOp->getOperand(1),
Owen Anderson0a5372e2009-07-13 04:09:18 +00006263 "tmp"), SI);
Chris Lattner87875da2005-01-13 22:52:24 +00006264 }
Chris Lattner97f37a42006-02-24 18:05:58 +00006265
6266 Value *NewTrueOp = OtherAddOp;
6267 Value *NewFalseOp = NegVal;
6268 if (AddOp != TI)
6269 std::swap(NewTrueOp, NewFalseOp);
6270 Instruction *NewSel =
Gabor Greifb1dbcd82008-05-15 10:04:30 +00006271 SelectInst::Create(CondVal, NewTrueOp,
6272 NewFalseOp, SI.getName() + ".p");
Chris Lattner97f37a42006-02-24 18:05:58 +00006273
6274 NewSel = InsertNewInstBefore(NewSel, SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006275 return BinaryOperator::CreateAdd(SubOp->getOperand(0), NewSel);
Chris Lattner87875da2005-01-13 22:52:24 +00006276 }
6277 }
6278 }
Misha Brukmanfd939082005-04-21 23:48:37 +00006279
Chris Lattnere576b912004-04-09 23:46:01 +00006280 // See if we can fold the select into one of our operands.
Chris Lattner42a75512007-01-15 02:27:26 +00006281 if (SI.getType()->isInteger()) {
Chris Lattnerb109b5c2009-12-21 06:03:05 +00006282 if (Instruction *FoldI = FoldSelectIntoOp(SI, TrueVal, FalseVal))
Evan Chengde621922009-03-31 20:42:45 +00006283 return FoldI;
Chris Lattnerb109b5c2009-12-21 06:03:05 +00006284
6285 // MAX(MAX(a, b), a) -> MAX(a, b)
6286 // MIN(MIN(a, b), a) -> MIN(a, b)
6287 // MAX(MIN(a, b), a) -> a
6288 // MIN(MAX(a, b), a) -> a
6289 Value *LHS, *RHS, *LHS2, *RHS2;
6290 if (SelectPatternFlavor SPF = MatchSelectPattern(&SI, LHS, RHS)) {
6291 if (SelectPatternFlavor SPF2 = MatchSelectPattern(LHS, LHS2, RHS2))
6292 if (Instruction *R = FoldSPFofSPF(cast<Instruction>(LHS),SPF2,LHS2,RHS2,
6293 SI, SPF, RHS))
6294 return R;
6295 if (SelectPatternFlavor SPF2 = MatchSelectPattern(RHS, LHS2, RHS2))
6296 if (Instruction *R = FoldSPFofSPF(cast<Instruction>(RHS),SPF2,LHS2,RHS2,
6297 SI, SPF, LHS))
6298 return R;
6299 }
6300
6301 // TODO.
6302 // ABS(-X) -> ABS(X)
6303 // ABS(ABS(X)) -> ABS(X)
Chris Lattnere576b912004-04-09 23:46:01 +00006304 }
Chris Lattnera1df33c2005-04-24 07:30:14 +00006305
Chris Lattner7f239582009-10-22 00:17:26 +00006306 // See if we can fold the select into a phi node if the condition is a select.
6307 if (isa<PHINode>(SI.getCondition()))
6308 // The true/false values have to be live in the PHI predecessor's blocks.
6309 if (CanSelectOperandBeMappingIntoPredBlock(TrueVal, SI) &&
6310 CanSelectOperandBeMappingIntoPredBlock(FalseVal, SI))
6311 if (Instruction *NV = FoldOpIntoPhi(SI))
6312 return NV;
Chris Lattner5d1704d2009-09-27 19:57:57 +00006313
Chris Lattnera1df33c2005-04-24 07:30:14 +00006314 if (BinaryOperator::isNot(CondVal)) {
6315 SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
6316 SI.setOperand(1, FalseVal);
6317 SI.setOperand(2, TrueVal);
6318 return &SI;
6319 }
6320
Chris Lattner3d69f462004-03-12 05:52:32 +00006321 return 0;
6322}
6323
Dan Gohmaneee962e2008-04-10 18:43:06 +00006324/// EnforceKnownAlignment - If the specified pointer points to an object that
6325/// we control, modify the object's alignment to PrefAlign. This isn't
6326/// often possible though. If alignment is important, a more reliable approach
6327/// is to simply align all global variables and allocation instructions to
6328/// their preferred alignment from the beginning.
6329///
6330static unsigned EnforceKnownAlignment(Value *V,
6331 unsigned Align, unsigned PrefAlign) {
Chris Lattnerf2369f22007-08-09 19:05:49 +00006332
Dan Gohmaneee962e2008-04-10 18:43:06 +00006333 User *U = dyn_cast<User>(V);
6334 if (!U) return Align;
6335
Dan Gohmanca178902009-07-17 20:47:02 +00006336 switch (Operator::getOpcode(U)) {
Dan Gohmaneee962e2008-04-10 18:43:06 +00006337 default: break;
6338 case Instruction::BitCast:
6339 return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
6340 case Instruction::GetElementPtr: {
Chris Lattner95a959d2006-03-06 20:18:44 +00006341 // If all indexes are zero, it is just the alignment of the base pointer.
6342 bool AllZeroOperands = true;
Gabor Greif52ed3632008-06-12 21:51:29 +00006343 for (User::op_iterator i = U->op_begin() + 1, e = U->op_end(); i != e; ++i)
Gabor Greif177dd3f2008-06-12 21:37:33 +00006344 if (!isa<Constant>(*i) ||
6345 !cast<Constant>(*i)->isNullValue()) {
Chris Lattner95a959d2006-03-06 20:18:44 +00006346 AllZeroOperands = false;
6347 break;
6348 }
Chris Lattnerf2369f22007-08-09 19:05:49 +00006349
6350 if (AllZeroOperands) {
6351 // Treat this like a bitcast.
Dan Gohmaneee962e2008-04-10 18:43:06 +00006352 return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
Chris Lattnerf2369f22007-08-09 19:05:49 +00006353 }
Dan Gohmaneee962e2008-04-10 18:43:06 +00006354 break;
Chris Lattner95a959d2006-03-06 20:18:44 +00006355 }
Dan Gohmaneee962e2008-04-10 18:43:06 +00006356 }
6357
6358 if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
6359 // If there is a large requested alignment and we can, bump up the alignment
6360 // of the global.
6361 if (!GV->isDeclaration()) {
Dan Gohmanecd0fb52009-02-16 23:02:21 +00006362 if (GV->getAlignment() >= PrefAlign)
6363 Align = GV->getAlignment();
6364 else {
6365 GV->setAlignment(PrefAlign);
6366 Align = PrefAlign;
6367 }
Dan Gohmaneee962e2008-04-10 18:43:06 +00006368 }
Chris Lattner42ebefa2009-09-27 21:42:46 +00006369 } else if (AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
6370 // If there is a requested alignment and if this is an alloca, round up.
6371 if (AI->getAlignment() >= PrefAlign)
6372 Align = AI->getAlignment();
6373 else {
6374 AI->setAlignment(PrefAlign);
6375 Align = PrefAlign;
Dan Gohmaneee962e2008-04-10 18:43:06 +00006376 }
6377 }
6378
6379 return Align;
6380}
6381
6382/// GetOrEnforceKnownAlignment - If the specified pointer has an alignment that
6383/// we can determine, return it, otherwise return 0. If PrefAlign is specified,
6384/// and it is more than the alignment of the ultimate object, see if we can
6385/// increase the alignment of the ultimate object, making this check succeed.
6386unsigned InstCombiner::GetOrEnforceKnownAlignment(Value *V,
6387 unsigned PrefAlign) {
6388 unsigned BitWidth = TD ? TD->getTypeSizeInBits(V->getType()) :
6389 sizeof(PrefAlign) * CHAR_BIT;
6390 APInt Mask = APInt::getAllOnesValue(BitWidth);
6391 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
6392 ComputeMaskedBits(V, Mask, KnownZero, KnownOne);
6393 unsigned TrailZ = KnownZero.countTrailingOnes();
6394 unsigned Align = 1u << std::min(BitWidth - 1, TrailZ);
6395
6396 if (PrefAlign > Align)
6397 Align = EnforceKnownAlignment(V, Align, PrefAlign);
6398
6399 // We don't need to make any adjustment.
6400 return Align;
Chris Lattner95a959d2006-03-06 20:18:44 +00006401}
6402
Chris Lattnerf497b022008-01-13 23:50:23 +00006403Instruction *InstCombiner::SimplifyMemTransfer(MemIntrinsic *MI) {
Dan Gohmaneee962e2008-04-10 18:43:06 +00006404 unsigned DstAlign = GetOrEnforceKnownAlignment(MI->getOperand(1));
Dan Gohmanbc989d42009-02-22 18:06:32 +00006405 unsigned SrcAlign = GetOrEnforceKnownAlignment(MI->getOperand(2));
Chris Lattnerf497b022008-01-13 23:50:23 +00006406 unsigned MinAlign = std::min(DstAlign, SrcAlign);
Chris Lattnerdfe964c2009-03-08 03:59:00 +00006407 unsigned CopyAlign = MI->getAlignment();
Chris Lattnerf497b022008-01-13 23:50:23 +00006408
6409 if (CopyAlign < MinAlign) {
Owen Andersoneed707b2009-07-24 23:12:02 +00006410 MI->setAlignment(ConstantInt::get(MI->getAlignmentType(),
Owen Andersona547b472009-07-09 18:36:20 +00006411 MinAlign, false));
Chris Lattnerf497b022008-01-13 23:50:23 +00006412 return MI;
6413 }
6414
6415 // If MemCpyInst length is 1/2/4/8 bytes then replace memcpy with
6416 // load/store.
6417 ConstantInt *MemOpLength = dyn_cast<ConstantInt>(MI->getOperand(3));
6418 if (MemOpLength == 0) return 0;
6419
Chris Lattner37ac6082008-01-14 00:28:35 +00006420 // Source and destination pointer types are always "i8*" for intrinsic. See
6421 // if the size is something we can handle with a single primitive load/store.
6422 // A single load+store correctly handles overlapping memory in the memmove
6423 // case.
Chris Lattnerf497b022008-01-13 23:50:23 +00006424 unsigned Size = MemOpLength->getZExtValue();
Chris Lattner69ea9d22008-04-30 06:39:11 +00006425 if (Size == 0) return MI; // Delete this mem transfer.
6426
6427 if (Size > 8 || (Size&(Size-1)))
Chris Lattner37ac6082008-01-14 00:28:35 +00006428 return 0; // If not 1/2/4/8 bytes, exit.
Chris Lattnerf497b022008-01-13 23:50:23 +00006429
Chris Lattner37ac6082008-01-14 00:28:35 +00006430 // Use an integer load+store unless we can find something better.
Owen Andersond672ecb2009-07-03 00:17:18 +00006431 Type *NewPtrTy =
Chris Lattner4de84762010-01-04 07:02:48 +00006432 PointerType::getUnqual(IntegerType::get(MI->getContext(), Size<<3));
Chris Lattner37ac6082008-01-14 00:28:35 +00006433
6434 // Memcpy forces the use of i8* for the source and destination. That means
6435 // that if you're using memcpy to move one double around, you'll get a cast
6436 // from double* to i8*. We'd much rather use a double load+store rather than
6437 // an i64 load+store, here because this improves the odds that the source or
6438 // dest address will be promotable. See if we can find a better type than the
6439 // integer datatype.
6440 if (Value *Op = getBitCastOperand(MI->getOperand(1))) {
6441 const Type *SrcETy = cast<PointerType>(Op->getType())->getElementType();
Dan Gohmance9fe9f2009-07-21 23:21:54 +00006442 if (TD && SrcETy->isSized() && TD->getTypeStoreSize(SrcETy) == Size) {
Chris Lattner37ac6082008-01-14 00:28:35 +00006443 // The SrcETy might be something like {{{double}}} or [1 x double]. Rip
6444 // down through these levels if so.
Dan Gohman8f8e2692008-05-23 01:52:21 +00006445 while (!SrcETy->isSingleValueType()) {
Chris Lattner37ac6082008-01-14 00:28:35 +00006446 if (const StructType *STy = dyn_cast<StructType>(SrcETy)) {
6447 if (STy->getNumElements() == 1)
6448 SrcETy = STy->getElementType(0);
6449 else
6450 break;
6451 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcETy)) {
6452 if (ATy->getNumElements() == 1)
6453 SrcETy = ATy->getElementType();
6454 else
6455 break;
6456 } else
6457 break;
6458 }
6459
Dan Gohman8f8e2692008-05-23 01:52:21 +00006460 if (SrcETy->isSingleValueType())
Owen Andersondebcb012009-07-29 22:17:13 +00006461 NewPtrTy = PointerType::getUnqual(SrcETy);
Chris Lattner37ac6082008-01-14 00:28:35 +00006462 }
6463 }
6464
6465
Chris Lattnerf497b022008-01-13 23:50:23 +00006466 // If the memcpy/memmove provides better alignment info than we can
6467 // infer, use it.
6468 SrcAlign = std::max(SrcAlign, CopyAlign);
6469 DstAlign = std::max(DstAlign, CopyAlign);
6470
Chris Lattner08142f22009-08-30 19:47:22 +00006471 Value *Src = Builder->CreateBitCast(MI->getOperand(2), NewPtrTy);
6472 Value *Dest = Builder->CreateBitCast(MI->getOperand(1), NewPtrTy);
Chris Lattner37ac6082008-01-14 00:28:35 +00006473 Instruction *L = new LoadInst(Src, "tmp", false, SrcAlign);
6474 InsertNewInstBefore(L, *MI);
6475 InsertNewInstBefore(new StoreInst(L, Dest, false, DstAlign), *MI);
6476
6477 // Set the size of the copy to 0, it will be deleted on the next iteration.
Owen Andersona7235ea2009-07-31 20:28:14 +00006478 MI->setOperand(3, Constant::getNullValue(MemOpLength->getType()));
Chris Lattner37ac6082008-01-14 00:28:35 +00006479 return MI;
Chris Lattnerf497b022008-01-13 23:50:23 +00006480}
Chris Lattner3d69f462004-03-12 05:52:32 +00006481
Chris Lattner69ea9d22008-04-30 06:39:11 +00006482Instruction *InstCombiner::SimplifyMemSet(MemSetInst *MI) {
6483 unsigned Alignment = GetOrEnforceKnownAlignment(MI->getDest());
Chris Lattnerdfe964c2009-03-08 03:59:00 +00006484 if (MI->getAlignment() < Alignment) {
Owen Andersoneed707b2009-07-24 23:12:02 +00006485 MI->setAlignment(ConstantInt::get(MI->getAlignmentType(),
Owen Andersona547b472009-07-09 18:36:20 +00006486 Alignment, false));
Chris Lattner69ea9d22008-04-30 06:39:11 +00006487 return MI;
6488 }
6489
6490 // Extract the length and alignment and fill if they are constant.
6491 ConstantInt *LenC = dyn_cast<ConstantInt>(MI->getLength());
6492 ConstantInt *FillC = dyn_cast<ConstantInt>(MI->getValue());
Chris Lattner4de84762010-01-04 07:02:48 +00006493 if (!LenC || !FillC || FillC->getType() != Type::getInt8Ty(MI->getContext()))
Chris Lattner69ea9d22008-04-30 06:39:11 +00006494 return 0;
6495 uint64_t Len = LenC->getZExtValue();
Chris Lattnerdfe964c2009-03-08 03:59:00 +00006496 Alignment = MI->getAlignment();
Chris Lattner69ea9d22008-04-30 06:39:11 +00006497
6498 // If the length is zero, this is a no-op
6499 if (Len == 0) return MI; // memset(d,c,0,a) -> noop
6500
6501 // memset(s,c,n) -> store s, c (for n=1,2,4,8)
6502 if (Len <= 8 && isPowerOf2_32((uint32_t)Len)) {
Chris Lattner4de84762010-01-04 07:02:48 +00006503 const Type *ITy = IntegerType::get(MI->getContext(), Len*8); // n=1 -> i8.
Chris Lattner69ea9d22008-04-30 06:39:11 +00006504
6505 Value *Dest = MI->getDest();
Chris Lattner08142f22009-08-30 19:47:22 +00006506 Dest = Builder->CreateBitCast(Dest, PointerType::getUnqual(ITy));
Chris Lattner69ea9d22008-04-30 06:39:11 +00006507
6508 // Alignment 0 is identity for alignment 1 for memset, but not store.
6509 if (Alignment == 0) Alignment = 1;
6510
6511 // Extract the fill value and store.
6512 uint64_t Fill = FillC->getZExtValue()*0x0101010101010101ULL;
Owen Andersoneed707b2009-07-24 23:12:02 +00006513 InsertNewInstBefore(new StoreInst(ConstantInt::get(ITy, Fill),
Owen Andersond672ecb2009-07-03 00:17:18 +00006514 Dest, false, Alignment), *MI);
Chris Lattner69ea9d22008-04-30 06:39:11 +00006515
6516 // Set the size of the copy to 0, it will be deleted on the next iteration.
Owen Andersona7235ea2009-07-31 20:28:14 +00006517 MI->setLength(Constant::getNullValue(LenC->getType()));
Chris Lattner69ea9d22008-04-30 06:39:11 +00006518 return MI;
6519 }
6520
6521 return 0;
6522}
6523
6524
Chris Lattner8b0ea312006-01-13 20:11:04 +00006525/// visitCallInst - CallInst simplification. This mostly only handles folding
6526/// of intrinsic instructions. For normal calls, it allows visitCallSite to do
6527/// the heavy lifting.
6528///
Chris Lattner9fe38862003-06-19 17:00:31 +00006529Instruction *InstCombiner::visitCallInst(CallInst &CI) {
Victor Hernandez66284e02009-10-24 04:23:03 +00006530 if (isFreeCall(&CI))
6531 return visitFree(CI);
6532
Chris Lattneraab6ec42009-05-13 17:39:14 +00006533 // If the caller function is nounwind, mark the call as nounwind, even if the
6534 // callee isn't.
6535 if (CI.getParent()->getParent()->doesNotThrow() &&
6536 !CI.doesNotThrow()) {
6537 CI.setDoesNotThrow();
6538 return &CI;
6539 }
6540
Chris Lattner8b0ea312006-01-13 20:11:04 +00006541 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
6542 if (!II) return visitCallSite(&CI);
6543
Chris Lattner7bcc0e72004-02-28 05:22:00 +00006544 // Intrinsics cannot occur in an invoke, so handle them here instead of in
6545 // visitCallSite.
Chris Lattner8b0ea312006-01-13 20:11:04 +00006546 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
Chris Lattner35b9e482004-10-12 04:52:52 +00006547 bool Changed = false;
6548
6549 // memmove/cpy/set of zero bytes is a noop.
6550 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
6551 if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
6552
Chris Lattner35b9e482004-10-12 04:52:52 +00006553 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
Reid Spencerb83eb642006-10-20 07:07:24 +00006554 if (CI->getZExtValue() == 1) {
Chris Lattner35b9e482004-10-12 04:52:52 +00006555 // Replace the instruction with just byte operations. We would
6556 // transform other cases to loads/stores, but we don't know if
6557 // alignment is sufficient.
6558 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +00006559 }
6560
Chris Lattner35b9e482004-10-12 04:52:52 +00006561 // If we have a memmove and the source operation is a constant global,
6562 // then the source and dest pointers can't alias, so we can change this
6563 // into a call to memcpy.
Chris Lattnerf497b022008-01-13 23:50:23 +00006564 if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI)) {
Chris Lattner35b9e482004-10-12 04:52:52 +00006565 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
6566 if (GVSrc->isConstant()) {
6567 Module *M = CI.getParent()->getParent()->getParent();
Chris Lattner824b9582008-11-21 16:42:48 +00006568 Intrinsic::ID MemCpyID = Intrinsic::memcpy;
6569 const Type *Tys[1];
6570 Tys[0] = CI.getOperand(3)->getType();
6571 CI.setOperand(0,
6572 Intrinsic::getDeclaration(M, MemCpyID, Tys, 1));
Chris Lattner35b9e482004-10-12 04:52:52 +00006573 Changed = true;
6574 }
Eli Friedman0c826d92009-12-17 21:07:31 +00006575 }
Chris Lattnera935db82008-05-28 05:30:41 +00006576
Eli Friedman0c826d92009-12-17 21:07:31 +00006577 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(MI)) {
Chris Lattnera935db82008-05-28 05:30:41 +00006578 // memmove(x,x,size) -> noop.
Eli Friedman0c826d92009-12-17 21:07:31 +00006579 if (MTI->getSource() == MTI->getDest())
Chris Lattnera935db82008-05-28 05:30:41 +00006580 return EraseInstFromFunction(CI);
Chris Lattner95a959d2006-03-06 20:18:44 +00006581 }
Chris Lattner35b9e482004-10-12 04:52:52 +00006582
Chris Lattner95a959d2006-03-06 20:18:44 +00006583 // If we can determine a pointer alignment that is bigger than currently
6584 // set, update the alignment.
Chris Lattner3ce5e882009-03-08 03:37:16 +00006585 if (isa<MemTransferInst>(MI)) {
Chris Lattnerf497b022008-01-13 23:50:23 +00006586 if (Instruction *I = SimplifyMemTransfer(MI))
6587 return I;
Chris Lattner69ea9d22008-04-30 06:39:11 +00006588 } else if (MemSetInst *MSI = dyn_cast<MemSetInst>(MI)) {
6589 if (Instruction *I = SimplifyMemSet(MSI))
6590 return I;
Chris Lattner95a959d2006-03-06 20:18:44 +00006591 }
6592
Chris Lattner8b0ea312006-01-13 20:11:04 +00006593 if (Changed) return II;
Chris Lattner0521e3c2008-06-18 04:33:20 +00006594 }
6595
6596 switch (II->getIntrinsicID()) {
6597 default: break;
6598 case Intrinsic::bswap:
6599 // bswap(bswap(x)) -> x
6600 if (IntrinsicInst *Operand = dyn_cast<IntrinsicInst>(II->getOperand(1)))
6601 if (Operand->getIntrinsicID() == Intrinsic::bswap)
6602 return ReplaceInstUsesWith(CI, Operand->getOperand(1));
Chris Lattnere33d4132010-01-01 18:34:40 +00006603
6604 // bswap(trunc(bswap(x))) -> trunc(lshr(x, c))
6605 if (TruncInst *TI = dyn_cast<TruncInst>(II->getOperand(1))) {
6606 if (IntrinsicInst *Operand = dyn_cast<IntrinsicInst>(TI->getOperand(0)))
6607 if (Operand->getIntrinsicID() == Intrinsic::bswap) {
6608 unsigned C = Operand->getType()->getPrimitiveSizeInBits() -
6609 TI->getType()->getPrimitiveSizeInBits();
6610 Value *CV = ConstantInt::get(Operand->getType(), C);
6611 Value *V = Builder->CreateLShr(Operand->getOperand(1), CV);
6612 return new TruncInst(V, TI->getType());
6613 }
6614 }
6615
Chris Lattner0521e3c2008-06-18 04:33:20 +00006616 break;
Chris Lattnerd27f9112010-01-01 01:52:15 +00006617 case Intrinsic::powi:
6618 if (ConstantInt *Power = dyn_cast<ConstantInt>(II->getOperand(2))) {
6619 // powi(x, 0) -> 1.0
6620 if (Power->isZero())
6621 return ReplaceInstUsesWith(CI, ConstantFP::get(CI.getType(), 1.0));
6622 // powi(x, 1) -> x
6623 if (Power->isOne())
6624 return ReplaceInstUsesWith(CI, II->getOperand(1));
6625 // powi(x, -1) -> 1/x
Chris Lattnerf9ead872010-01-01 01:54:08 +00006626 if (Power->isAllOnesValue())
6627 return BinaryOperator::CreateFDiv(ConstantFP::get(CI.getType(), 1.0),
6628 II->getOperand(1));
Chris Lattnerd27f9112010-01-01 01:52:15 +00006629 }
6630 break;
6631
Chris Lattner2bbac752009-11-26 21:42:47 +00006632 case Intrinsic::uadd_with_overflow: {
6633 Value *LHS = II->getOperand(1), *RHS = II->getOperand(2);
6634 const IntegerType *IT = cast<IntegerType>(II->getOperand(1)->getType());
6635 uint32_t BitWidth = IT->getBitWidth();
6636 APInt Mask = APInt::getSignBit(BitWidth);
Chris Lattner998e25a2009-11-26 22:08:06 +00006637 APInt LHSKnownZero(BitWidth, 0);
6638 APInt LHSKnownOne(BitWidth, 0);
Chris Lattner2bbac752009-11-26 21:42:47 +00006639 ComputeMaskedBits(LHS, Mask, LHSKnownZero, LHSKnownOne);
6640 bool LHSKnownNegative = LHSKnownOne[BitWidth - 1];
6641 bool LHSKnownPositive = LHSKnownZero[BitWidth - 1];
6642
6643 if (LHSKnownNegative || LHSKnownPositive) {
Chris Lattner998e25a2009-11-26 22:08:06 +00006644 APInt RHSKnownZero(BitWidth, 0);
6645 APInt RHSKnownOne(BitWidth, 0);
Chris Lattner2bbac752009-11-26 21:42:47 +00006646 ComputeMaskedBits(RHS, Mask, RHSKnownZero, RHSKnownOne);
6647 bool RHSKnownNegative = RHSKnownOne[BitWidth - 1];
6648 bool RHSKnownPositive = RHSKnownZero[BitWidth - 1];
6649 if (LHSKnownNegative && RHSKnownNegative) {
6650 // The sign bit is set in both cases: this MUST overflow.
6651 // Create a simple add instruction, and insert it into the struct.
6652 Instruction *Add = BinaryOperator::CreateAdd(LHS, RHS, "", &CI);
6653 Worklist.Add(Add);
Chris Lattnercd188e92009-11-29 02:57:29 +00006654 Constant *V[] = {
Chris Lattner4de84762010-01-04 07:02:48 +00006655 UndefValue::get(LHS->getType()),ConstantInt::getTrue(II->getContext())
Chris Lattnercd188e92009-11-29 02:57:29 +00006656 };
Chris Lattner4de84762010-01-04 07:02:48 +00006657 Constant *Struct = ConstantStruct::get(II->getContext(), V, 2, false);
Chris Lattner2bbac752009-11-26 21:42:47 +00006658 return InsertValueInst::Create(Struct, Add, 0);
6659 }
6660
6661 if (LHSKnownPositive && RHSKnownPositive) {
6662 // The sign bit is clear in both cases: this CANNOT overflow.
6663 // Create a simple add instruction, and insert it into the struct.
6664 Instruction *Add = BinaryOperator::CreateNUWAdd(LHS, RHS, "", &CI);
6665 Worklist.Add(Add);
Chris Lattnercd188e92009-11-29 02:57:29 +00006666 Constant *V[] = {
Chris Lattner4de84762010-01-04 07:02:48 +00006667 UndefValue::get(LHS->getType()),
6668 ConstantInt::getFalse(II->getContext())
Chris Lattnercd188e92009-11-29 02:57:29 +00006669 };
Chris Lattner4de84762010-01-04 07:02:48 +00006670 Constant *Struct = ConstantStruct::get(II->getContext(), V, 2, false);
Chris Lattner2bbac752009-11-26 21:42:47 +00006671 return InsertValueInst::Create(Struct, Add, 0);
6672 }
6673 }
6674 }
6675 // FALL THROUGH uadd into sadd
6676 case Intrinsic::sadd_with_overflow:
6677 // Canonicalize constants into the RHS.
6678 if (isa<Constant>(II->getOperand(1)) &&
6679 !isa<Constant>(II->getOperand(2))) {
6680 Value *LHS = II->getOperand(1);
6681 II->setOperand(1, II->getOperand(2));
6682 II->setOperand(2, LHS);
6683 return II;
6684 }
6685
6686 // X + undef -> undef
6687 if (isa<UndefValue>(II->getOperand(2)))
6688 return ReplaceInstUsesWith(CI, UndefValue::get(II->getType()));
6689
6690 if (ConstantInt *RHS = dyn_cast<ConstantInt>(II->getOperand(2))) {
6691 // X + 0 -> {X, false}
6692 if (RHS->isZero()) {
6693 Constant *V[] = {
Chris Lattnercd188e92009-11-29 02:57:29 +00006694 UndefValue::get(II->getOperand(0)->getType()),
Chris Lattner4de84762010-01-04 07:02:48 +00006695 ConstantInt::getFalse(II->getContext())
Chris Lattner2bbac752009-11-26 21:42:47 +00006696 };
Chris Lattner4de84762010-01-04 07:02:48 +00006697 Constant *Struct = ConstantStruct::get(II->getContext(), V, 2, false);
Chris Lattner2bbac752009-11-26 21:42:47 +00006698 return InsertValueInst::Create(Struct, II->getOperand(1), 0);
6699 }
6700 }
6701 break;
6702 case Intrinsic::usub_with_overflow:
6703 case Intrinsic::ssub_with_overflow:
6704 // undef - X -> undef
6705 // X - undef -> undef
6706 if (isa<UndefValue>(II->getOperand(1)) ||
6707 isa<UndefValue>(II->getOperand(2)))
6708 return ReplaceInstUsesWith(CI, UndefValue::get(II->getType()));
6709
6710 if (ConstantInt *RHS = dyn_cast<ConstantInt>(II->getOperand(2))) {
6711 // X - 0 -> {X, false}
6712 if (RHS->isZero()) {
6713 Constant *V[] = {
Chris Lattnercd188e92009-11-29 02:57:29 +00006714 UndefValue::get(II->getOperand(1)->getType()),
Chris Lattner4de84762010-01-04 07:02:48 +00006715 ConstantInt::getFalse(II->getContext())
Chris Lattner2bbac752009-11-26 21:42:47 +00006716 };
Chris Lattner4de84762010-01-04 07:02:48 +00006717 Constant *Struct = ConstantStruct::get(II->getContext(), V, 2, false);
Chris Lattner2bbac752009-11-26 21:42:47 +00006718 return InsertValueInst::Create(Struct, II->getOperand(1), 0);
6719 }
6720 }
6721 break;
6722 case Intrinsic::umul_with_overflow:
6723 case Intrinsic::smul_with_overflow:
6724 // Canonicalize constants into the RHS.
6725 if (isa<Constant>(II->getOperand(1)) &&
6726 !isa<Constant>(II->getOperand(2))) {
6727 Value *LHS = II->getOperand(1);
6728 II->setOperand(1, II->getOperand(2));
6729 II->setOperand(2, LHS);
6730 return II;
6731 }
6732
6733 // X * undef -> undef
6734 if (isa<UndefValue>(II->getOperand(2)))
6735 return ReplaceInstUsesWith(CI, UndefValue::get(II->getType()));
6736
6737 if (ConstantInt *RHSI = dyn_cast<ConstantInt>(II->getOperand(2))) {
6738 // X*0 -> {0, false}
6739 if (RHSI->isZero())
6740 return ReplaceInstUsesWith(CI, Constant::getNullValue(II->getType()));
6741
6742 // X * 1 -> {X, false}
6743 if (RHSI->equalsInt(1)) {
Chris Lattnercd188e92009-11-29 02:57:29 +00006744 Constant *V[] = {
6745 UndefValue::get(II->getOperand(1)->getType()),
Chris Lattner4de84762010-01-04 07:02:48 +00006746 ConstantInt::getFalse(II->getContext())
Chris Lattnercd188e92009-11-29 02:57:29 +00006747 };
Chris Lattner4de84762010-01-04 07:02:48 +00006748 Constant *Struct = ConstantStruct::get(II->getContext(), V, 2, false);
Chris Lattnercd188e92009-11-29 02:57:29 +00006749 return InsertValueInst::Create(Struct, II->getOperand(1), 0);
Chris Lattner2bbac752009-11-26 21:42:47 +00006750 }
6751 }
6752 break;
Chris Lattner0521e3c2008-06-18 04:33:20 +00006753 case Intrinsic::ppc_altivec_lvx:
6754 case Intrinsic::ppc_altivec_lvxl:
6755 case Intrinsic::x86_sse_loadu_ps:
6756 case Intrinsic::x86_sse2_loadu_pd:
6757 case Intrinsic::x86_sse2_loadu_dq:
6758 // Turn PPC lvx -> load if the pointer is known aligned.
6759 // Turn X86 loadups -> load if the pointer is known aligned.
6760 if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
Chris Lattner08142f22009-08-30 19:47:22 +00006761 Value *Ptr = Builder->CreateBitCast(II->getOperand(1),
6762 PointerType::getUnqual(II->getType()));
Chris Lattner0521e3c2008-06-18 04:33:20 +00006763 return new LoadInst(Ptr);
Chris Lattner867b99f2006-10-05 06:55:50 +00006764 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00006765 break;
6766 case Intrinsic::ppc_altivec_stvx:
6767 case Intrinsic::ppc_altivec_stvxl:
6768 // Turn stvx -> store if the pointer is known aligned.
6769 if (GetOrEnforceKnownAlignment(II->getOperand(2), 16) >= 16) {
6770 const Type *OpPtrTy =
Owen Andersondebcb012009-07-29 22:17:13 +00006771 PointerType::getUnqual(II->getOperand(1)->getType());
Chris Lattner08142f22009-08-30 19:47:22 +00006772 Value *Ptr = Builder->CreateBitCast(II->getOperand(2), OpPtrTy);
Chris Lattner0521e3c2008-06-18 04:33:20 +00006773 return new StoreInst(II->getOperand(1), Ptr);
6774 }
6775 break;
6776 case Intrinsic::x86_sse_storeu_ps:
6777 case Intrinsic::x86_sse2_storeu_pd:
6778 case Intrinsic::x86_sse2_storeu_dq:
Chris Lattner0521e3c2008-06-18 04:33:20 +00006779 // Turn X86 storeu -> store if the pointer is known aligned.
6780 if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
6781 const Type *OpPtrTy =
Owen Andersondebcb012009-07-29 22:17:13 +00006782 PointerType::getUnqual(II->getOperand(2)->getType());
Chris Lattner08142f22009-08-30 19:47:22 +00006783 Value *Ptr = Builder->CreateBitCast(II->getOperand(1), OpPtrTy);
Chris Lattner0521e3c2008-06-18 04:33:20 +00006784 return new StoreInst(II->getOperand(2), Ptr);
6785 }
6786 break;
6787
6788 case Intrinsic::x86_sse_cvttss2si: {
6789 // These intrinsics only demands the 0th element of its input vector. If
6790 // we can simplify the input based on that, do so now.
Evan Cheng388df622009-02-03 10:05:09 +00006791 unsigned VWidth =
6792 cast<VectorType>(II->getOperand(1)->getType())->getNumElements();
6793 APInt DemandedElts(VWidth, 1);
6794 APInt UndefElts(VWidth, 0);
6795 if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
Chris Lattner0521e3c2008-06-18 04:33:20 +00006796 UndefElts)) {
6797 II->setOperand(1, V);
6798 return II;
6799 }
6800 break;
6801 }
6802
6803 case Intrinsic::ppc_altivec_vperm:
6804 // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
6805 if (ConstantVector *Mask = dyn_cast<ConstantVector>(II->getOperand(3))) {
6806 assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
Chris Lattner867b99f2006-10-05 06:55:50 +00006807
Chris Lattner0521e3c2008-06-18 04:33:20 +00006808 // Check that all of the elements are integer constants or undefs.
6809 bool AllEltsOk = true;
6810 for (unsigned i = 0; i != 16; ++i) {
6811 if (!isa<ConstantInt>(Mask->getOperand(i)) &&
6812 !isa<UndefValue>(Mask->getOperand(i))) {
6813 AllEltsOk = false;
6814 break;
6815 }
6816 }
6817
6818 if (AllEltsOk) {
6819 // Cast the input vectors to byte vectors.
Chris Lattner08142f22009-08-30 19:47:22 +00006820 Value *Op0 = Builder->CreateBitCast(II->getOperand(1), Mask->getType());
6821 Value *Op1 = Builder->CreateBitCast(II->getOperand(2), Mask->getType());
Owen Anderson9e9a0d52009-07-30 23:03:37 +00006822 Value *Result = UndefValue::get(Op0->getType());
Chris Lattnere2ed0572006-04-06 19:19:17 +00006823
Chris Lattner0521e3c2008-06-18 04:33:20 +00006824 // Only extract each element once.
6825 Value *ExtractedElts[32];
6826 memset(ExtractedElts, 0, sizeof(ExtractedElts));
6827
Chris Lattnere2ed0572006-04-06 19:19:17 +00006828 for (unsigned i = 0; i != 16; ++i) {
Chris Lattner0521e3c2008-06-18 04:33:20 +00006829 if (isa<UndefValue>(Mask->getOperand(i)))
6830 continue;
6831 unsigned Idx=cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
6832 Idx &= 31; // Match the hardware behavior.
6833
6834 if (ExtractedElts[Idx] == 0) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +00006835 ExtractedElts[Idx] =
6836 Builder->CreateExtractElement(Idx < 16 ? Op0 : Op1,
Chris Lattner4de84762010-01-04 07:02:48 +00006837 ConstantInt::get(Type::getInt32Ty(II->getContext()),
6838 Idx&15, false), "tmp");
Chris Lattnere2ed0572006-04-06 19:19:17 +00006839 }
Chris Lattnere2ed0572006-04-06 19:19:17 +00006840
Chris Lattner0521e3c2008-06-18 04:33:20 +00006841 // Insert this value into the result vector.
Chris Lattnerf925cbd2009-08-30 18:50:58 +00006842 Result = Builder->CreateInsertElement(Result, ExtractedElts[Idx],
Chris Lattner4de84762010-01-04 07:02:48 +00006843 ConstantInt::get(Type::getInt32Ty(II->getContext()),
6844 i, false), "tmp");
Chris Lattnere2ed0572006-04-06 19:19:17 +00006845 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00006846 return CastInst::Create(Instruction::BitCast, Result, CI.getType());
Chris Lattnere2ed0572006-04-06 19:19:17 +00006847 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00006848 }
6849 break;
Chris Lattnere2ed0572006-04-06 19:19:17 +00006850
Chris Lattner0521e3c2008-06-18 04:33:20 +00006851 case Intrinsic::stackrestore: {
6852 // If the save is right next to the restore, remove the restore. This can
6853 // happen when variable allocas are DCE'd.
6854 if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
6855 if (SS->getIntrinsicID() == Intrinsic::stacksave) {
6856 BasicBlock::iterator BI = SS;
6857 if (&*++BI == II)
6858 return EraseInstFromFunction(CI);
Chris Lattnera728ddc2006-01-13 21:28:09 +00006859 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00006860 }
6861
6862 // Scan down this block to see if there is another stack restore in the
6863 // same block without an intervening call/alloca.
6864 BasicBlock::iterator BI = II;
6865 TerminatorInst *TI = II->getParent()->getTerminator();
6866 bool CannotRemove = false;
6867 for (++BI; &*BI != TI; ++BI) {
Victor Hernandez83d63912009-09-18 22:35:49 +00006868 if (isa<AllocaInst>(BI) || isMalloc(BI)) {
Chris Lattner0521e3c2008-06-18 04:33:20 +00006869 CannotRemove = true;
6870 break;
6871 }
Chris Lattneraa0bf522008-06-25 05:59:28 +00006872 if (CallInst *BCI = dyn_cast<CallInst>(BI)) {
6873 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(BCI)) {
6874 // If there is a stackrestore below this one, remove this one.
6875 if (II->getIntrinsicID() == Intrinsic::stackrestore)
6876 return EraseInstFromFunction(CI);
6877 // Otherwise, ignore the intrinsic.
6878 } else {
6879 // If we found a non-intrinsic call, we can't remove the stack
6880 // restore.
Chris Lattnerbf1d8a72008-02-18 06:12:38 +00006881 CannotRemove = true;
6882 break;
6883 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00006884 }
Chris Lattnera728ddc2006-01-13 21:28:09 +00006885 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00006886
6887 // If the stack restore is in a return/unwind block and if there are no
6888 // allocas or calls between the restore and the return, nuke the restore.
6889 if (!CannotRemove && (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)))
6890 return EraseInstFromFunction(CI);
6891 break;
6892 }
Chris Lattner35b9e482004-10-12 04:52:52 +00006893 }
6894
Chris Lattner8b0ea312006-01-13 20:11:04 +00006895 return visitCallSite(II);
Chris Lattner9fe38862003-06-19 17:00:31 +00006896}
6897
6898// InvokeInst simplification
6899//
6900Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
Chris Lattnera44d8a22003-10-07 22:32:43 +00006901 return visitCallSite(&II);
Chris Lattner9fe38862003-06-19 17:00:31 +00006902}
6903
Dale Johannesenda30ccb2008-04-25 21:16:07 +00006904/// isSafeToEliminateVarargsCast - If this cast does not affect the value
6905/// passed through the varargs area, we can eliminate the use of the cast.
Dale Johannesen1f530a52008-04-23 18:34:37 +00006906static bool isSafeToEliminateVarargsCast(const CallSite CS,
6907 const CastInst * const CI,
6908 const TargetData * const TD,
6909 const int ix) {
6910 if (!CI->isLosslessCast())
6911 return false;
6912
6913 // The size of ByVal arguments is derived from the type, so we
6914 // can't change to a type with a different size. If the size were
6915 // passed explicitly we could avoid this check.
Devang Patel05988662008-09-25 21:00:45 +00006916 if (!CS.paramHasAttr(ix, Attribute::ByVal))
Dale Johannesen1f530a52008-04-23 18:34:37 +00006917 return true;
6918
6919 const Type* SrcTy =
6920 cast<PointerType>(CI->getOperand(0)->getType())->getElementType();
6921 const Type* DstTy = cast<PointerType>(CI->getType())->getElementType();
6922 if (!SrcTy->isSized() || !DstTy->isSized())
6923 return false;
Dan Gohmance9fe9f2009-07-21 23:21:54 +00006924 if (!TD || TD->getTypeAllocSize(SrcTy) != TD->getTypeAllocSize(DstTy))
Dale Johannesen1f530a52008-04-23 18:34:37 +00006925 return false;
6926 return true;
6927}
6928
Chris Lattnera44d8a22003-10-07 22:32:43 +00006929// visitCallSite - Improvements for call and invoke instructions.
6930//
6931Instruction *InstCombiner::visitCallSite(CallSite CS) {
Chris Lattner6c266db2003-10-07 22:54:13 +00006932 bool Changed = false;
6933
6934 // If the callee is a constexpr cast of a function, attempt to move the cast
6935 // to the arguments of the call/invoke.
Chris Lattnera44d8a22003-10-07 22:32:43 +00006936 if (transformConstExprCastCall(CS)) return 0;
6937
Chris Lattner6c266db2003-10-07 22:54:13 +00006938 Value *Callee = CS.getCalledValue();
Chris Lattnere87597f2004-10-16 18:11:37 +00006939
Chris Lattner08b22ec2005-05-13 07:09:09 +00006940 if (Function *CalleeF = dyn_cast<Function>(Callee))
6941 if (CalleeF->getCallingConv() != CS.getCallingConv()) {
6942 Instruction *OldCall = CS.getInstruction();
6943 // If the call and callee calling conventions don't match, this call must
6944 // be unreachable, as the call is undefined.
Chris Lattner4de84762010-01-04 07:02:48 +00006945 new StoreInst(ConstantInt::getTrue(Callee->getContext()),
6946 UndefValue::get(Type::getInt1PtrTy(Callee->getContext())),
Owen Andersond672ecb2009-07-03 00:17:18 +00006947 OldCall);
Devang Patel228ebd02009-10-13 22:56:32 +00006948 // If OldCall dues not return void then replaceAllUsesWith undef.
6949 // This allows ValueHandlers and custom metadata to adjust itself.
Devang Patel9674d152009-10-14 17:29:00 +00006950 if (!OldCall->getType()->isVoidTy())
Devang Patel228ebd02009-10-13 22:56:32 +00006951 OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
Chris Lattner08b22ec2005-05-13 07:09:09 +00006952 if (isa<CallInst>(OldCall)) // Not worth removing an invoke here.
6953 return EraseInstFromFunction(*OldCall);
6954 return 0;
6955 }
6956
Chris Lattner17be6352004-10-18 02:59:09 +00006957 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
6958 // This instruction is not reachable, just remove it. We insert a store to
6959 // undef so that we know that this code is not reachable, despite the fact
6960 // that we can't modify the CFG here.
Chris Lattner4de84762010-01-04 07:02:48 +00006961 new StoreInst(ConstantInt::getTrue(Callee->getContext()),
6962 UndefValue::get(Type::getInt1PtrTy(Callee->getContext())),
Chris Lattner17be6352004-10-18 02:59:09 +00006963 CS.getInstruction());
6964
Devang Patel228ebd02009-10-13 22:56:32 +00006965 // If CS dues not return void then replaceAllUsesWith undef.
6966 // This allows ValueHandlers and custom metadata to adjust itself.
Devang Patel9674d152009-10-14 17:29:00 +00006967 if (!CS.getInstruction()->getType()->isVoidTy())
Devang Patel228ebd02009-10-13 22:56:32 +00006968 CS.getInstruction()->
6969 replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
Chris Lattner17be6352004-10-18 02:59:09 +00006970
6971 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
6972 // Don't break the CFG, insert a dummy cond branch.
Gabor Greif051a9502008-04-06 20:25:17 +00006973 BranchInst::Create(II->getNormalDest(), II->getUnwindDest(),
Chris Lattner4de84762010-01-04 07:02:48 +00006974 ConstantInt::getTrue(Callee->getContext()), II);
Chris Lattnere87597f2004-10-16 18:11:37 +00006975 }
Chris Lattner17be6352004-10-18 02:59:09 +00006976 return EraseInstFromFunction(*CS.getInstruction());
6977 }
Chris Lattnere87597f2004-10-16 18:11:37 +00006978
Duncan Sandscdb6d922007-09-17 10:26:40 +00006979 if (BitCastInst *BC = dyn_cast<BitCastInst>(Callee))
6980 if (IntrinsicInst *In = dyn_cast<IntrinsicInst>(BC->getOperand(0)))
6981 if (In->getIntrinsicID() == Intrinsic::init_trampoline)
6982 return transformCallThroughTrampoline(CS);
6983
Chris Lattner6c266db2003-10-07 22:54:13 +00006984 const PointerType *PTy = cast<PointerType>(Callee->getType());
6985 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
6986 if (FTy->isVarArg()) {
Dale Johannesen63e7eb42008-04-23 01:03:05 +00006987 int ix = FTy->getNumParams() + (isa<InvokeInst>(Callee) ? 3 : 1);
Chris Lattner6c266db2003-10-07 22:54:13 +00006988 // See if we can optimize any arguments passed through the varargs area of
6989 // the call.
6990 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
Dale Johannesen1f530a52008-04-23 18:34:37 +00006991 E = CS.arg_end(); I != E; ++I, ++ix) {
6992 CastInst *CI = dyn_cast<CastInst>(*I);
6993 if (CI && isSafeToEliminateVarargsCast(CS, CI, TD, ix)) {
6994 *I = CI->getOperand(0);
6995 Changed = true;
Chris Lattner6c266db2003-10-07 22:54:13 +00006996 }
Dale Johannesen1f530a52008-04-23 18:34:37 +00006997 }
Chris Lattner6c266db2003-10-07 22:54:13 +00006998 }
Misha Brukmanfd939082005-04-21 23:48:37 +00006999
Duncan Sandsf0c33542007-12-19 21:13:37 +00007000 if (isa<InlineAsm>(Callee) && !CS.doesNotThrow()) {
Duncan Sandsece2c042007-12-16 15:51:49 +00007001 // Inline asm calls cannot throw - mark them 'nounwind'.
Duncan Sandsf0c33542007-12-19 21:13:37 +00007002 CS.setDoesNotThrow();
Duncan Sandsece2c042007-12-16 15:51:49 +00007003 Changed = true;
7004 }
7005
Chris Lattner6c266db2003-10-07 22:54:13 +00007006 return Changed ? CS.getInstruction() : 0;
Chris Lattnera44d8a22003-10-07 22:32:43 +00007007}
7008
Chris Lattner9fe38862003-06-19 17:00:31 +00007009// transformConstExprCastCall - If the callee is a constexpr cast of a function,
7010// attempt to move the cast to the arguments of the call/invoke.
7011//
7012bool InstCombiner::transformConstExprCastCall(CallSite CS) {
7013 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
7014 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
Reid Spencer3da59db2006-11-27 01:05:10 +00007015 if (CE->getOpcode() != Instruction::BitCast ||
7016 !isa<Function>(CE->getOperand(0)))
Chris Lattner9fe38862003-06-19 17:00:31 +00007017 return false;
Reid Spencer8863f182004-07-18 00:38:32 +00007018 Function *Callee = cast<Function>(CE->getOperand(0));
Chris Lattner9fe38862003-06-19 17:00:31 +00007019 Instruction *Caller = CS.getInstruction();
Devang Patel05988662008-09-25 21:00:45 +00007020 const AttrListPtr &CallerPAL = CS.getAttributes();
Chris Lattner9fe38862003-06-19 17:00:31 +00007021
7022 // Okay, this is a cast from a function to a different type. Unless doing so
7023 // would cause a type conversion of one of our arguments, change this call to
7024 // be a direct call with arguments casted to the appropriate types.
7025 //
7026 const FunctionType *FT = Callee->getFunctionType();
7027 const Type *OldRetTy = Caller->getType();
Duncan Sandsf413cdf2008-06-01 07:38:42 +00007028 const Type *NewRetTy = FT->getReturnType();
Chris Lattner9fe38862003-06-19 17:00:31 +00007029
Duncan Sandsf413cdf2008-06-01 07:38:42 +00007030 if (isa<StructType>(NewRetTy))
Devang Patel75e6f022008-03-11 18:04:06 +00007031 return false; // TODO: Handle multiple return values.
7032
Chris Lattnerf78616b2004-01-14 06:06:08 +00007033 // Check to see if we are changing the return type...
Duncan Sandsf413cdf2008-06-01 07:38:42 +00007034 if (OldRetTy != NewRetTy) {
Bill Wendlinga6c31122008-05-14 22:45:20 +00007035 if (Callee->isDeclaration() &&
Duncan Sandsf413cdf2008-06-01 07:38:42 +00007036 // Conversion is ok if changing from one pointer type to another or from
7037 // a pointer to an integer of the same size.
Dan Gohmance9fe9f2009-07-21 23:21:54 +00007038 !((isa<PointerType>(OldRetTy) || !TD ||
Owen Anderson1d0be152009-08-13 21:58:54 +00007039 OldRetTy == TD->getIntPtrType(Caller->getContext())) &&
Dan Gohmance9fe9f2009-07-21 23:21:54 +00007040 (isa<PointerType>(NewRetTy) || !TD ||
Owen Anderson1d0be152009-08-13 21:58:54 +00007041 NewRetTy == TD->getIntPtrType(Caller->getContext()))))
Chris Lattnerec479922007-01-06 02:09:32 +00007042 return false; // Cannot transform this return value.
Chris Lattnerf78616b2004-01-14 06:06:08 +00007043
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00007044 if (!Caller->use_empty() &&
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00007045 // void -> non-void is handled specially
Devang Patel9674d152009-10-14 17:29:00 +00007046 !NewRetTy->isVoidTy() && !CastInst::isCastable(NewRetTy, OldRetTy))
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00007047 return false; // Cannot transform this return value.
7048
Chris Lattner58d74912008-03-12 17:45:29 +00007049 if (!CallerPAL.isEmpty() && !Caller->use_empty()) {
Devang Patel19c87462008-09-26 22:53:05 +00007050 Attributes RAttrs = CallerPAL.getRetAttributes();
Devang Patel05988662008-09-25 21:00:45 +00007051 if (RAttrs & Attribute::typeIncompatible(NewRetTy))
Duncan Sands6c3470e2008-01-07 17:16:06 +00007052 return false; // Attribute not compatible with transformed value.
7053 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +00007054
Chris Lattnerf78616b2004-01-14 06:06:08 +00007055 // If the callsite is an invoke instruction, and the return value is used by
7056 // a PHI node in a successor, we cannot change the return type of the call
7057 // because there is no place to put the cast instruction (without breaking
7058 // the critical edge). Bail out in this case.
7059 if (!Caller->use_empty())
7060 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
7061 for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
7062 UI != E; ++UI)
7063 if (PHINode *PN = dyn_cast<PHINode>(*UI))
7064 if (PN->getParent() == II->getNormalDest() ||
Chris Lattneraeb2a1d2004-02-08 21:44:31 +00007065 PN->getParent() == II->getUnwindDest())
Chris Lattnerf78616b2004-01-14 06:06:08 +00007066 return false;
7067 }
Chris Lattner9fe38862003-06-19 17:00:31 +00007068
7069 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
7070 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
Misha Brukmanfd939082005-04-21 23:48:37 +00007071
Chris Lattner9fe38862003-06-19 17:00:31 +00007072 CallSite::arg_iterator AI = CS.arg_begin();
7073 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
7074 const Type *ParamTy = FT->getParamType(i);
Andrew Lenharthb8e604c2006-06-28 01:01:52 +00007075 const Type *ActTy = (*AI)->getType();
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00007076
7077 if (!CastInst::isCastable(ActTy, ParamTy))
Duncan Sandsad9a9e12008-01-06 18:27:01 +00007078 return false; // Cannot transform this parameter value.
7079
Devang Patel19c87462008-09-26 22:53:05 +00007080 if (CallerPAL.getParamAttributes(i + 1)
7081 & Attribute::typeIncompatible(ParamTy))
Chris Lattner58d74912008-03-12 17:45:29 +00007082 return false; // Attribute not compatible with transformed value.
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00007083
Duncan Sandsf413cdf2008-06-01 07:38:42 +00007084 // Converting from one pointer type to another or between a pointer and an
7085 // integer of the same size is safe even if we do not have a body.
Chris Lattnerec479922007-01-06 02:09:32 +00007086 bool isConvertible = ActTy == ParamTy ||
Owen Anderson1d0be152009-08-13 21:58:54 +00007087 (TD && ((isa<PointerType>(ParamTy) ||
7088 ParamTy == TD->getIntPtrType(Caller->getContext())) &&
7089 (isa<PointerType>(ActTy) ||
7090 ActTy == TD->getIntPtrType(Caller->getContext()))));
Reid Spencer5cbf9852007-01-30 20:08:39 +00007091 if (Callee->isDeclaration() && !isConvertible) return false;
Chris Lattner9fe38862003-06-19 17:00:31 +00007092 }
7093
7094 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
Reid Spencer5cbf9852007-01-30 20:08:39 +00007095 Callee->isDeclaration())
Chris Lattner58d74912008-03-12 17:45:29 +00007096 return false; // Do not delete arguments unless we have a function body.
Chris Lattner9fe38862003-06-19 17:00:31 +00007097
Chris Lattner58d74912008-03-12 17:45:29 +00007098 if (FT->getNumParams() < NumActualArgs && FT->isVarArg() &&
7099 !CallerPAL.isEmpty())
Duncan Sandsad9a9e12008-01-06 18:27:01 +00007100 // In this case we have more arguments than the new function type, but we
Duncan Sandse1e520f2008-01-13 08:02:44 +00007101 // won't be dropping them. Check that these extra arguments have attributes
7102 // that are compatible with being a vararg call argument.
Chris Lattner58d74912008-03-12 17:45:29 +00007103 for (unsigned i = CallerPAL.getNumSlots(); i; --i) {
7104 if (CallerPAL.getSlot(i - 1).Index <= FT->getNumParams())
Duncan Sandse1e520f2008-01-13 08:02:44 +00007105 break;
Devang Pateleaf42ab2008-09-23 23:03:40 +00007106 Attributes PAttrs = CallerPAL.getSlot(i - 1).Attrs;
Devang Patel05988662008-09-25 21:00:45 +00007107 if (PAttrs & Attribute::VarArgsIncompatible)
Duncan Sandse1e520f2008-01-13 08:02:44 +00007108 return false;
7109 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +00007110
Chris Lattner9fe38862003-06-19 17:00:31 +00007111 // Okay, we decided that this is a safe thing to do: go ahead and start
7112 // inserting cast instructions as necessary...
7113 std::vector<Value*> Args;
7114 Args.reserve(NumActualArgs);
Devang Patel05988662008-09-25 21:00:45 +00007115 SmallVector<AttributeWithIndex, 8> attrVec;
Duncan Sandsad9a9e12008-01-06 18:27:01 +00007116 attrVec.reserve(NumCommonArgs);
7117
7118 // Get any return attributes.
Devang Patel19c87462008-09-26 22:53:05 +00007119 Attributes RAttrs = CallerPAL.getRetAttributes();
Duncan Sandsad9a9e12008-01-06 18:27:01 +00007120
7121 // If the return value is not being used, the type may not be compatible
7122 // with the existing attributes. Wipe out any problematic attributes.
Devang Patel05988662008-09-25 21:00:45 +00007123 RAttrs &= ~Attribute::typeIncompatible(NewRetTy);
Duncan Sandsad9a9e12008-01-06 18:27:01 +00007124
7125 // Add the new return attributes.
7126 if (RAttrs)
Devang Patel05988662008-09-25 21:00:45 +00007127 attrVec.push_back(AttributeWithIndex::get(0, RAttrs));
Chris Lattner9fe38862003-06-19 17:00:31 +00007128
7129 AI = CS.arg_begin();
7130 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
7131 const Type *ParamTy = FT->getParamType(i);
7132 if ((*AI)->getType() == ParamTy) {
7133 Args.push_back(*AI);
7134 } else {
Reid Spencer8a903db2006-12-18 08:47:13 +00007135 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
Reid Spencerc5b206b2006-12-31 05:48:39 +00007136 false, ParamTy, false);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007137 Args.push_back(Builder->CreateCast(opcode, *AI, ParamTy, "tmp"));
Chris Lattner9fe38862003-06-19 17:00:31 +00007138 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +00007139
7140 // Add any parameter attributes.
Devang Patel19c87462008-09-26 22:53:05 +00007141 if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
Devang Patel05988662008-09-25 21:00:45 +00007142 attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
Chris Lattner9fe38862003-06-19 17:00:31 +00007143 }
7144
7145 // If the function takes more arguments than the call was taking, add them
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007146 // now.
Chris Lattner9fe38862003-06-19 17:00:31 +00007147 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
Owen Andersona7235ea2009-07-31 20:28:14 +00007148 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
Chris Lattner9fe38862003-06-19 17:00:31 +00007149
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007150 // If we are removing arguments to the function, emit an obnoxious warning.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00007151 if (FT->getNumParams() < NumActualArgs) {
Chris Lattner9fe38862003-06-19 17:00:31 +00007152 if (!FT->isVarArg()) {
Daniel Dunbarce63ffb2009-07-25 00:23:56 +00007153 errs() << "WARNING: While resolving call to function '"
7154 << Callee->getName() << "' arguments were dropped!\n";
Chris Lattner9fe38862003-06-19 17:00:31 +00007155 } else {
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007156 // Add all of the arguments in their promoted form to the arg list.
Chris Lattner9fe38862003-06-19 17:00:31 +00007157 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
7158 const Type *PTy = getPromotedType((*AI)->getType());
7159 if (PTy != (*AI)->getType()) {
7160 // Must promote to pass through va_arg area!
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007161 Instruction::CastOps opcode =
7162 CastInst::getCastOpcode(*AI, false, PTy, false);
7163 Args.push_back(Builder->CreateCast(opcode, *AI, PTy, "tmp"));
Chris Lattner9fe38862003-06-19 17:00:31 +00007164 } else {
7165 Args.push_back(*AI);
7166 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +00007167
Duncan Sandse1e520f2008-01-13 08:02:44 +00007168 // Add any parameter attributes.
Devang Patel19c87462008-09-26 22:53:05 +00007169 if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
Devang Patel05988662008-09-25 21:00:45 +00007170 attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
Duncan Sandse1e520f2008-01-13 08:02:44 +00007171 }
Chris Lattner9fe38862003-06-19 17:00:31 +00007172 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00007173 }
Chris Lattner9fe38862003-06-19 17:00:31 +00007174
Devang Patel19c87462008-09-26 22:53:05 +00007175 if (Attributes FnAttrs = CallerPAL.getFnAttributes())
7176 attrVec.push_back(AttributeWithIndex::get(~0, FnAttrs));
7177
Devang Patel9674d152009-10-14 17:29:00 +00007178 if (NewRetTy->isVoidTy())
Chris Lattner6934a042007-02-11 01:23:03 +00007179 Caller->setName(""); // Void type should not have a name.
Chris Lattner9fe38862003-06-19 17:00:31 +00007180
Eric Christophera66297a2009-07-25 02:45:27 +00007181 const AttrListPtr &NewCallerPAL = AttrListPtr::get(attrVec.begin(),
7182 attrVec.end());
Duncan Sandsad9a9e12008-01-06 18:27:01 +00007183
Chris Lattner9fe38862003-06-19 17:00:31 +00007184 Instruction *NC;
7185 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Gabor Greif051a9502008-04-06 20:25:17 +00007186 NC = InvokeInst::Create(Callee, II->getNormalDest(), II->getUnwindDest(),
Gabor Greifb1dbcd82008-05-15 10:04:30 +00007187 Args.begin(), Args.end(),
7188 Caller->getName(), Caller);
Reid Spencered3fa852007-07-30 19:53:57 +00007189 cast<InvokeInst>(NC)->setCallingConv(II->getCallingConv());
Devang Patel05988662008-09-25 21:00:45 +00007190 cast<InvokeInst>(NC)->setAttributes(NewCallerPAL);
Chris Lattner9fe38862003-06-19 17:00:31 +00007191 } else {
Gabor Greif051a9502008-04-06 20:25:17 +00007192 NC = CallInst::Create(Callee, Args.begin(), Args.end(),
7193 Caller->getName(), Caller);
Duncan Sandsdc024672007-11-27 13:23:08 +00007194 CallInst *CI = cast<CallInst>(Caller);
7195 if (CI->isTailCall())
Chris Lattnera9e92112005-05-06 06:48:21 +00007196 cast<CallInst>(NC)->setTailCall();
Duncan Sandsdc024672007-11-27 13:23:08 +00007197 cast<CallInst>(NC)->setCallingConv(CI->getCallingConv());
Devang Patel05988662008-09-25 21:00:45 +00007198 cast<CallInst>(NC)->setAttributes(NewCallerPAL);
Chris Lattner9fe38862003-06-19 17:00:31 +00007199 }
7200
Chris Lattner6934a042007-02-11 01:23:03 +00007201 // Insert a cast of the return type as necessary.
Chris Lattner9fe38862003-06-19 17:00:31 +00007202 Value *NV = NC;
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00007203 if (OldRetTy != NV->getType() && !Caller->use_empty()) {
Devang Patel9674d152009-10-14 17:29:00 +00007204 if (!NV->getType()->isVoidTy()) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00007205 Instruction::CastOps opcode = CastInst::getCastOpcode(NC, false,
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00007206 OldRetTy, false);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007207 NV = NC = CastInst::Create(opcode, NC, OldRetTy, "tmp");
Chris Lattnerbb609042003-10-30 00:46:41 +00007208
7209 // If this is an invoke instruction, we should insert it after the first
7210 // non-phi, instruction in the normal successor block.
7211 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Dan Gohman02dea8b2008-05-23 21:05:58 +00007212 BasicBlock::iterator I = II->getNormalDest()->getFirstNonPHI();
Chris Lattnerbb609042003-10-30 00:46:41 +00007213 InsertNewInstBefore(NC, *I);
7214 } else {
7215 // Otherwise, it's a call, just insert cast right after the call instr
7216 InsertNewInstBefore(NC, *Caller);
7217 }
Chris Lattnere5ecdb52009-08-30 06:22:51 +00007218 Worklist.AddUsersToWorkList(*Caller);
Chris Lattner9fe38862003-06-19 17:00:31 +00007219 } else {
Owen Anderson9e9a0d52009-07-30 23:03:37 +00007220 NV = UndefValue::get(Caller->getType());
Chris Lattner9fe38862003-06-19 17:00:31 +00007221 }
7222 }
7223
Devang Patel1bf5ebc2009-10-13 21:41:20 +00007224
Chris Lattner931f8f32009-08-31 05:17:58 +00007225 if (!Caller->use_empty())
Chris Lattner9fe38862003-06-19 17:00:31 +00007226 Caller->replaceAllUsesWith(NV);
Chris Lattner931f8f32009-08-31 05:17:58 +00007227
7228 EraseInstFromFunction(*Caller);
Chris Lattner9fe38862003-06-19 17:00:31 +00007229 return true;
7230}
7231
Duncan Sandscdb6d922007-09-17 10:26:40 +00007232// transformCallThroughTrampoline - Turn a call to a function created by the
7233// init_trampoline intrinsic into a direct call to the underlying function.
7234//
7235Instruction *InstCombiner::transformCallThroughTrampoline(CallSite CS) {
7236 Value *Callee = CS.getCalledValue();
7237 const PointerType *PTy = cast<PointerType>(Callee->getType());
7238 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
Devang Patel05988662008-09-25 21:00:45 +00007239 const AttrListPtr &Attrs = CS.getAttributes();
Duncan Sandsb0c9b932008-01-14 19:52:09 +00007240
7241 // If the call already has the 'nest' attribute somewhere then give up -
7242 // otherwise 'nest' would occur twice after splicing in the chain.
Devang Patel05988662008-09-25 21:00:45 +00007243 if (Attrs.hasAttrSomewhere(Attribute::Nest))
Duncan Sandsb0c9b932008-01-14 19:52:09 +00007244 return 0;
Duncan Sandscdb6d922007-09-17 10:26:40 +00007245
7246 IntrinsicInst *Tramp =
7247 cast<IntrinsicInst>(cast<BitCastInst>(Callee)->getOperand(0));
7248
Anton Korobeynikov0b12ecf2008-05-07 22:54:15 +00007249 Function *NestF = cast<Function>(Tramp->getOperand(2)->stripPointerCasts());
Duncan Sandscdb6d922007-09-17 10:26:40 +00007250 const PointerType *NestFPTy = cast<PointerType>(NestF->getType());
7251 const FunctionType *NestFTy = cast<FunctionType>(NestFPTy->getElementType());
7252
Devang Patel05988662008-09-25 21:00:45 +00007253 const AttrListPtr &NestAttrs = NestF->getAttributes();
Chris Lattner58d74912008-03-12 17:45:29 +00007254 if (!NestAttrs.isEmpty()) {
Duncan Sandscdb6d922007-09-17 10:26:40 +00007255 unsigned NestIdx = 1;
7256 const Type *NestTy = 0;
Devang Patel05988662008-09-25 21:00:45 +00007257 Attributes NestAttr = Attribute::None;
Duncan Sandscdb6d922007-09-17 10:26:40 +00007258
7259 // Look for a parameter marked with the 'nest' attribute.
7260 for (FunctionType::param_iterator I = NestFTy->param_begin(),
7261 E = NestFTy->param_end(); I != E; ++NestIdx, ++I)
Devang Patel05988662008-09-25 21:00:45 +00007262 if (NestAttrs.paramHasAttr(NestIdx, Attribute::Nest)) {
Duncan Sandscdb6d922007-09-17 10:26:40 +00007263 // Record the parameter type and any other attributes.
7264 NestTy = *I;
Devang Patel19c87462008-09-26 22:53:05 +00007265 NestAttr = NestAttrs.getParamAttributes(NestIdx);
Duncan Sandscdb6d922007-09-17 10:26:40 +00007266 break;
7267 }
7268
7269 if (NestTy) {
7270 Instruction *Caller = CS.getInstruction();
7271 std::vector<Value*> NewArgs;
7272 NewArgs.reserve(unsigned(CS.arg_end()-CS.arg_begin())+1);
7273
Devang Patel05988662008-09-25 21:00:45 +00007274 SmallVector<AttributeWithIndex, 8> NewAttrs;
Chris Lattner58d74912008-03-12 17:45:29 +00007275 NewAttrs.reserve(Attrs.getNumSlots() + 1);
Duncan Sandsb0c9b932008-01-14 19:52:09 +00007276
Duncan Sandscdb6d922007-09-17 10:26:40 +00007277 // Insert the nest argument into the call argument list, which may
Duncan Sandsb0c9b932008-01-14 19:52:09 +00007278 // mean appending it. Likewise for attributes.
7279
Devang Patel19c87462008-09-26 22:53:05 +00007280 // Add any result attributes.
7281 if (Attributes Attr = Attrs.getRetAttributes())
Devang Patel05988662008-09-25 21:00:45 +00007282 NewAttrs.push_back(AttributeWithIndex::get(0, Attr));
Duncan Sandsb0c9b932008-01-14 19:52:09 +00007283
Duncan Sandscdb6d922007-09-17 10:26:40 +00007284 {
7285 unsigned Idx = 1;
7286 CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
7287 do {
7288 if (Idx == NestIdx) {
Duncan Sandsb0c9b932008-01-14 19:52:09 +00007289 // Add the chain argument and attributes.
Duncan Sandscdb6d922007-09-17 10:26:40 +00007290 Value *NestVal = Tramp->getOperand(3);
7291 if (NestVal->getType() != NestTy)
7292 NestVal = new BitCastInst(NestVal, NestTy, "nest", Caller);
7293 NewArgs.push_back(NestVal);
Devang Patel05988662008-09-25 21:00:45 +00007294 NewAttrs.push_back(AttributeWithIndex::get(NestIdx, NestAttr));
Duncan Sandscdb6d922007-09-17 10:26:40 +00007295 }
7296
7297 if (I == E)
7298 break;
7299
Duncan Sandsb0c9b932008-01-14 19:52:09 +00007300 // Add the original argument and attributes.
Duncan Sandscdb6d922007-09-17 10:26:40 +00007301 NewArgs.push_back(*I);
Devang Patel19c87462008-09-26 22:53:05 +00007302 if (Attributes Attr = Attrs.getParamAttributes(Idx))
Duncan Sandsb0c9b932008-01-14 19:52:09 +00007303 NewAttrs.push_back
Devang Patel05988662008-09-25 21:00:45 +00007304 (AttributeWithIndex::get(Idx + (Idx >= NestIdx), Attr));
Duncan Sandscdb6d922007-09-17 10:26:40 +00007305
7306 ++Idx, ++I;
7307 } while (1);
7308 }
7309
Devang Patel19c87462008-09-26 22:53:05 +00007310 // Add any function attributes.
7311 if (Attributes Attr = Attrs.getFnAttributes())
7312 NewAttrs.push_back(AttributeWithIndex::get(~0, Attr));
7313
Duncan Sandscdb6d922007-09-17 10:26:40 +00007314 // The trampoline may have been bitcast to a bogus type (FTy).
7315 // Handle this by synthesizing a new function type, equal to FTy
Duncan Sandsb0c9b932008-01-14 19:52:09 +00007316 // with the chain parameter inserted.
Duncan Sandscdb6d922007-09-17 10:26:40 +00007317
Duncan Sandscdb6d922007-09-17 10:26:40 +00007318 std::vector<const Type*> NewTypes;
Duncan Sandscdb6d922007-09-17 10:26:40 +00007319 NewTypes.reserve(FTy->getNumParams()+1);
7320
Duncan Sandscdb6d922007-09-17 10:26:40 +00007321 // Insert the chain's type into the list of parameter types, which may
Duncan Sandsb0c9b932008-01-14 19:52:09 +00007322 // mean appending it.
Duncan Sandscdb6d922007-09-17 10:26:40 +00007323 {
7324 unsigned Idx = 1;
7325 FunctionType::param_iterator I = FTy->param_begin(),
7326 E = FTy->param_end();
7327
7328 do {
Duncan Sandsb0c9b932008-01-14 19:52:09 +00007329 if (Idx == NestIdx)
7330 // Add the chain's type.
Duncan Sandscdb6d922007-09-17 10:26:40 +00007331 NewTypes.push_back(NestTy);
Duncan Sandscdb6d922007-09-17 10:26:40 +00007332
7333 if (I == E)
7334 break;
7335
Duncan Sandsb0c9b932008-01-14 19:52:09 +00007336 // Add the original type.
Duncan Sandscdb6d922007-09-17 10:26:40 +00007337 NewTypes.push_back(*I);
Duncan Sandscdb6d922007-09-17 10:26:40 +00007338
7339 ++Idx, ++I;
7340 } while (1);
7341 }
7342
7343 // Replace the trampoline call with a direct call. Let the generic
7344 // code sort out any function type mismatches.
Owen Andersondebcb012009-07-29 22:17:13 +00007345 FunctionType *NewFTy = FunctionType::get(FTy->getReturnType(), NewTypes,
Owen Andersond672ecb2009-07-03 00:17:18 +00007346 FTy->isVarArg());
7347 Constant *NewCallee =
Owen Andersondebcb012009-07-29 22:17:13 +00007348 NestF->getType() == PointerType::getUnqual(NewFTy) ?
Owen Andersonbaf3c402009-07-29 18:55:55 +00007349 NestF : ConstantExpr::getBitCast(NestF,
Owen Andersondebcb012009-07-29 22:17:13 +00007350 PointerType::getUnqual(NewFTy));
Eric Christophera66297a2009-07-25 02:45:27 +00007351 const AttrListPtr &NewPAL = AttrListPtr::get(NewAttrs.begin(),
7352 NewAttrs.end());
Duncan Sandscdb6d922007-09-17 10:26:40 +00007353
7354 Instruction *NewCaller;
7355 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Gabor Greif051a9502008-04-06 20:25:17 +00007356 NewCaller = InvokeInst::Create(NewCallee,
7357 II->getNormalDest(), II->getUnwindDest(),
7358 NewArgs.begin(), NewArgs.end(),
7359 Caller->getName(), Caller);
Duncan Sandscdb6d922007-09-17 10:26:40 +00007360 cast<InvokeInst>(NewCaller)->setCallingConv(II->getCallingConv());
Devang Patel05988662008-09-25 21:00:45 +00007361 cast<InvokeInst>(NewCaller)->setAttributes(NewPAL);
Duncan Sandscdb6d922007-09-17 10:26:40 +00007362 } else {
Gabor Greif051a9502008-04-06 20:25:17 +00007363 NewCaller = CallInst::Create(NewCallee, NewArgs.begin(), NewArgs.end(),
7364 Caller->getName(), Caller);
Duncan Sandscdb6d922007-09-17 10:26:40 +00007365 if (cast<CallInst>(Caller)->isTailCall())
7366 cast<CallInst>(NewCaller)->setTailCall();
7367 cast<CallInst>(NewCaller)->
7368 setCallingConv(cast<CallInst>(Caller)->getCallingConv());
Devang Patel05988662008-09-25 21:00:45 +00007369 cast<CallInst>(NewCaller)->setAttributes(NewPAL);
Duncan Sandscdb6d922007-09-17 10:26:40 +00007370 }
Devang Patel9674d152009-10-14 17:29:00 +00007371 if (!Caller->getType()->isVoidTy())
Duncan Sandscdb6d922007-09-17 10:26:40 +00007372 Caller->replaceAllUsesWith(NewCaller);
7373 Caller->eraseFromParent();
Chris Lattner7a1e9242009-08-30 06:13:40 +00007374 Worklist.Remove(Caller);
Duncan Sandscdb6d922007-09-17 10:26:40 +00007375 return 0;
7376 }
7377 }
7378
7379 // Replace the trampoline call with a direct call. Since there is no 'nest'
7380 // parameter, there is no need to adjust the argument list. Let the generic
7381 // code sort out any function type mismatches.
7382 Constant *NewCallee =
Owen Andersond672ecb2009-07-03 00:17:18 +00007383 NestF->getType() == PTy ? NestF :
Owen Andersonbaf3c402009-07-29 18:55:55 +00007384 ConstantExpr::getBitCast(NestF, PTy);
Duncan Sandscdb6d922007-09-17 10:26:40 +00007385 CS.setCalledFunction(NewCallee);
7386 return CS.getInstruction();
7387}
7388
Dan Gohman9ad29202009-09-16 16:50:24 +00007389/// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(a,c)]
7390/// and if a/b/c and the add's all have a single use, turn this into a phi
Chris Lattner7da52b22006-11-01 04:51:18 +00007391/// and a single binop.
7392Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
7393 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
Chris Lattner38b3dcc2008-12-01 03:42:51 +00007394 assert(isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst));
Chris Lattner7da52b22006-11-01 04:51:18 +00007395 unsigned Opc = FirstInst->getOpcode();
Chris Lattnerf6fd94d2006-11-08 19:29:23 +00007396 Value *LHSVal = FirstInst->getOperand(0);
7397 Value *RHSVal = FirstInst->getOperand(1);
7398
7399 const Type *LHSType = LHSVal->getType();
7400 const Type *RHSType = RHSVal->getType();
Chris Lattner7da52b22006-11-01 04:51:18 +00007401
Dan Gohman9ad29202009-09-16 16:50:24 +00007402 // Scan to see if all operands are the same opcode, and all have one use.
Chris Lattner05f18922008-12-01 02:34:36 +00007403 for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
Chris Lattner7da52b22006-11-01 04:51:18 +00007404 Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
Chris Lattnera90a24c2006-11-01 04:55:47 +00007405 if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
Reid Spencere4d87aa2006-12-23 06:05:41 +00007406 // Verify type of the LHS matches so we don't fold cmp's of different
Chris Lattner9c080502006-11-01 07:43:41 +00007407 // types or GEP's with different index types.
7408 I->getOperand(0)->getType() != LHSType ||
7409 I->getOperand(1)->getType() != RHSType)
Chris Lattner7da52b22006-11-01 04:51:18 +00007410 return 0;
Reid Spencere4d87aa2006-12-23 06:05:41 +00007411
7412 // If they are CmpInst instructions, check their predicates
7413 if (Opc == Instruction::ICmp || Opc == Instruction::FCmp)
7414 if (cast<CmpInst>(I)->getPredicate() !=
7415 cast<CmpInst>(FirstInst)->getPredicate())
7416 return 0;
Chris Lattnerf6fd94d2006-11-08 19:29:23 +00007417
7418 // Keep track of which operand needs a phi node.
7419 if (I->getOperand(0) != LHSVal) LHSVal = 0;
7420 if (I->getOperand(1) != RHSVal) RHSVal = 0;
Chris Lattner7da52b22006-11-01 04:51:18 +00007421 }
Dan Gohman9ad29202009-09-16 16:50:24 +00007422
7423 // If both LHS and RHS would need a PHI, don't do this transformation,
7424 // because it would increase the number of PHIs entering the block,
7425 // which leads to higher register pressure. This is especially
7426 // bad when the PHIs are in the header of a loop.
7427 if (!LHSVal && !RHSVal)
7428 return 0;
Chris Lattner7da52b22006-11-01 04:51:18 +00007429
Chris Lattner38b3dcc2008-12-01 03:42:51 +00007430 // Otherwise, this is safe to transform!
Chris Lattner53738a42006-11-08 19:42:28 +00007431
Chris Lattner7da52b22006-11-01 04:51:18 +00007432 Value *InLHS = FirstInst->getOperand(0);
Chris Lattner7da52b22006-11-01 04:51:18 +00007433 Value *InRHS = FirstInst->getOperand(1);
Chris Lattner53738a42006-11-08 19:42:28 +00007434 PHINode *NewLHS = 0, *NewRHS = 0;
Chris Lattnerf6fd94d2006-11-08 19:29:23 +00007435 if (LHSVal == 0) {
Gabor Greifb1dbcd82008-05-15 10:04:30 +00007436 NewLHS = PHINode::Create(LHSType,
7437 FirstInst->getOperand(0)->getName() + ".pn");
Chris Lattnerf6fd94d2006-11-08 19:29:23 +00007438 NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
7439 NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
Chris Lattner9c080502006-11-01 07:43:41 +00007440 InsertNewInstBefore(NewLHS, PN);
7441 LHSVal = NewLHS;
7442 }
Chris Lattnerf6fd94d2006-11-08 19:29:23 +00007443
7444 if (RHSVal == 0) {
Gabor Greifb1dbcd82008-05-15 10:04:30 +00007445 NewRHS = PHINode::Create(RHSType,
7446 FirstInst->getOperand(1)->getName() + ".pn");
Chris Lattnerf6fd94d2006-11-08 19:29:23 +00007447 NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
7448 NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
Chris Lattner9c080502006-11-01 07:43:41 +00007449 InsertNewInstBefore(NewRHS, PN);
7450 RHSVal = NewRHS;
7451 }
7452
Chris Lattnerf6fd94d2006-11-08 19:29:23 +00007453 // Add all operands to the new PHIs.
Chris Lattner05f18922008-12-01 02:34:36 +00007454 if (NewLHS || NewRHS) {
7455 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
7456 Instruction *InInst = cast<Instruction>(PN.getIncomingValue(i));
7457 if (NewLHS) {
7458 Value *NewInLHS = InInst->getOperand(0);
7459 NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
7460 }
7461 if (NewRHS) {
7462 Value *NewInRHS = InInst->getOperand(1);
7463 NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
7464 }
Chris Lattnerf6fd94d2006-11-08 19:29:23 +00007465 }
7466 }
7467
Chris Lattner7da52b22006-11-01 04:51:18 +00007468 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007469 return BinaryOperator::Create(BinOp->getOpcode(), LHSVal, RHSVal);
Chris Lattner38b3dcc2008-12-01 03:42:51 +00007470 CmpInst *CIOp = cast<CmpInst>(FirstInst);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007471 return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(),
Owen Anderson333c4002009-07-09 23:48:35 +00007472 LHSVal, RHSVal);
Chris Lattner7da52b22006-11-01 04:51:18 +00007473}
7474
Chris Lattner05f18922008-12-01 02:34:36 +00007475Instruction *InstCombiner::FoldPHIArgGEPIntoPHI(PHINode &PN) {
7476 GetElementPtrInst *FirstInst =cast<GetElementPtrInst>(PN.getIncomingValue(0));
7477
7478 SmallVector<Value*, 16> FixedOperands(FirstInst->op_begin(),
7479 FirstInst->op_end());
Chris Lattner36d3e322009-02-21 00:46:50 +00007480 // This is true if all GEP bases are allocas and if all indices into them are
7481 // constants.
7482 bool AllBasePointersAreAllocas = true;
Dan Gohmanb6c33852009-09-16 02:01:52 +00007483
7484 // We don't want to replace this phi if the replacement would require
Dan Gohman9ad29202009-09-16 16:50:24 +00007485 // more than one phi, which leads to higher register pressure. This is
7486 // especially bad when the PHIs are in the header of a loop.
Dan Gohmanb6c33852009-09-16 02:01:52 +00007487 bool NeededPhi = false;
Chris Lattner05f18922008-12-01 02:34:36 +00007488
Dan Gohman9ad29202009-09-16 16:50:24 +00007489 // Scan to see if all operands are the same opcode, and all have one use.
Chris Lattner05f18922008-12-01 02:34:36 +00007490 for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
7491 GetElementPtrInst *GEP= dyn_cast<GetElementPtrInst>(PN.getIncomingValue(i));
7492 if (!GEP || !GEP->hasOneUse() || GEP->getType() != FirstInst->getType() ||
7493 GEP->getNumOperands() != FirstInst->getNumOperands())
7494 return 0;
7495
Chris Lattner36d3e322009-02-21 00:46:50 +00007496 // Keep track of whether or not all GEPs are of alloca pointers.
7497 if (AllBasePointersAreAllocas &&
7498 (!isa<AllocaInst>(GEP->getOperand(0)) ||
7499 !GEP->hasAllConstantIndices()))
7500 AllBasePointersAreAllocas = false;
7501
Chris Lattner05f18922008-12-01 02:34:36 +00007502 // Compare the operand lists.
7503 for (unsigned op = 0, e = FirstInst->getNumOperands(); op != e; ++op) {
7504 if (FirstInst->getOperand(op) == GEP->getOperand(op))
7505 continue;
7506
7507 // Don't merge two GEPs when two operands differ (introducing phi nodes)
7508 // if one of the PHIs has a constant for the index. The index may be
7509 // substantially cheaper to compute for the constants, so making it a
7510 // variable index could pessimize the path. This also handles the case
7511 // for struct indices, which must always be constant.
7512 if (isa<ConstantInt>(FirstInst->getOperand(op)) ||
7513 isa<ConstantInt>(GEP->getOperand(op)))
7514 return 0;
7515
7516 if (FirstInst->getOperand(op)->getType() !=GEP->getOperand(op)->getType())
7517 return 0;
Dan Gohmanb6c33852009-09-16 02:01:52 +00007518
7519 // If we already needed a PHI for an earlier operand, and another operand
7520 // also requires a PHI, we'd be introducing more PHIs than we're
7521 // eliminating, which increases register pressure on entry to the PHI's
7522 // block.
7523 if (NeededPhi)
7524 return 0;
7525
Chris Lattner05f18922008-12-01 02:34:36 +00007526 FixedOperands[op] = 0; // Needs a PHI.
Dan Gohmanb6c33852009-09-16 02:01:52 +00007527 NeededPhi = true;
Chris Lattner05f18922008-12-01 02:34:36 +00007528 }
7529 }
7530
Chris Lattner36d3e322009-02-21 00:46:50 +00007531 // If all of the base pointers of the PHI'd GEPs are from allocas, don't
Chris Lattner21550882009-02-23 05:56:17 +00007532 // bother doing this transformation. At best, this will just save a bit of
Chris Lattner36d3e322009-02-21 00:46:50 +00007533 // offset calculation, but all the predecessors will have to materialize the
7534 // stack address into a register anyway. We'd actually rather *clone* the
7535 // load up into the predecessors so that we have a load of a gep of an alloca,
7536 // which can usually all be folded into the load.
7537 if (AllBasePointersAreAllocas)
7538 return 0;
7539
Chris Lattner05f18922008-12-01 02:34:36 +00007540 // Otherwise, this is safe to transform. Insert PHI nodes for each operand
7541 // that is variable.
7542 SmallVector<PHINode*, 16> OperandPhis(FixedOperands.size());
7543
7544 bool HasAnyPHIs = false;
7545 for (unsigned i = 0, e = FixedOperands.size(); i != e; ++i) {
7546 if (FixedOperands[i]) continue; // operand doesn't need a phi.
7547 Value *FirstOp = FirstInst->getOperand(i);
7548 PHINode *NewPN = PHINode::Create(FirstOp->getType(),
7549 FirstOp->getName()+".pn");
7550 InsertNewInstBefore(NewPN, PN);
7551
7552 NewPN->reserveOperandSpace(e);
7553 NewPN->addIncoming(FirstOp, PN.getIncomingBlock(0));
7554 OperandPhis[i] = NewPN;
7555 FixedOperands[i] = NewPN;
7556 HasAnyPHIs = true;
7557 }
7558
7559
7560 // Add all operands to the new PHIs.
7561 if (HasAnyPHIs) {
7562 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
7563 GetElementPtrInst *InGEP =cast<GetElementPtrInst>(PN.getIncomingValue(i));
7564 BasicBlock *InBB = PN.getIncomingBlock(i);
7565
7566 for (unsigned op = 0, e = OperandPhis.size(); op != e; ++op)
7567 if (PHINode *OpPhi = OperandPhis[op])
7568 OpPhi->addIncoming(InGEP->getOperand(op), InBB);
7569 }
7570 }
7571
7572 Value *Base = FixedOperands[0];
Dan Gohmanf8dbee72009-09-07 23:54:19 +00007573 return cast<GEPOperator>(FirstInst)->isInBounds() ?
7574 GetElementPtrInst::CreateInBounds(Base, FixedOperands.begin()+1,
7575 FixedOperands.end()) :
Dan Gohmand6aa02d2009-07-28 01:40:03 +00007576 GetElementPtrInst::Create(Base, FixedOperands.begin()+1,
7577 FixedOperands.end());
Chris Lattner05f18922008-12-01 02:34:36 +00007578}
7579
7580
Chris Lattner21550882009-02-23 05:56:17 +00007581/// isSafeAndProfitableToSinkLoad - Return true if we know that it is safe to
7582/// sink the load out of the block that defines it. This means that it must be
Chris Lattner36d3e322009-02-21 00:46:50 +00007583/// obvious the value of the load is not changed from the point of the load to
7584/// the end of the block it is in.
Chris Lattnerfd905ca2007-02-01 22:30:07 +00007585///
7586/// Finally, it is safe, but not profitable, to sink a load targetting a
7587/// non-address-taken alloca. Doing so will cause us to not promote the alloca
7588/// to a register.
Chris Lattner36d3e322009-02-21 00:46:50 +00007589static bool isSafeAndProfitableToSinkLoad(LoadInst *L) {
Chris Lattner76c73142006-11-01 07:13:54 +00007590 BasicBlock::iterator BBI = L, E = L->getParent()->end();
7591
7592 for (++BBI; BBI != E; ++BBI)
7593 if (BBI->mayWriteToMemory())
7594 return false;
Chris Lattnerfd905ca2007-02-01 22:30:07 +00007595
7596 // Check for non-address taken alloca. If not address-taken already, it isn't
7597 // profitable to do this xform.
7598 if (AllocaInst *AI = dyn_cast<AllocaInst>(L->getOperand(0))) {
7599 bool isAddressTaken = false;
7600 for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
7601 UI != E; ++UI) {
7602 if (isa<LoadInst>(UI)) continue;
7603 if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
7604 // If storing TO the alloca, then the address isn't taken.
7605 if (SI->getOperand(1) == AI) continue;
7606 }
7607 isAddressTaken = true;
7608 break;
7609 }
7610
Chris Lattner36d3e322009-02-21 00:46:50 +00007611 if (!isAddressTaken && AI->isStaticAlloca())
Chris Lattnerfd905ca2007-02-01 22:30:07 +00007612 return false;
7613 }
7614
Chris Lattner36d3e322009-02-21 00:46:50 +00007615 // If this load is a load from a GEP with a constant offset from an alloca,
7616 // then we don't want to sink it. In its present form, it will be
7617 // load [constant stack offset]. Sinking it will cause us to have to
7618 // materialize the stack addresses in each predecessor in a register only to
7619 // do a shared load from register in the successor.
7620 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(L->getOperand(0)))
7621 if (AllocaInst *AI = dyn_cast<AllocaInst>(GEP->getOperand(0)))
7622 if (AI->isStaticAlloca() && GEP->hasAllConstantIndices())
7623 return false;
7624
Chris Lattner76c73142006-11-01 07:13:54 +00007625 return true;
7626}
7627
Chris Lattner751a3622009-11-01 20:04:24 +00007628Instruction *InstCombiner::FoldPHIArgLoadIntoPHI(PHINode &PN) {
7629 LoadInst *FirstLI = cast<LoadInst>(PN.getIncomingValue(0));
7630
7631 // When processing loads, we need to propagate two bits of information to the
7632 // sunk load: whether it is volatile, and what its alignment is. We currently
7633 // don't sink loads when some have their alignment specified and some don't.
7634 // visitLoadInst will propagate an alignment onto the load when TD is around,
7635 // and if TD isn't around, we can't handle the mixed case.
7636 bool isVolatile = FirstLI->isVolatile();
7637 unsigned LoadAlignment = FirstLI->getAlignment();
7638
7639 // We can't sink the load if the loaded value could be modified between the
7640 // load and the PHI.
7641 if (FirstLI->getParent() != PN.getIncomingBlock(0) ||
7642 !isSafeAndProfitableToSinkLoad(FirstLI))
7643 return 0;
7644
7645 // If the PHI is of volatile loads and the load block has multiple
7646 // successors, sinking it would remove a load of the volatile value from
7647 // the path through the other successor.
7648 if (isVolatile &&
7649 FirstLI->getParent()->getTerminator()->getNumSuccessors() != 1)
7650 return 0;
7651
7652 // Check to see if all arguments are the same operation.
7653 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
7654 LoadInst *LI = dyn_cast<LoadInst>(PN.getIncomingValue(i));
7655 if (!LI || !LI->hasOneUse())
7656 return 0;
7657
7658 // We can't sink the load if the loaded value could be modified between
7659 // the load and the PHI.
7660 if (LI->isVolatile() != isVolatile ||
7661 LI->getParent() != PN.getIncomingBlock(i) ||
7662 !isSafeAndProfitableToSinkLoad(LI))
7663 return 0;
7664
7665 // If some of the loads have an alignment specified but not all of them,
7666 // we can't do the transformation.
7667 if ((LoadAlignment != 0) != (LI->getAlignment() != 0))
7668 return 0;
7669
Chris Lattnera664bb72009-11-01 20:07:07 +00007670 LoadAlignment = std::min(LoadAlignment, LI->getAlignment());
Chris Lattner751a3622009-11-01 20:04:24 +00007671
7672 // If the PHI is of volatile loads and the load block has multiple
7673 // successors, sinking it would remove a load of the volatile value from
7674 // the path through the other successor.
7675 if (isVolatile &&
7676 LI->getParent()->getTerminator()->getNumSuccessors() != 1)
7677 return 0;
7678 }
7679
7680 // Okay, they are all the same operation. Create a new PHI node of the
7681 // correct type, and PHI together all of the LHS's of the instructions.
7682 PHINode *NewPN = PHINode::Create(FirstLI->getOperand(0)->getType(),
7683 PN.getName()+".in");
7684 NewPN->reserveOperandSpace(PN.getNumOperands()/2);
7685
7686 Value *InVal = FirstLI->getOperand(0);
7687 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
7688
7689 // Add all operands to the new PHI.
7690 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
7691 Value *NewInVal = cast<LoadInst>(PN.getIncomingValue(i))->getOperand(0);
7692 if (NewInVal != InVal)
7693 InVal = 0;
7694 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
7695 }
7696
7697 Value *PhiVal;
7698 if (InVal) {
7699 // The new PHI unions all of the same values together. This is really
7700 // common, so we handle it intelligently here for compile-time speed.
7701 PhiVal = InVal;
7702 delete NewPN;
7703 } else {
7704 InsertNewInstBefore(NewPN, PN);
7705 PhiVal = NewPN;
7706 }
7707
7708 // If this was a volatile load that we are merging, make sure to loop through
7709 // and mark all the input loads as non-volatile. If we don't do this, we will
7710 // insert a new volatile load and the old ones will not be deletable.
7711 if (isVolatile)
7712 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
7713 cast<LoadInst>(PN.getIncomingValue(i))->setVolatile(false);
7714
7715 return new LoadInst(PhiVal, "", isVolatile, LoadAlignment);
7716}
7717
Chris Lattner9fe38862003-06-19 17:00:31 +00007718
Chris Lattnerc22d4d12009-11-10 07:23:37 +00007719
7720/// FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
7721/// operator and they all are only used by the PHI, PHI together their
7722/// inputs, and do the operation once, to the result of the PHI.
Chris Lattnerbac32862004-11-14 19:13:23 +00007723Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
7724 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
7725
Chris Lattner751a3622009-11-01 20:04:24 +00007726 if (isa<GetElementPtrInst>(FirstInst))
7727 return FoldPHIArgGEPIntoPHI(PN);
7728 if (isa<LoadInst>(FirstInst))
7729 return FoldPHIArgLoadIntoPHI(PN);
7730
Chris Lattnerbac32862004-11-14 19:13:23 +00007731 // Scan the instruction, looking for input operations that can be folded away.
7732 // If all input operands to the phi are the same instruction (e.g. a cast from
7733 // the same type or "+42") we can pull the operation through the PHI, reducing
7734 // code size and simplifying code.
7735 Constant *ConstantOp = 0;
7736 const Type *CastSrcTy = 0;
Chris Lattnere3c62812009-11-01 19:50:13 +00007737
Chris Lattnerbac32862004-11-14 19:13:23 +00007738 if (isa<CastInst>(FirstInst)) {
7739 CastSrcTy = FirstInst->getOperand(0)->getType();
Chris Lattnerbf382b52009-11-08 21:20:06 +00007740
7741 // Be careful about transforming integer PHIs. We don't want to pessimize
7742 // the code by turning an i32 into an i1293.
7743 if (isa<IntegerType>(PN.getType()) && isa<IntegerType>(CastSrcTy)) {
Chris Lattnerc22d4d12009-11-10 07:23:37 +00007744 if (!ShouldChangeType(PN.getType(), CastSrcTy, TD))
Chris Lattnerbf382b52009-11-08 21:20:06 +00007745 return 0;
7746 }
Reid Spencer832254e2007-02-02 02:16:23 +00007747 } else if (isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00007748 // Can fold binop, compare or shift here if the RHS is a constant,
7749 // otherwise call FoldPHIArgBinOpIntoPHI.
Chris Lattnerbac32862004-11-14 19:13:23 +00007750 ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
Chris Lattner7da52b22006-11-01 04:51:18 +00007751 if (ConstantOp == 0)
7752 return FoldPHIArgBinOpIntoPHI(PN);
Chris Lattnerbac32862004-11-14 19:13:23 +00007753 } else {
7754 return 0; // Cannot fold this operation.
7755 }
7756
7757 // Check to see if all arguments are the same operation.
7758 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
Chris Lattner751a3622009-11-01 20:04:24 +00007759 Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
7760 if (I == 0 || !I->hasOneUse() || !I->isSameOperationAs(FirstInst))
Chris Lattnerbac32862004-11-14 19:13:23 +00007761 return 0;
7762 if (CastSrcTy) {
7763 if (I->getOperand(0)->getType() != CastSrcTy)
7764 return 0; // Cast operation must match.
7765 } else if (I->getOperand(1) != ConstantOp) {
7766 return 0;
7767 }
7768 }
7769
7770 // Okay, they are all the same operation. Create a new PHI node of the
7771 // correct type, and PHI together all of the LHS's of the instructions.
Gabor Greif051a9502008-04-06 20:25:17 +00007772 PHINode *NewPN = PHINode::Create(FirstInst->getOperand(0)->getType(),
7773 PN.getName()+".in");
Chris Lattner55517062005-01-29 00:39:08 +00007774 NewPN->reserveOperandSpace(PN.getNumOperands()/2);
Chris Lattnerb5893442004-11-14 19:29:34 +00007775
7776 Value *InVal = FirstInst->getOperand(0);
7777 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
Chris Lattnerbac32862004-11-14 19:13:23 +00007778
7779 // Add all operands to the new PHI.
Chris Lattnerb5893442004-11-14 19:29:34 +00007780 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
7781 Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
7782 if (NewInVal != InVal)
7783 InVal = 0;
7784 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
7785 }
7786
7787 Value *PhiVal;
7788 if (InVal) {
7789 // The new PHI unions all of the same values together. This is really
7790 // common, so we handle it intelligently here for compile-time speed.
7791 PhiVal = InVal;
7792 delete NewPN;
7793 } else {
7794 InsertNewInstBefore(NewPN, PN);
7795 PhiVal = NewPN;
7796 }
Misha Brukmanfd939082005-04-21 23:48:37 +00007797
Chris Lattnerbac32862004-11-14 19:13:23 +00007798 // Insert and return the new operation.
Chris Lattnere3c62812009-11-01 19:50:13 +00007799 if (CastInst *FirstCI = dyn_cast<CastInst>(FirstInst))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007800 return CastInst::Create(FirstCI->getOpcode(), PhiVal, PN.getType());
Chris Lattnere3c62812009-11-01 19:50:13 +00007801
Chris Lattner54545ac2008-04-29 17:13:43 +00007802 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007803 return BinaryOperator::Create(BinOp->getOpcode(), PhiVal, ConstantOp);
Chris Lattnere3c62812009-11-01 19:50:13 +00007804
Chris Lattner751a3622009-11-01 20:04:24 +00007805 CmpInst *CIOp = cast<CmpInst>(FirstInst);
7806 return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(),
7807 PhiVal, ConstantOp);
Chris Lattnerbac32862004-11-14 19:13:23 +00007808}
Chris Lattnera1be5662002-05-02 17:06:02 +00007809
Chris Lattnera3fd1c52005-01-17 05:10:15 +00007810/// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
7811/// that is dead.
Chris Lattner0e5444b2007-03-26 20:40:50 +00007812static bool DeadPHICycle(PHINode *PN,
7813 SmallPtrSet<PHINode*, 16> &PotentiallyDeadPHIs) {
Chris Lattnera3fd1c52005-01-17 05:10:15 +00007814 if (PN->use_empty()) return true;
7815 if (!PN->hasOneUse()) return false;
7816
7817 // Remember this node, and if we find the cycle, return.
Chris Lattner0e5444b2007-03-26 20:40:50 +00007818 if (!PotentiallyDeadPHIs.insert(PN))
Chris Lattnera3fd1c52005-01-17 05:10:15 +00007819 return true;
Chris Lattner92103de2007-08-28 04:23:55 +00007820
7821 // Don't scan crazily complex things.
7822 if (PotentiallyDeadPHIs.size() == 16)
7823 return false;
Chris Lattnera3fd1c52005-01-17 05:10:15 +00007824
7825 if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
7826 return DeadPHICycle(PU, PotentiallyDeadPHIs);
Misha Brukmanfd939082005-04-21 23:48:37 +00007827
Chris Lattnera3fd1c52005-01-17 05:10:15 +00007828 return false;
7829}
7830
Chris Lattnercf5008a2007-11-06 21:52:06 +00007831/// PHIsEqualValue - Return true if this phi node is always equal to
7832/// NonPhiInVal. This happens with mutually cyclic phi nodes like:
7833/// z = some value; x = phi (y, z); y = phi (x, z)
7834static bool PHIsEqualValue(PHINode *PN, Value *NonPhiInVal,
7835 SmallPtrSet<PHINode*, 16> &ValueEqualPHIs) {
7836 // See if we already saw this PHI node.
7837 if (!ValueEqualPHIs.insert(PN))
7838 return true;
7839
7840 // Don't scan crazily complex things.
7841 if (ValueEqualPHIs.size() == 16)
7842 return false;
7843
7844 // Scan the operands to see if they are either phi nodes or are equal to
7845 // the value.
7846 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
7847 Value *Op = PN->getIncomingValue(i);
7848 if (PHINode *OpPN = dyn_cast<PHINode>(Op)) {
7849 if (!PHIsEqualValue(OpPN, NonPhiInVal, ValueEqualPHIs))
7850 return false;
7851 } else if (Op != NonPhiInVal)
7852 return false;
7853 }
7854
7855 return true;
7856}
7857
7858
Chris Lattner9956c052009-11-08 19:23:30 +00007859namespace {
7860struct PHIUsageRecord {
Chris Lattnerdd21a1c2009-11-09 01:38:00 +00007861 unsigned PHIId; // The ID # of the PHI (something determinstic to sort on)
Chris Lattner9956c052009-11-08 19:23:30 +00007862 unsigned Shift; // The amount shifted.
7863 Instruction *Inst; // The trunc instruction.
7864
Chris Lattnerdd21a1c2009-11-09 01:38:00 +00007865 PHIUsageRecord(unsigned pn, unsigned Sh, Instruction *User)
7866 : PHIId(pn), Shift(Sh), Inst(User) {}
Chris Lattner9956c052009-11-08 19:23:30 +00007867
7868 bool operator<(const PHIUsageRecord &RHS) const {
Chris Lattnerdd21a1c2009-11-09 01:38:00 +00007869 if (PHIId < RHS.PHIId) return true;
7870 if (PHIId > RHS.PHIId) return false;
Chris Lattner9956c052009-11-08 19:23:30 +00007871 if (Shift < RHS.Shift) return true;
Chris Lattnerdd21a1c2009-11-09 01:38:00 +00007872 if (Shift > RHS.Shift) return false;
7873 return Inst->getType()->getPrimitiveSizeInBits() <
Chris Lattner9956c052009-11-08 19:23:30 +00007874 RHS.Inst->getType()->getPrimitiveSizeInBits();
7875 }
7876};
Chris Lattnerdd21a1c2009-11-09 01:38:00 +00007877
7878struct LoweredPHIRecord {
7879 PHINode *PN; // The PHI that was lowered.
7880 unsigned Shift; // The amount shifted.
7881 unsigned Width; // The width extracted.
7882
7883 LoweredPHIRecord(PHINode *pn, unsigned Sh, const Type *Ty)
7884 : PN(pn), Shift(Sh), Width(Ty->getPrimitiveSizeInBits()) {}
7885
7886 // Ctor form used by DenseMap.
7887 LoweredPHIRecord(PHINode *pn, unsigned Sh)
7888 : PN(pn), Shift(Sh), Width(0) {}
7889};
7890}
7891
7892namespace llvm {
7893 template<>
7894 struct DenseMapInfo<LoweredPHIRecord> {
7895 static inline LoweredPHIRecord getEmptyKey() {
7896 return LoweredPHIRecord(0, 0);
7897 }
7898 static inline LoweredPHIRecord getTombstoneKey() {
7899 return LoweredPHIRecord(0, 1);
7900 }
7901 static unsigned getHashValue(const LoweredPHIRecord &Val) {
7902 return DenseMapInfo<PHINode*>::getHashValue(Val.PN) ^ (Val.Shift>>3) ^
7903 (Val.Width>>3);
7904 }
7905 static bool isEqual(const LoweredPHIRecord &LHS,
7906 const LoweredPHIRecord &RHS) {
7907 return LHS.PN == RHS.PN && LHS.Shift == RHS.Shift &&
7908 LHS.Width == RHS.Width;
7909 }
Chris Lattnerdd21a1c2009-11-09 01:38:00 +00007910 };
Chris Lattner4bbf4ee2009-12-15 07:26:43 +00007911 template <>
7912 struct isPodLike<LoweredPHIRecord> { static const bool value = true; };
Chris Lattner9956c052009-11-08 19:23:30 +00007913}
7914
7915
7916/// SliceUpIllegalIntegerPHI - This is an integer PHI and we know that it has an
7917/// illegal type: see if it is only used by trunc or trunc(lshr) operations. If
7918/// so, we split the PHI into the various pieces being extracted. This sort of
7919/// thing is introduced when SROA promotes an aggregate to large integer values.
7920///
7921/// TODO: The user of the trunc may be an bitcast to float/double/vector or an
7922/// inttoptr. We should produce new PHIs in the right type.
7923///
Chris Lattnerdd21a1c2009-11-09 01:38:00 +00007924Instruction *InstCombiner::SliceUpIllegalIntegerPHI(PHINode &FirstPhi) {
7925 // PHIUsers - Keep track of all of the truncated values extracted from a set
7926 // of PHIs, along with their offset. These are the things we want to rewrite.
Chris Lattner9956c052009-11-08 19:23:30 +00007927 SmallVector<PHIUsageRecord, 16> PHIUsers;
7928
Chris Lattnerdd21a1c2009-11-09 01:38:00 +00007929 // PHIs are often mutually cyclic, so we keep track of a whole set of PHI
7930 // nodes which are extracted from. PHIsToSlice is a set we use to avoid
7931 // revisiting PHIs, PHIsInspected is a ordered list of PHIs that we need to
7932 // check the uses of (to ensure they are all extracts).
7933 SmallVector<PHINode*, 8> PHIsToSlice;
7934 SmallPtrSet<PHINode*, 8> PHIsInspected;
7935
7936 PHIsToSlice.push_back(&FirstPhi);
7937 PHIsInspected.insert(&FirstPhi);
7938
7939 for (unsigned PHIId = 0; PHIId != PHIsToSlice.size(); ++PHIId) {
7940 PHINode *PN = PHIsToSlice[PHIId];
Chris Lattner9956c052009-11-08 19:23:30 +00007941
Chris Lattner0ebc6ce2009-12-19 07:01:15 +00007942 // Scan the input list of the PHI. If any input is an invoke, and if the
7943 // input is defined in the predecessor, then we won't be split the critical
7944 // edge which is required to insert a truncate. Because of this, we have to
7945 // bail out.
7946 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
7947 InvokeInst *II = dyn_cast<InvokeInst>(PN->getIncomingValue(i));
7948 if (II == 0) continue;
7949 if (II->getParent() != PN->getIncomingBlock(i))
7950 continue;
7951
7952 // If we have a phi, and if it's directly in the predecessor, then we have
7953 // a critical edge where we need to put the truncate. Since we can't
7954 // split the edge in instcombine, we have to bail out.
7955 return 0;
7956 }
7957
7958
Chris Lattnerdd21a1c2009-11-09 01:38:00 +00007959 for (Value::use_iterator UI = PN->use_begin(), E = PN->use_end();
7960 UI != E; ++UI) {
7961 Instruction *User = cast<Instruction>(*UI);
7962
7963 // If the user is a PHI, inspect its uses recursively.
7964 if (PHINode *UserPN = dyn_cast<PHINode>(User)) {
7965 if (PHIsInspected.insert(UserPN))
7966 PHIsToSlice.push_back(UserPN);
7967 continue;
7968 }
7969
7970 // Truncates are always ok.
7971 if (isa<TruncInst>(User)) {
7972 PHIUsers.push_back(PHIUsageRecord(PHIId, 0, User));
7973 continue;
7974 }
7975
7976 // Otherwise it must be a lshr which can only be used by one trunc.
7977 if (User->getOpcode() != Instruction::LShr ||
7978 !User->hasOneUse() || !isa<TruncInst>(User->use_back()) ||
7979 !isa<ConstantInt>(User->getOperand(1)))
7980 return 0;
7981
7982 unsigned Shift = cast<ConstantInt>(User->getOperand(1))->getZExtValue();
7983 PHIUsers.push_back(PHIUsageRecord(PHIId, Shift, User->use_back()));
Chris Lattner9956c052009-11-08 19:23:30 +00007984 }
Chris Lattner9956c052009-11-08 19:23:30 +00007985 }
7986
7987 // If we have no users, they must be all self uses, just nuke the PHI.
7988 if (PHIUsers.empty())
Chris Lattnerdd21a1c2009-11-09 01:38:00 +00007989 return ReplaceInstUsesWith(FirstPhi, UndefValue::get(FirstPhi.getType()));
Chris Lattner9956c052009-11-08 19:23:30 +00007990
7991 // If this phi node is transformable, create new PHIs for all the pieces
7992 // extracted out of it. First, sort the users by their offset and size.
7993 array_pod_sort(PHIUsers.begin(), PHIUsers.end());
7994
Chris Lattnerdd21a1c2009-11-09 01:38:00 +00007995 DEBUG(errs() << "SLICING UP PHI: " << FirstPhi << '\n';
7996 for (unsigned i = 1, e = PHIsToSlice.size(); i != e; ++i)
7997 errs() << "AND USER PHI #" << i << ": " << *PHIsToSlice[i] <<'\n';
7998 );
Chris Lattner9956c052009-11-08 19:23:30 +00007999
Chris Lattnerdd21a1c2009-11-09 01:38:00 +00008000 // PredValues - This is a temporary used when rewriting PHI nodes. It is
8001 // hoisted out here to avoid construction/destruction thrashing.
Chris Lattner9956c052009-11-08 19:23:30 +00008002 DenseMap<BasicBlock*, Value*> PredValues;
8003
Chris Lattnerdd21a1c2009-11-09 01:38:00 +00008004 // ExtractedVals - Each new PHI we introduce is saved here so we don't
8005 // introduce redundant PHIs.
8006 DenseMap<LoweredPHIRecord, PHINode*> ExtractedVals;
8007
8008 for (unsigned UserI = 0, UserE = PHIUsers.size(); UserI != UserE; ++UserI) {
8009 unsigned PHIId = PHIUsers[UserI].PHIId;
8010 PHINode *PN = PHIsToSlice[PHIId];
Chris Lattner9956c052009-11-08 19:23:30 +00008011 unsigned Offset = PHIUsers[UserI].Shift;
8012 const Type *Ty = PHIUsers[UserI].Inst->getType();
Chris Lattner9956c052009-11-08 19:23:30 +00008013
Chris Lattnerdd21a1c2009-11-09 01:38:00 +00008014 PHINode *EltPHI;
8015
8016 // If we've already lowered a user like this, reuse the previously lowered
8017 // value.
8018 if ((EltPHI = ExtractedVals[LoweredPHIRecord(PN, Offset, Ty)]) == 0) {
Chris Lattner9956c052009-11-08 19:23:30 +00008019
Chris Lattnerdd21a1c2009-11-09 01:38:00 +00008020 // Otherwise, Create the new PHI node for this user.
8021 EltPHI = PHINode::Create(Ty, PN->getName()+".off"+Twine(Offset), PN);
8022 assert(EltPHI->getType() != PN->getType() &&
8023 "Truncate didn't shrink phi?");
8024
8025 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
8026 BasicBlock *Pred = PN->getIncomingBlock(i);
8027 Value *&PredVal = PredValues[Pred];
8028
8029 // If we already have a value for this predecessor, reuse it.
8030 if (PredVal) {
8031 EltPHI->addIncoming(PredVal, Pred);
8032 continue;
8033 }
Chris Lattner9956c052009-11-08 19:23:30 +00008034
Chris Lattnerdd21a1c2009-11-09 01:38:00 +00008035 // Handle the PHI self-reuse case.
8036 Value *InVal = PN->getIncomingValue(i);
8037 if (InVal == PN) {
8038 PredVal = EltPHI;
8039 EltPHI->addIncoming(PredVal, Pred);
8040 continue;
Chris Lattner0ebc6ce2009-12-19 07:01:15 +00008041 }
8042
8043 if (PHINode *InPHI = dyn_cast<PHINode>(PN)) {
Chris Lattnerdd21a1c2009-11-09 01:38:00 +00008044 // If the incoming value was a PHI, and if it was one of the PHIs we
8045 // already rewrote it, just use the lowered value.
8046 if (Value *Res = ExtractedVals[LoweredPHIRecord(InPHI, Offset, Ty)]) {
8047 PredVal = Res;
8048 EltPHI->addIncoming(PredVal, Pred);
8049 continue;
8050 }
8051 }
8052
8053 // Otherwise, do an extract in the predecessor.
8054 Builder->SetInsertPoint(Pred, Pred->getTerminator());
8055 Value *Res = InVal;
8056 if (Offset)
8057 Res = Builder->CreateLShr(Res, ConstantInt::get(InVal->getType(),
8058 Offset), "extract");
8059 Res = Builder->CreateTrunc(Res, Ty, "extract.t");
8060 PredVal = Res;
8061 EltPHI->addIncoming(Res, Pred);
8062
8063 // If the incoming value was a PHI, and if it was one of the PHIs we are
8064 // rewriting, we will ultimately delete the code we inserted. This
8065 // means we need to revisit that PHI to make sure we extract out the
8066 // needed piece.
8067 if (PHINode *OldInVal = dyn_cast<PHINode>(PN->getIncomingValue(i)))
8068 if (PHIsInspected.count(OldInVal)) {
8069 unsigned RefPHIId = std::find(PHIsToSlice.begin(),PHIsToSlice.end(),
8070 OldInVal)-PHIsToSlice.begin();
8071 PHIUsers.push_back(PHIUsageRecord(RefPHIId, Offset,
8072 cast<Instruction>(Res)));
8073 ++UserE;
8074 }
Chris Lattner9956c052009-11-08 19:23:30 +00008075 }
Chris Lattnerdd21a1c2009-11-09 01:38:00 +00008076 PredValues.clear();
Chris Lattner9956c052009-11-08 19:23:30 +00008077
Chris Lattnerdd21a1c2009-11-09 01:38:00 +00008078 DEBUG(errs() << " Made element PHI for offset " << Offset << ": "
8079 << *EltPHI << '\n');
8080 ExtractedVals[LoweredPHIRecord(PN, Offset, Ty)] = EltPHI;
Chris Lattner9956c052009-11-08 19:23:30 +00008081 }
Chris Lattner9956c052009-11-08 19:23:30 +00008082
Chris Lattnerdd21a1c2009-11-09 01:38:00 +00008083 // Replace the use of this piece with the PHI node.
8084 ReplaceInstUsesWith(*PHIUsers[UserI].Inst, EltPHI);
Chris Lattner9956c052009-11-08 19:23:30 +00008085 }
Chris Lattnerdd21a1c2009-11-09 01:38:00 +00008086
8087 // Replace all the remaining uses of the PHI nodes (self uses and the lshrs)
8088 // with undefs.
8089 Value *Undef = UndefValue::get(FirstPhi.getType());
8090 for (unsigned i = 1, e = PHIsToSlice.size(); i != e; ++i)
8091 ReplaceInstUsesWith(*PHIsToSlice[i], Undef);
8092 return ReplaceInstUsesWith(FirstPhi, Undef);
Chris Lattner9956c052009-11-08 19:23:30 +00008093}
8094
Chris Lattner473945d2002-05-06 18:06:38 +00008095// PHINode simplification
8096//
Chris Lattner7e708292002-06-25 16:13:24 +00008097Instruction *InstCombiner::visitPHINode(PHINode &PN) {
Owen Andersonb64ab872006-07-10 22:15:25 +00008098 // If LCSSA is around, don't mess with Phi nodes
Chris Lattnerf964f322007-03-04 04:27:24 +00008099 if (MustPreserveLCSSA) return 0;
Owen Andersond1b78a12006-07-10 19:03:49 +00008100
Owen Anderson7e057142006-07-10 22:03:18 +00008101 if (Value *V = PN.hasConstantValue())
8102 return ReplaceInstUsesWith(PN, V);
8103
Owen Anderson7e057142006-07-10 22:03:18 +00008104 // If all PHI operands are the same operation, pull them through the PHI,
8105 // reducing code size.
8106 if (isa<Instruction>(PN.getIncomingValue(0)) &&
Chris Lattner05f18922008-12-01 02:34:36 +00008107 isa<Instruction>(PN.getIncomingValue(1)) &&
8108 cast<Instruction>(PN.getIncomingValue(0))->getOpcode() ==
8109 cast<Instruction>(PN.getIncomingValue(1))->getOpcode() &&
8110 // FIXME: The hasOneUse check will fail for PHIs that use the value more
8111 // than themselves more than once.
Owen Anderson7e057142006-07-10 22:03:18 +00008112 PN.getIncomingValue(0)->hasOneUse())
8113 if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
8114 return Result;
8115
8116 // If this is a trivial cycle in the PHI node graph, remove it. Basically, if
8117 // this PHI only has a single use (a PHI), and if that PHI only has one use (a
8118 // PHI)... break the cycle.
Chris Lattnerff9f13a2007-01-15 07:30:06 +00008119 if (PN.hasOneUse()) {
8120 Instruction *PHIUser = cast<Instruction>(PN.use_back());
8121 if (PHINode *PU = dyn_cast<PHINode>(PHIUser)) {
Chris Lattner0e5444b2007-03-26 20:40:50 +00008122 SmallPtrSet<PHINode*, 16> PotentiallyDeadPHIs;
Owen Anderson7e057142006-07-10 22:03:18 +00008123 PotentiallyDeadPHIs.insert(&PN);
8124 if (DeadPHICycle(PU, PotentiallyDeadPHIs))
Owen Anderson9e9a0d52009-07-30 23:03:37 +00008125 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
Owen Anderson7e057142006-07-10 22:03:18 +00008126 }
Chris Lattnerff9f13a2007-01-15 07:30:06 +00008127
8128 // If this phi has a single use, and if that use just computes a value for
8129 // the next iteration of a loop, delete the phi. This occurs with unused
8130 // induction variables, e.g. "for (int j = 0; ; ++j);". Detecting this
8131 // common case here is good because the only other things that catch this
8132 // are induction variable analysis (sometimes) and ADCE, which is only run
8133 // late.
8134 if (PHIUser->hasOneUse() &&
8135 (isa<BinaryOperator>(PHIUser) || isa<GetElementPtrInst>(PHIUser)) &&
8136 PHIUser->use_back() == &PN) {
Owen Anderson9e9a0d52009-07-30 23:03:37 +00008137 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
Chris Lattnerff9f13a2007-01-15 07:30:06 +00008138 }
8139 }
Owen Anderson7e057142006-07-10 22:03:18 +00008140
Chris Lattnercf5008a2007-11-06 21:52:06 +00008141 // We sometimes end up with phi cycles that non-obviously end up being the
8142 // same value, for example:
8143 // z = some value; x = phi (y, z); y = phi (x, z)
8144 // where the phi nodes don't necessarily need to be in the same block. Do a
8145 // quick check to see if the PHI node only contains a single non-phi value, if
8146 // so, scan to see if the phi cycle is actually equal to that value.
8147 {
8148 unsigned InValNo = 0, NumOperandVals = PN.getNumIncomingValues();
8149 // Scan for the first non-phi operand.
8150 while (InValNo != NumOperandVals &&
8151 isa<PHINode>(PN.getIncomingValue(InValNo)))
8152 ++InValNo;
8153
8154 if (InValNo != NumOperandVals) {
8155 Value *NonPhiInVal = PN.getOperand(InValNo);
8156
8157 // Scan the rest of the operands to see if there are any conflicts, if so
8158 // there is no need to recursively scan other phis.
8159 for (++InValNo; InValNo != NumOperandVals; ++InValNo) {
8160 Value *OpVal = PN.getIncomingValue(InValNo);
8161 if (OpVal != NonPhiInVal && !isa<PHINode>(OpVal))
8162 break;
8163 }
8164
8165 // If we scanned over all operands, then we have one unique value plus
8166 // phi values. Scan PHI nodes to see if they all merge in each other or
8167 // the value.
8168 if (InValNo == NumOperandVals) {
8169 SmallPtrSet<PHINode*, 16> ValueEqualPHIs;
8170 if (PHIsEqualValue(&PN, NonPhiInVal, ValueEqualPHIs))
8171 return ReplaceInstUsesWith(PN, NonPhiInVal);
8172 }
8173 }
8174 }
Dan Gohman8e42e4b2009-10-30 22:22:22 +00008175
Dan Gohman5b097012009-10-31 14:22:52 +00008176 // If there are multiple PHIs, sort their operands so that they all list
8177 // the blocks in the same order. This will help identical PHIs be eliminated
8178 // by other passes. Other passes shouldn't depend on this for correctness
8179 // however.
8180 PHINode *FirstPN = cast<PHINode>(PN.getParent()->begin());
8181 if (&PN != FirstPN)
8182 for (unsigned i = 0, e = FirstPN->getNumIncomingValues(); i != e; ++i) {
Dan Gohman8e42e4b2009-10-30 22:22:22 +00008183 BasicBlock *BBA = PN.getIncomingBlock(i);
Dan Gohman5b097012009-10-31 14:22:52 +00008184 BasicBlock *BBB = FirstPN->getIncomingBlock(i);
8185 if (BBA != BBB) {
8186 Value *VA = PN.getIncomingValue(i);
8187 unsigned j = PN.getBasicBlockIndex(BBB);
8188 Value *VB = PN.getIncomingValue(j);
8189 PN.setIncomingBlock(i, BBB);
8190 PN.setIncomingValue(i, VB);
8191 PN.setIncomingBlock(j, BBA);
8192 PN.setIncomingValue(j, VA);
Chris Lattner28f3d342009-10-31 17:48:31 +00008193 // NOTE: Instcombine normally would want us to "return &PN" if we
8194 // modified any of the operands of an instruction. However, since we
8195 // aren't adding or removing uses (just rearranging them) we don't do
8196 // this in this case.
Dan Gohman5b097012009-10-31 14:22:52 +00008197 }
Dan Gohman8e42e4b2009-10-30 22:22:22 +00008198 }
8199
Chris Lattner9956c052009-11-08 19:23:30 +00008200 // If this is an integer PHI and we know that it has an illegal type, see if
8201 // it is only used by trunc or trunc(lshr) operations. If so, we split the
8202 // PHI into the various pieces being extracted. This sort of thing is
8203 // introduced when SROA promotes an aggregate to a single large integer type.
Chris Lattnerbf382b52009-11-08 21:20:06 +00008204 if (isa<IntegerType>(PN.getType()) && TD &&
Chris Lattner9956c052009-11-08 19:23:30 +00008205 !TD->isLegalInteger(PN.getType()->getPrimitiveSizeInBits()))
8206 if (Instruction *Res = SliceUpIllegalIntegerPHI(PN))
8207 return Res;
8208
Chris Lattner60921c92003-12-19 05:58:40 +00008209 return 0;
Chris Lattner473945d2002-05-06 18:06:38 +00008210}
8211
Chris Lattner7e708292002-06-25 16:13:24 +00008212Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
Chris Lattnerc514c1f2009-11-27 00:29:05 +00008213 SmallVector<Value*, 8> Ops(GEP.op_begin(), GEP.op_end());
8214
8215 if (Value *V = SimplifyGEPInst(&Ops[0], Ops.size(), TD))
8216 return ReplaceInstUsesWith(GEP, V);
8217
Chris Lattner620ce142004-05-07 22:09:22 +00008218 Value *PtrOp = GEP.getOperand(0);
Chris Lattnerc6bd1952004-02-22 05:25:17 +00008219
Chris Lattnere87597f2004-10-16 18:11:37 +00008220 if (isa<UndefValue>(GEP.getOperand(0)))
Owen Anderson9e9a0d52009-07-30 23:03:37 +00008221 return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00008222
Chris Lattner28977af2004-04-05 01:30:19 +00008223 // Eliminate unneeded casts for indices.
Chris Lattnerccf4b342009-08-30 04:49:01 +00008224 if (TD) {
8225 bool MadeChange = false;
8226 unsigned PtrSize = TD->getPointerSizeInBits();
8227
8228 gep_type_iterator GTI = gep_type_begin(GEP);
8229 for (User::op_iterator I = GEP.op_begin() + 1, E = GEP.op_end();
8230 I != E; ++I, ++GTI) {
8231 if (!isa<SequentialType>(*GTI)) continue;
8232
Chris Lattnercb69a4e2004-04-07 18:38:20 +00008233 // If we are using a wider index than needed for this platform, shrink it
Chris Lattnerccf4b342009-08-30 04:49:01 +00008234 // to what we need. If narrower, sign-extend it to what we need. This
8235 // explicit cast can make subsequent optimizations more obvious.
8236 unsigned OpBits = cast<IntegerType>((*I)->getType())->getBitWidth();
Chris Lattnerccf4b342009-08-30 04:49:01 +00008237 if (OpBits == PtrSize)
8238 continue;
8239
Chris Lattner2345d1d2009-08-30 20:01:10 +00008240 *I = Builder->CreateIntCast(*I, TD->getIntPtrType(GEP.getContext()),true);
Chris Lattnerccf4b342009-08-30 04:49:01 +00008241 MadeChange = true;
Chris Lattner28977af2004-04-05 01:30:19 +00008242 }
Chris Lattnerccf4b342009-08-30 04:49:01 +00008243 if (MadeChange) return &GEP;
Chris Lattnerdb9654e2007-03-25 20:43:09 +00008244 }
Chris Lattner28977af2004-04-05 01:30:19 +00008245
Chris Lattner90ac28c2002-08-02 19:29:35 +00008246 // Combine Indices - If the source pointer to this getelementptr instruction
8247 // is a getelementptr instruction, combine the indices of the two
8248 // getelementptr instructions into a single instruction.
8249 //
Dan Gohmand6aa02d2009-07-28 01:40:03 +00008250 if (GEPOperator *Src = dyn_cast<GEPOperator>(PtrOp)) {
Chris Lattner620ce142004-05-07 22:09:22 +00008251 // Note that if our source is a gep chain itself that we wait for that
8252 // chain to be resolved before we perform this transformation. This
8253 // avoids us creating a TON of code in some cases.
8254 //
Chris Lattnerf9b91bb2009-08-30 05:08:50 +00008255 if (GetElementPtrInst *SrcGEP =
8256 dyn_cast<GetElementPtrInst>(Src->getOperand(0)))
8257 if (SrcGEP->getNumOperands() == 2)
8258 return 0; // Wait until our source is folded to completion.
Chris Lattner620ce142004-05-07 22:09:22 +00008259
Chris Lattner72588fc2007-02-15 22:48:32 +00008260 SmallVector<Value*, 8> Indices;
Chris Lattner620ce142004-05-07 22:09:22 +00008261
8262 // Find out whether the last index in the source GEP is a sequential idx.
8263 bool EndsWithSequential = false;
Chris Lattnerab984842009-08-30 05:30:55 +00008264 for (gep_type_iterator I = gep_type_begin(*Src), E = gep_type_end(*Src);
8265 I != E; ++I)
Chris Lattnerbe97b4e2004-05-08 22:41:42 +00008266 EndsWithSequential = !isa<StructType>(*I);
Misha Brukmanfd939082005-04-21 23:48:37 +00008267
Chris Lattner90ac28c2002-08-02 19:29:35 +00008268 // Can we combine the two pointer arithmetics offsets?
Chris Lattner620ce142004-05-07 22:09:22 +00008269 if (EndsWithSequential) {
Chris Lattnerdecd0812003-03-05 22:33:14 +00008270 // Replace: gep (gep %P, long B), long A, ...
8271 // With: T = long A+B; gep %P, T, ...
8272 //
Chris Lattnerf9b91bb2009-08-30 05:08:50 +00008273 Value *Sum;
8274 Value *SO1 = Src->getOperand(Src->getNumOperands()-1);
8275 Value *GO1 = GEP.getOperand(1);
Owen Andersona7235ea2009-07-31 20:28:14 +00008276 if (SO1 == Constant::getNullValue(SO1->getType())) {
Chris Lattner28977af2004-04-05 01:30:19 +00008277 Sum = GO1;
Owen Andersona7235ea2009-07-31 20:28:14 +00008278 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
Chris Lattner28977af2004-04-05 01:30:19 +00008279 Sum = SO1;
8280 } else {
Chris Lattnerab984842009-08-30 05:30:55 +00008281 // If they aren't the same type, then the input hasn't been processed
8282 // by the loop above yet (which canonicalizes sequential index types to
8283 // intptr_t). Just avoid transforming this until the input has been
8284 // normalized.
8285 if (SO1->getType() != GO1->getType())
8286 return 0;
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008287 Sum = Builder->CreateAdd(SO1, GO1, PtrOp->getName()+".sum");
Chris Lattner28977af2004-04-05 01:30:19 +00008288 }
Chris Lattner620ce142004-05-07 22:09:22 +00008289
Chris Lattnerab984842009-08-30 05:30:55 +00008290 // Update the GEP in place if possible.
Chris Lattnerf9b91bb2009-08-30 05:08:50 +00008291 if (Src->getNumOperands() == 2) {
8292 GEP.setOperand(0, Src->getOperand(0));
Chris Lattner620ce142004-05-07 22:09:22 +00008293 GEP.setOperand(1, Sum);
8294 return &GEP;
Chris Lattner620ce142004-05-07 22:09:22 +00008295 }
Chris Lattnerab984842009-08-30 05:30:55 +00008296 Indices.append(Src->op_begin()+1, Src->op_end()-1);
Chris Lattnerccf4b342009-08-30 04:49:01 +00008297 Indices.push_back(Sum);
Chris Lattnerab984842009-08-30 05:30:55 +00008298 Indices.append(GEP.op_begin()+2, GEP.op_end());
Misha Brukmanfd939082005-04-21 23:48:37 +00008299 } else if (isa<Constant>(*GEP.idx_begin()) &&
Chris Lattner28977af2004-04-05 01:30:19 +00008300 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
Chris Lattnerf9b91bb2009-08-30 05:08:50 +00008301 Src->getNumOperands() != 1) {
Chris Lattner90ac28c2002-08-02 19:29:35 +00008302 // Otherwise we can do the fold if the first index of the GEP is a zero
Chris Lattnerab984842009-08-30 05:30:55 +00008303 Indices.append(Src->op_begin()+1, Src->op_end());
8304 Indices.append(GEP.idx_begin()+1, GEP.idx_end());
Chris Lattner90ac28c2002-08-02 19:29:35 +00008305 }
8306
Dan Gohmanf8dbee72009-09-07 23:54:19 +00008307 if (!Indices.empty())
8308 return (cast<GEPOperator>(&GEP)->isInBounds() &&
8309 Src->isInBounds()) ?
8310 GetElementPtrInst::CreateInBounds(Src->getOperand(0), Indices.begin(),
8311 Indices.end(), GEP.getName()) :
Chris Lattnerf9b91bb2009-08-30 05:08:50 +00008312 GetElementPtrInst::Create(Src->getOperand(0), Indices.begin(),
Chris Lattnerccf4b342009-08-30 04:49:01 +00008313 Indices.end(), GEP.getName());
Chris Lattner6e24d832009-08-30 05:00:50 +00008314 }
8315
Chris Lattnerf9b91bb2009-08-30 05:08:50 +00008316 // Handle gep(bitcast x) and gep(gep x, 0, 0, 0).
8317 if (Value *X = getBitCastOperand(PtrOp)) {
Chris Lattner6e24d832009-08-30 05:00:50 +00008318 assert(isa<PointerType>(X->getType()) && "Must be cast from pointer");
Chris Lattner963f4ba2009-08-30 20:36:46 +00008319
Chris Lattner2de23192009-08-30 20:38:21 +00008320 // If the input bitcast is actually "bitcast(bitcast(x))", then we don't
8321 // want to change the gep until the bitcasts are eliminated.
8322 if (getBitCastOperand(X)) {
8323 Worklist.AddValue(PtrOp);
8324 return 0;
8325 }
8326
Chris Lattnerc514c1f2009-11-27 00:29:05 +00008327 bool HasZeroPointerIndex = false;
8328 if (ConstantInt *C = dyn_cast<ConstantInt>(GEP.getOperand(1)))
8329 HasZeroPointerIndex = C->isZero();
8330
Chris Lattner963f4ba2009-08-30 20:36:46 +00008331 // Transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ...
8332 // into : GEP [10 x i8]* X, i32 0, ...
8333 //
8334 // Likewise, transform: GEP (bitcast i8* X to [0 x i8]*), i32 0, ...
8335 // into : GEP i8* X, ...
8336 //
8337 // This occurs when the program declares an array extern like "int X[];"
Chris Lattner6e24d832009-08-30 05:00:50 +00008338 if (HasZeroPointerIndex) {
Chris Lattnereed48272005-09-13 00:40:14 +00008339 const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
8340 const PointerType *XTy = cast<PointerType>(X->getType());
Duncan Sands5b7cfb02009-03-02 09:18:21 +00008341 if (const ArrayType *CATy =
8342 dyn_cast<ArrayType>(CPTy->getElementType())) {
8343 // GEP (bitcast i8* X to [0 x i8]*), i32 0, ... ?
8344 if (CATy->getElementType() == XTy->getElementType()) {
8345 // -> GEP i8* X, ...
8346 SmallVector<Value*, 8> Indices(GEP.idx_begin()+1, GEP.idx_end());
Dan Gohmanf8dbee72009-09-07 23:54:19 +00008347 return cast<GEPOperator>(&GEP)->isInBounds() ?
8348 GetElementPtrInst::CreateInBounds(X, Indices.begin(), Indices.end(),
8349 GEP.getName()) :
Dan Gohmand6aa02d2009-07-28 01:40:03 +00008350 GetElementPtrInst::Create(X, Indices.begin(), Indices.end(),
8351 GEP.getName());
Chris Lattner963f4ba2009-08-30 20:36:46 +00008352 }
8353
8354 if (const ArrayType *XATy = dyn_cast<ArrayType>(XTy->getElementType())){
Duncan Sands5b7cfb02009-03-02 09:18:21 +00008355 // GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ... ?
Chris Lattnereed48272005-09-13 00:40:14 +00008356 if (CATy->getElementType() == XATy->getElementType()) {
Duncan Sands5b7cfb02009-03-02 09:18:21 +00008357 // -> GEP [10 x i8]* X, i32 0, ...
Chris Lattnereed48272005-09-13 00:40:14 +00008358 // At this point, we know that the cast source type is a pointer
8359 // to an array of the same type as the destination pointer
8360 // array. Because the array type is never stepped over (there
8361 // is a leading zero) we can fold the cast into this GEP.
8362 GEP.setOperand(0, X);
8363 return &GEP;
8364 }
Duncan Sands5b7cfb02009-03-02 09:18:21 +00008365 }
8366 }
Chris Lattnereed48272005-09-13 00:40:14 +00008367 } else if (GEP.getNumOperands() == 2) {
8368 // Transform things like:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +00008369 // %t = getelementptr i32* bitcast ([2 x i32]* %str to i32*), i32 %V
8370 // into: %t1 = getelementptr [2 x i32]* %str, i32 0, i32 %V; bitcast
Chris Lattnereed48272005-09-13 00:40:14 +00008371 const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
8372 const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
Dan Gohmance9fe9f2009-07-21 23:21:54 +00008373 if (TD && isa<ArrayType>(SrcElTy) &&
Duncan Sands777d2302009-05-09 07:06:46 +00008374 TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
8375 TD->getTypeAllocSize(ResElTy)) {
David Greeneb8f74792007-09-04 15:46:09 +00008376 Value *Idx[2];
Chris Lattner4de84762010-01-04 07:02:48 +00008377 Idx[0] = Constant::getNullValue(Type::getInt32Ty(GEP.getContext()));
David Greeneb8f74792007-09-04 15:46:09 +00008378 Idx[1] = GEP.getOperand(1);
Dan Gohmanf8dbee72009-09-07 23:54:19 +00008379 Value *NewGEP = cast<GEPOperator>(&GEP)->isInBounds() ?
8380 Builder->CreateInBoundsGEP(X, Idx, Idx + 2, GEP.getName()) :
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008381 Builder->CreateGEP(X, Idx, Idx + 2, GEP.getName());
Reid Spencer3da59db2006-11-27 01:05:10 +00008382 // V and GEP are both pointer types --> BitCast
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008383 return new BitCastInst(NewGEP, GEP.getType());
Chris Lattnerc6bd1952004-02-22 05:25:17 +00008384 }
Chris Lattner7835cdd2005-09-13 18:36:04 +00008385
8386 // Transform things like:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +00008387 // getelementptr i8* bitcast ([100 x double]* X to i8*), i32 %tmp
Chris Lattner7835cdd2005-09-13 18:36:04 +00008388 // (where tmp = 8*tmp2) into:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +00008389 // getelementptr [100 x double]* %arr, i32 0, i32 %tmp2; bitcast
Chris Lattner7835cdd2005-09-13 18:36:04 +00008390
Chris Lattner4de84762010-01-04 07:02:48 +00008391 if (TD && isa<ArrayType>(SrcElTy) &&
8392 ResElTy == Type::getInt8Ty(GEP.getContext())) {
Chris Lattner7835cdd2005-09-13 18:36:04 +00008393 uint64_t ArrayEltSize =
Duncan Sands777d2302009-05-09 07:06:46 +00008394 TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType());
Chris Lattner7835cdd2005-09-13 18:36:04 +00008395
8396 // Check to see if "tmp" is a scale by a multiple of ArrayEltSize. We
8397 // allow either a mul, shift, or constant here.
8398 Value *NewIdx = 0;
8399 ConstantInt *Scale = 0;
8400 if (ArrayEltSize == 1) {
8401 NewIdx = GEP.getOperand(1);
Chris Lattnerab984842009-08-30 05:30:55 +00008402 Scale = ConstantInt::get(cast<IntegerType>(NewIdx->getType()), 1);
Chris Lattner7835cdd2005-09-13 18:36:04 +00008403 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
Owen Andersoneed707b2009-07-24 23:12:02 +00008404 NewIdx = ConstantInt::get(CI->getType(), 1);
Chris Lattner7835cdd2005-09-13 18:36:04 +00008405 Scale = CI;
8406 } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
8407 if (Inst->getOpcode() == Instruction::Shl &&
8408 isa<ConstantInt>(Inst->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00008409 ConstantInt *ShAmt = cast<ConstantInt>(Inst->getOperand(1));
8410 uint32_t ShAmtVal = ShAmt->getLimitedValue(64);
Owen Andersoneed707b2009-07-24 23:12:02 +00008411 Scale = ConstantInt::get(cast<IntegerType>(Inst->getType()),
Dan Gohman6de29f82009-06-15 22:12:54 +00008412 1ULL << ShAmtVal);
Chris Lattner7835cdd2005-09-13 18:36:04 +00008413 NewIdx = Inst->getOperand(0);
8414 } else if (Inst->getOpcode() == Instruction::Mul &&
8415 isa<ConstantInt>(Inst->getOperand(1))) {
8416 Scale = cast<ConstantInt>(Inst->getOperand(1));
8417 NewIdx = Inst->getOperand(0);
8418 }
8419 }
Wojciech Matyjewiczed223252007-12-12 15:21:32 +00008420
Chris Lattner7835cdd2005-09-13 18:36:04 +00008421 // If the index will be to exactly the right offset with the scale taken
Wojciech Matyjewiczed223252007-12-12 15:21:32 +00008422 // out, perform the transformation. Note, we don't know whether Scale is
8423 // signed or not. We'll use unsigned version of division/modulo
8424 // operation after making sure Scale doesn't have the sign bit set.
Chris Lattner58b1ac72009-02-25 18:20:01 +00008425 if (ArrayEltSize && Scale && Scale->getSExtValue() >= 0LL &&
Wojciech Matyjewiczed223252007-12-12 15:21:32 +00008426 Scale->getZExtValue() % ArrayEltSize == 0) {
Owen Andersoneed707b2009-07-24 23:12:02 +00008427 Scale = ConstantInt::get(Scale->getType(),
Wojciech Matyjewiczed223252007-12-12 15:21:32 +00008428 Scale->getZExtValue() / ArrayEltSize);
Reid Spencerb83eb642006-10-20 07:07:24 +00008429 if (Scale->getZExtValue() != 1) {
Chris Lattner878daed2009-08-30 05:56:44 +00008430 Constant *C = ConstantExpr::getIntegerCast(Scale, NewIdx->getType(),
8431 false /*ZExt*/);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008432 NewIdx = Builder->CreateMul(NewIdx, C, "idxscale");
Chris Lattner7835cdd2005-09-13 18:36:04 +00008433 }
8434
8435 // Insert the new GEP instruction.
David Greeneb8f74792007-09-04 15:46:09 +00008436 Value *Idx[2];
Chris Lattner4de84762010-01-04 07:02:48 +00008437 Idx[0] = Constant::getNullValue(Type::getInt32Ty(GEP.getContext()));
David Greeneb8f74792007-09-04 15:46:09 +00008438 Idx[1] = NewIdx;
Dan Gohmanf8dbee72009-09-07 23:54:19 +00008439 Value *NewGEP = cast<GEPOperator>(&GEP)->isInBounds() ?
8440 Builder->CreateInBoundsGEP(X, Idx, Idx + 2, GEP.getName()) :
8441 Builder->CreateGEP(X, Idx, Idx + 2, GEP.getName());
Reid Spencer3da59db2006-11-27 01:05:10 +00008442 // The NewGEP must be pointer typed, so must the old one -> BitCast
8443 return new BitCastInst(NewGEP, GEP.getType());
Chris Lattner7835cdd2005-09-13 18:36:04 +00008444 }
8445 }
Chris Lattnerc6bd1952004-02-22 05:25:17 +00008446 }
Chris Lattner8a2a3112001-12-14 16:52:21 +00008447 }
Chris Lattner58407792009-01-09 04:53:57 +00008448
Chris Lattner46cd5a12009-01-09 05:44:56 +00008449 /// See if we can simplify:
Chris Lattner873ff012009-08-30 05:55:36 +00008450 /// X = bitcast A* to B*
Chris Lattner46cd5a12009-01-09 05:44:56 +00008451 /// Y = gep X, <...constant indices...>
8452 /// into a gep of the original struct. This is important for SROA and alias
8453 /// analysis of unions. If "A" is also a bitcast, wait for A/X to be merged.
Chris Lattner58407792009-01-09 04:53:57 +00008454 if (BitCastInst *BCI = dyn_cast<BitCastInst>(PtrOp)) {
Dan Gohmance9fe9f2009-07-21 23:21:54 +00008455 if (TD &&
8456 !isa<BitCastInst>(BCI->getOperand(0)) && GEP.hasAllConstantIndices()) {
Chris Lattner46cd5a12009-01-09 05:44:56 +00008457 // Determine how much the GEP moves the pointer. We are guaranteed to get
8458 // a constant back from EmitGEPOffset.
Chris Lattner02446fc2010-01-04 07:37:31 +00008459 ConstantInt *OffsetV = cast<ConstantInt>(EmitGEPOffset(&GEP));
Chris Lattner46cd5a12009-01-09 05:44:56 +00008460 int64_t Offset = OffsetV->getSExtValue();
8461
8462 // If this GEP instruction doesn't move the pointer, just replace the GEP
8463 // with a bitcast of the real input to the dest type.
8464 if (Offset == 0) {
8465 // If the bitcast is of an allocation, and the allocation will be
8466 // converted to match the type of the cast, don't touch this.
Victor Hernandez7b929da2009-10-23 21:09:37 +00008467 if (isa<AllocaInst>(BCI->getOperand(0)) ||
Victor Hernandez83d63912009-09-18 22:35:49 +00008468 isMalloc(BCI->getOperand(0))) {
Chris Lattner46cd5a12009-01-09 05:44:56 +00008469 // See if the bitcast simplifies, if so, don't nuke this GEP yet.
8470 if (Instruction *I = visitBitCast(*BCI)) {
8471 if (I != BCI) {
8472 I->takeName(BCI);
8473 BCI->getParent()->getInstList().insert(BCI, I);
8474 ReplaceInstUsesWith(*BCI, I);
8475 }
8476 return &GEP;
Chris Lattner58407792009-01-09 04:53:57 +00008477 }
Chris Lattner58407792009-01-09 04:53:57 +00008478 }
Chris Lattner46cd5a12009-01-09 05:44:56 +00008479 return new BitCastInst(BCI->getOperand(0), GEP.getType());
Chris Lattner58407792009-01-09 04:53:57 +00008480 }
Chris Lattner46cd5a12009-01-09 05:44:56 +00008481
8482 // Otherwise, if the offset is non-zero, we need to find out if there is a
8483 // field at Offset in 'A's type. If so, we can pull the cast through the
8484 // GEP.
8485 SmallVector<Value*, 8> NewIndices;
8486 const Type *InTy =
8487 cast<PointerType>(BCI->getOperand(0)->getType())->getElementType();
Chris Lattner4de84762010-01-04 07:02:48 +00008488 if (FindElementAtOffset(InTy, Offset, NewIndices, TD)) {
Dan Gohmanf8dbee72009-09-07 23:54:19 +00008489 Value *NGEP = cast<GEPOperator>(&GEP)->isInBounds() ?
8490 Builder->CreateInBoundsGEP(BCI->getOperand(0), NewIndices.begin(),
8491 NewIndices.end()) :
8492 Builder->CreateGEP(BCI->getOperand(0), NewIndices.begin(),
8493 NewIndices.end());
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008494
8495 if (NGEP->getType() == GEP.getType())
8496 return ReplaceInstUsesWith(GEP, NGEP);
Chris Lattner46cd5a12009-01-09 05:44:56 +00008497 NGEP->takeName(&GEP);
8498 return new BitCastInst(NGEP, GEP.getType());
8499 }
Chris Lattner58407792009-01-09 04:53:57 +00008500 }
8501 }
8502
Chris Lattner8a2a3112001-12-14 16:52:21 +00008503 return 0;
8504}
8505
Victor Hernandez7b929da2009-10-23 21:09:37 +00008506Instruction *InstCombiner::visitAllocaInst(AllocaInst &AI) {
Chris Lattnere3c62812009-11-01 19:50:13 +00008507 // Convert: alloca Ty, C - where C is a constant != 1 into: alloca [C x Ty], 1
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00008508 if (AI.isArrayAllocation()) { // Check C != 1
Reid Spencerb83eb642006-10-20 07:07:24 +00008509 if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
8510 const Type *NewTy =
Owen Andersondebcb012009-07-29 22:17:13 +00008511 ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
Victor Hernandeza276c602009-10-17 01:18:07 +00008512 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
Victor Hernandez7b929da2009-10-23 21:09:37 +00008513 AllocaInst *New = Builder->CreateAlloca(NewTy, 0, AI.getName());
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008514 New->setAlignment(AI.getAlignment());
Misha Brukmanfd939082005-04-21 23:48:37 +00008515
Chris Lattner0864acf2002-11-04 16:18:53 +00008516 // Scan to the end of the allocation instructions, to skip over a block of
Dale Johannesena8915182009-03-11 22:19:43 +00008517 // allocas if possible...also skip interleaved debug info
Chris Lattner0864acf2002-11-04 16:18:53 +00008518 //
8519 BasicBlock::iterator It = New;
Victor Hernandez7b929da2009-10-23 21:09:37 +00008520 while (isa<AllocaInst>(*It) || isa<DbgInfoIntrinsic>(*It)) ++It;
Chris Lattner0864acf2002-11-04 16:18:53 +00008521
8522 // Now that I is pointing to the first non-allocation-inst in the block,
8523 // insert our getelementptr instruction...
8524 //
Chris Lattner4de84762010-01-04 07:02:48 +00008525 Value *NullIdx =Constant::getNullValue(Type::getInt32Ty(AI.getContext()));
David Greeneb8f74792007-09-04 15:46:09 +00008526 Value *Idx[2];
8527 Idx[0] = NullIdx;
8528 Idx[1] = NullIdx;
Dan Gohmanf8dbee72009-09-07 23:54:19 +00008529 Value *V = GetElementPtrInst::CreateInBounds(New, Idx, Idx + 2,
8530 New->getName()+".sub", It);
Chris Lattner0864acf2002-11-04 16:18:53 +00008531
8532 // Now make everything use the getelementptr instead of the original
8533 // allocation.
Chris Lattner7c881df2004-03-19 06:08:10 +00008534 return ReplaceInstUsesWith(AI, V);
Chris Lattnere87597f2004-10-16 18:11:37 +00008535 } else if (isa<UndefValue>(AI.getArraySize())) {
Owen Andersona7235ea2009-07-31 20:28:14 +00008536 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
Chris Lattner0864acf2002-11-04 16:18:53 +00008537 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00008538 }
Chris Lattner7c881df2004-03-19 06:08:10 +00008539
Dan Gohmance9fe9f2009-07-21 23:21:54 +00008540 if (TD && isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized()) {
Dan Gohman6893cd72009-01-13 20:18:38 +00008541 // If alloca'ing a zero byte object, replace the alloca with a null pointer.
Chris Lattner46d232d2009-03-17 17:55:15 +00008542 // Note that we only do this for alloca's, because malloc should allocate
8543 // and return a unique pointer, even for a zero byte allocation.
Duncan Sands777d2302009-05-09 07:06:46 +00008544 if (TD->getTypeAllocSize(AI.getAllocatedType()) == 0)
Owen Andersona7235ea2009-07-31 20:28:14 +00008545 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
Dan Gohman6893cd72009-01-13 20:18:38 +00008546
8547 // If the alignment is 0 (unspecified), assign it the preferred alignment.
8548 if (AI.getAlignment() == 0)
8549 AI.setAlignment(TD->getPrefTypeAlignment(AI.getAllocatedType()));
8550 }
Chris Lattner7c881df2004-03-19 06:08:10 +00008551
Chris Lattner0864acf2002-11-04 16:18:53 +00008552 return 0;
8553}
8554
Victor Hernandez66284e02009-10-24 04:23:03 +00008555Instruction *InstCombiner::visitFree(Instruction &FI) {
8556 Value *Op = FI.getOperand(1);
8557
8558 // free undef -> unreachable.
8559 if (isa<UndefValue>(Op)) {
8560 // Insert a new store to null because we cannot modify the CFG here.
Chris Lattner4de84762010-01-04 07:02:48 +00008561 new StoreInst(ConstantInt::getTrue(FI.getContext()),
8562 UndefValue::get(Type::getInt1PtrTy(FI.getContext())), &FI);
Victor Hernandez66284e02009-10-24 04:23:03 +00008563 return EraseInstFromFunction(FI);
8564 }
8565
8566 // If we have 'free null' delete the instruction. This can happen in stl code
8567 // when lots of inlining happens.
8568 if (isa<ConstantPointerNull>(Op))
8569 return EraseInstFromFunction(FI);
8570
Victor Hernandez046e78c2009-10-26 23:43:48 +00008571 // If we have a malloc call whose only use is a free call, delete both.
Dan Gohman7f712a12009-10-27 00:11:02 +00008572 if (isMalloc(Op)) {
Victor Hernandez66284e02009-10-24 04:23:03 +00008573 if (CallInst* CI = extractMallocCallFromBitCast(Op)) {
8574 if (Op->hasOneUse() && CI->hasOneUse()) {
8575 EraseInstFromFunction(FI);
8576 EraseInstFromFunction(*CI);
8577 return EraseInstFromFunction(*cast<Instruction>(Op));
8578 }
8579 } else {
8580 // Op is a call to malloc
8581 if (Op->hasOneUse()) {
8582 EraseInstFromFunction(FI);
8583 return EraseInstFromFunction(*cast<Instruction>(Op));
8584 }
8585 }
Dan Gohman7f712a12009-10-27 00:11:02 +00008586 }
Victor Hernandez66284e02009-10-24 04:23:03 +00008587
8588 return 0;
8589}
Chris Lattner67b1e1b2003-12-07 01:24:23 +00008590
Chris Lattnerfcfe33a2005-01-31 05:51:45 +00008591/// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
Devang Patel99db6ad2007-10-18 19:52:32 +00008592static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI,
Bill Wendling587c01d2008-02-26 10:53:30 +00008593 const TargetData *TD) {
Chris Lattnerb89e0712004-07-13 01:49:43 +00008594 User *CI = cast<User>(LI.getOperand(0));
Chris Lattnerf9527852005-01-31 04:50:46 +00008595 Value *CastOp = CI->getOperand(0);
Chris Lattnerb89e0712004-07-13 01:49:43 +00008596
Mon P Wang6753f952009-02-07 22:19:29 +00008597 const PointerType *DestTy = cast<PointerType>(CI->getType());
8598 const Type *DestPTy = DestTy->getElementType();
Chris Lattnerf9527852005-01-31 04:50:46 +00008599 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
Mon P Wang6753f952009-02-07 22:19:29 +00008600
8601 // If the address spaces don't match, don't eliminate the cast.
8602 if (DestTy->getAddressSpace() != SrcTy->getAddressSpace())
8603 return 0;
8604
Chris Lattnerb89e0712004-07-13 01:49:43 +00008605 const Type *SrcPTy = SrcTy->getElementType();
Chris Lattnerf9527852005-01-31 04:50:46 +00008606
Reid Spencer42230162007-01-22 05:51:25 +00008607 if (DestPTy->isInteger() || isa<PointerType>(DestPTy) ||
Reid Spencer9d6565a2007-02-15 02:26:10 +00008608 isa<VectorType>(DestPTy)) {
Chris Lattnerf9527852005-01-31 04:50:46 +00008609 // If the source is an array, the code below will not succeed. Check to
8610 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
8611 // constants.
8612 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
8613 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
8614 if (ASrcTy->getNumElements() != 0) {
Chris Lattner55eb1c42007-01-31 04:40:53 +00008615 Value *Idxs[2];
Chris Lattner4de84762010-01-04 07:02:48 +00008616 Idxs[0] = Constant::getNullValue(Type::getInt32Ty(LI.getContext()));
Chris Lattnere00c43f2009-10-22 06:44:07 +00008617 Idxs[1] = Idxs[0];
Owen Andersonbaf3c402009-07-29 18:55:55 +00008618 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
Chris Lattnerf9527852005-01-31 04:50:46 +00008619 SrcTy = cast<PointerType>(CastOp->getType());
8620 SrcPTy = SrcTy->getElementType();
8621 }
8622
Dan Gohmance9fe9f2009-07-21 23:21:54 +00008623 if (IC.getTargetData() &&
8624 (SrcPTy->isInteger() || isa<PointerType>(SrcPTy) ||
Reid Spencer9d6565a2007-02-15 02:26:10 +00008625 isa<VectorType>(SrcPTy)) &&
Chris Lattnerb1515fe2005-03-29 06:37:47 +00008626 // Do not allow turning this into a load of an integer, which is then
8627 // casted to a pointer, this pessimizes pointer analysis a lot.
8628 (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
Dan Gohmance9fe9f2009-07-21 23:21:54 +00008629 IC.getTargetData()->getTypeSizeInBits(SrcPTy) ==
8630 IC.getTargetData()->getTypeSizeInBits(DestPTy)) {
Misha Brukmanfd939082005-04-21 23:48:37 +00008631
Chris Lattnerf9527852005-01-31 04:50:46 +00008632 // Okay, we are casting from one integer or pointer type to another of
8633 // the same size. Instead of casting the pointer before the load, cast
8634 // the result of the loaded value.
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008635 Value *NewLoad =
8636 IC.Builder->CreateLoad(CastOp, LI.isVolatile(), CI->getName());
Chris Lattnerf9527852005-01-31 04:50:46 +00008637 // Now cast the result of the load.
Reid Spencerd977d862006-12-12 23:36:14 +00008638 return new BitCastInst(NewLoad, LI.getType());
Chris Lattnerf9527852005-01-31 04:50:46 +00008639 }
Chris Lattnerb89e0712004-07-13 01:49:43 +00008640 }
8641 }
8642 return 0;
8643}
8644
Chris Lattner833b8a42003-06-26 05:06:25 +00008645Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
8646 Value *Op = LI.getOperand(0);
Chris Lattner5f16a132004-01-12 04:13:56 +00008647
Dan Gohman9941f742007-07-20 16:34:21 +00008648 // Attempt to improve the alignment.
Dan Gohmance9fe9f2009-07-21 23:21:54 +00008649 if (TD) {
8650 unsigned KnownAlign =
8651 GetOrEnforceKnownAlignment(Op, TD->getPrefTypeAlignment(LI.getType()));
8652 if (KnownAlign >
8653 (LI.getAlignment() == 0 ? TD->getABITypeAlignment(LI.getType()) :
8654 LI.getAlignment()))
8655 LI.setAlignment(KnownAlign);
8656 }
Dan Gohman9941f742007-07-20 16:34:21 +00008657
Chris Lattner963f4ba2009-08-30 20:36:46 +00008658 // load (cast X) --> cast (load X) iff safe.
Reid Spencer3ed469c2006-11-02 20:25:50 +00008659 if (isa<CastInst>(Op))
Devang Patel99db6ad2007-10-18 19:52:32 +00008660 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
Chris Lattner37366c12005-05-01 04:24:53 +00008661 return Res;
8662
8663 // None of the following transforms are legal for volatile loads.
8664 if (LI.isVolatile()) return 0;
Chris Lattner62f254d2005-09-12 22:00:15 +00008665
Dan Gohman2276a7b2008-10-15 23:19:35 +00008666 // Do really simple store-to-load forwarding and load CSE, to catch cases
8667 // where there are several consequtive memory accesses to the same location,
8668 // separated by a few arithmetic operations.
8669 BasicBlock::iterator BBI = &LI;
Chris Lattner4aebaee2008-11-27 08:56:30 +00008670 if (Value *AvailableVal = FindAvailableLoadedValue(Op, LI.getParent(), BBI,6))
8671 return ReplaceInstUsesWith(LI, AvailableVal);
Chris Lattner37366c12005-05-01 04:24:53 +00008672
Chris Lattner878e4942009-10-22 06:25:11 +00008673 // load(gep null, ...) -> unreachable
Christopher Lambb15147e2007-12-29 07:56:53 +00008674 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
8675 const Value *GEPI0 = GEPI->getOperand(0);
8676 // TODO: Consider a target hook for valid address spaces for this xform.
Chris Lattner8a67ac52009-08-30 20:06:40 +00008677 if (isa<ConstantPointerNull>(GEPI0) && GEPI->getPointerAddressSpace() == 0){
Chris Lattner37366c12005-05-01 04:24:53 +00008678 // Insert a new store to null instruction before the load to indicate
8679 // that this code is not reachable. We do this instead of inserting
8680 // an unreachable instruction directly because we cannot modify the
8681 // CFG.
Owen Anderson9e9a0d52009-07-30 23:03:37 +00008682 new StoreInst(UndefValue::get(LI.getType()),
Owen Andersona7235ea2009-07-31 20:28:14 +00008683 Constant::getNullValue(Op->getType()), &LI);
Owen Anderson9e9a0d52009-07-30 23:03:37 +00008684 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Chris Lattner37366c12005-05-01 04:24:53 +00008685 }
Christopher Lambb15147e2007-12-29 07:56:53 +00008686 }
Chris Lattner37366c12005-05-01 04:24:53 +00008687
Chris Lattner878e4942009-10-22 06:25:11 +00008688 // load null/undef -> unreachable
8689 // TODO: Consider a target hook for valid address spaces for this xform.
8690 if (isa<UndefValue>(Op) ||
8691 (isa<ConstantPointerNull>(Op) && LI.getPointerAddressSpace() == 0)) {
8692 // Insert a new store to null instruction before the load to indicate that
8693 // this code is not reachable. We do this instead of inserting an
8694 // unreachable instruction directly because we cannot modify the CFG.
8695 new StoreInst(UndefValue::get(LI.getType()),
8696 Constant::getNullValue(Op->getType()), &LI);
8697 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00008698 }
Chris Lattner878e4942009-10-22 06:25:11 +00008699
8700 // Instcombine load (constantexpr_cast global) -> cast (load global)
8701 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op))
8702 if (CE->isCast())
8703 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
8704 return Res;
8705
Chris Lattner37366c12005-05-01 04:24:53 +00008706 if (Op->hasOneUse()) {
Chris Lattnerc10aced2004-09-19 18:43:46 +00008707 // Change select and PHI nodes to select values instead of addresses: this
8708 // helps alias analysis out a lot, allows many others simplifications, and
8709 // exposes redundancy in the code.
8710 //
8711 // Note that we cannot do the transformation unless we know that the
8712 // introduced loads cannot trap! Something like this is valid as long as
8713 // the condition is always false: load (select bool %C, int* null, int* %G),
8714 // but it would not be valid if we transformed it to load from null
8715 // unconditionally.
8716 //
8717 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
8718 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
Chris Lattner8a375202004-09-19 19:18:10 +00008719 if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
8720 isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008721 Value *V1 = Builder->CreateLoad(SI->getOperand(1),
8722 SI->getOperand(1)->getName()+".val");
8723 Value *V2 = Builder->CreateLoad(SI->getOperand(2),
8724 SI->getOperand(2)->getName()+".val");
Gabor Greif051a9502008-04-06 20:25:17 +00008725 return SelectInst::Create(SI->getCondition(), V1, V2);
Chris Lattnerc10aced2004-09-19 18:43:46 +00008726 }
8727
Chris Lattner684fe212004-09-23 15:46:00 +00008728 // load (select (cond, null, P)) -> load P
8729 if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
8730 if (C->isNullValue()) {
8731 LI.setOperand(0, SI->getOperand(2));
8732 return &LI;
8733 }
8734
8735 // load (select (cond, P, null)) -> load P
8736 if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
8737 if (C->isNullValue()) {
8738 LI.setOperand(0, SI->getOperand(1));
8739 return &LI;
8740 }
Chris Lattnerc10aced2004-09-19 18:43:46 +00008741 }
8742 }
Chris Lattner833b8a42003-06-26 05:06:25 +00008743 return 0;
8744}
8745
Reid Spencer55af2b52007-01-19 21:20:31 +00008746/// InstCombineStoreToCast - Fold store V, (cast P) -> store (cast V), P
Chris Lattner3914f722009-01-24 01:00:13 +00008747/// when possible. This makes it generally easy to do alias analysis and/or
8748/// SROA/mem2reg of the memory object.
Chris Lattnerfcfe33a2005-01-31 05:51:45 +00008749static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
8750 User *CI = cast<User>(SI.getOperand(1));
8751 Value *CastOp = CI->getOperand(0);
8752
8753 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
Chris Lattner1b8eaf52009-01-16 20:08:59 +00008754 const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType());
8755 if (SrcTy == 0) return 0;
8756
8757 const Type *SrcPTy = SrcTy->getElementType();
Chris Lattnerfcfe33a2005-01-31 05:51:45 +00008758
Chris Lattner1b8eaf52009-01-16 20:08:59 +00008759 if (!DestPTy->isInteger() && !isa<PointerType>(DestPTy))
8760 return 0;
8761
Chris Lattner3914f722009-01-24 01:00:13 +00008762 /// NewGEPIndices - If SrcPTy is an aggregate type, we can emit a "noop gep"
8763 /// to its first element. This allows us to handle things like:
8764 /// store i32 xxx, (bitcast {foo*, float}* %P to i32*)
8765 /// on 32-bit hosts.
8766 SmallVector<Value*, 4> NewGEPIndices;
8767
Chris Lattner1b8eaf52009-01-16 20:08:59 +00008768 // If the source is an array, the code below will not succeed. Check to
8769 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
8770 // constants.
Chris Lattner3914f722009-01-24 01:00:13 +00008771 if (isa<ArrayType>(SrcPTy) || isa<StructType>(SrcPTy)) {
8772 // Index through pointer.
Chris Lattner4de84762010-01-04 07:02:48 +00008773 Constant *Zero = Constant::getNullValue(Type::getInt32Ty(SI.getContext()));
Chris Lattner3914f722009-01-24 01:00:13 +00008774 NewGEPIndices.push_back(Zero);
8775
8776 while (1) {
8777 if (const StructType *STy = dyn_cast<StructType>(SrcPTy)) {
Torok Edwin08ffee52009-01-24 17:16:04 +00008778 if (!STy->getNumElements()) /* Struct can be empty {} */
Torok Edwin629e92b2009-01-24 11:30:49 +00008779 break;
Chris Lattner3914f722009-01-24 01:00:13 +00008780 NewGEPIndices.push_back(Zero);
8781 SrcPTy = STy->getElementType(0);
8782 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcPTy)) {
8783 NewGEPIndices.push_back(Zero);
8784 SrcPTy = ATy->getElementType();
8785 } else {
8786 break;
Chris Lattnerfcfe33a2005-01-31 05:51:45 +00008787 }
Chris Lattner3914f722009-01-24 01:00:13 +00008788 }
8789
Owen Andersondebcb012009-07-29 22:17:13 +00008790 SrcTy = PointerType::get(SrcPTy, SrcTy->getAddressSpace());
Chris Lattner3914f722009-01-24 01:00:13 +00008791 }
Chris Lattner1b8eaf52009-01-16 20:08:59 +00008792
8793 if (!SrcPTy->isInteger() && !isa<PointerType>(SrcPTy))
8794 return 0;
8795
Chris Lattner71759c42009-01-16 20:12:52 +00008796 // If the pointers point into different address spaces or if they point to
8797 // values with different sizes, we can't do the transformation.
Dan Gohmance9fe9f2009-07-21 23:21:54 +00008798 if (!IC.getTargetData() ||
8799 SrcTy->getAddressSpace() !=
Chris Lattner71759c42009-01-16 20:12:52 +00008800 cast<PointerType>(CI->getType())->getAddressSpace() ||
Dan Gohmance9fe9f2009-07-21 23:21:54 +00008801 IC.getTargetData()->getTypeSizeInBits(SrcPTy) !=
8802 IC.getTargetData()->getTypeSizeInBits(DestPTy))
Chris Lattner1b8eaf52009-01-16 20:08:59 +00008803 return 0;
8804
8805 // Okay, we are casting from one integer or pointer type to another of
8806 // the same size. Instead of casting the pointer before
8807 // the store, cast the value to be stored.
8808 Value *NewCast;
8809 Value *SIOp0 = SI.getOperand(0);
8810 Instruction::CastOps opcode = Instruction::BitCast;
8811 const Type* CastSrcTy = SIOp0->getType();
8812 const Type* CastDstTy = SrcPTy;
8813 if (isa<PointerType>(CastDstTy)) {
8814 if (CastSrcTy->isInteger())
8815 opcode = Instruction::IntToPtr;
8816 } else if (isa<IntegerType>(CastDstTy)) {
8817 if (isa<PointerType>(SIOp0->getType()))
8818 opcode = Instruction::PtrToInt;
Chris Lattnerfcfe33a2005-01-31 05:51:45 +00008819 }
Chris Lattner3914f722009-01-24 01:00:13 +00008820
8821 // SIOp0 is a pointer to aggregate and this is a store to the first field,
8822 // emit a GEP to index into its first field.
Dan Gohmanf8dbee72009-09-07 23:54:19 +00008823 if (!NewGEPIndices.empty())
8824 CastOp = IC.Builder->CreateInBoundsGEP(CastOp, NewGEPIndices.begin(),
8825 NewGEPIndices.end());
Chris Lattner3914f722009-01-24 01:00:13 +00008826
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008827 NewCast = IC.Builder->CreateCast(opcode, SIOp0, CastDstTy,
8828 SIOp0->getName()+".c");
Chris Lattner1b8eaf52009-01-16 20:08:59 +00008829 return new StoreInst(NewCast, CastOp);
Chris Lattnerfcfe33a2005-01-31 05:51:45 +00008830}
8831
Chris Lattner4aebaee2008-11-27 08:56:30 +00008832/// equivalentAddressValues - Test if A and B will obviously have the same
8833/// value. This includes recognizing that %t0 and %t1 will have the same
8834/// value in code like this:
Dan Gohman0f8b53f2009-03-03 02:55:14 +00008835/// %t0 = getelementptr \@a, 0, 3
Chris Lattner4aebaee2008-11-27 08:56:30 +00008836/// store i32 0, i32* %t0
Dan Gohman0f8b53f2009-03-03 02:55:14 +00008837/// %t1 = getelementptr \@a, 0, 3
Chris Lattner4aebaee2008-11-27 08:56:30 +00008838/// %t2 = load i32* %t1
8839///
8840static bool equivalentAddressValues(Value *A, Value *B) {
8841 // Test if the values are trivially equivalent.
8842 if (A == B) return true;
8843
8844 // Test if the values come form identical arithmetic instructions.
Dan Gohman58cfa3b2009-08-25 22:11:20 +00008845 // This uses isIdenticalToWhenDefined instead of isIdenticalTo because
8846 // its only used to compare two uses within the same basic block, which
8847 // means that they'll always either have the same value or one of them
8848 // will have an undefined value.
Chris Lattner4aebaee2008-11-27 08:56:30 +00008849 if (isa<BinaryOperator>(A) ||
8850 isa<CastInst>(A) ||
8851 isa<PHINode>(A) ||
8852 isa<GetElementPtrInst>(A))
8853 if (Instruction *BI = dyn_cast<Instruction>(B))
Dan Gohman58cfa3b2009-08-25 22:11:20 +00008854 if (cast<Instruction>(A)->isIdenticalToWhenDefined(BI))
Chris Lattner4aebaee2008-11-27 08:56:30 +00008855 return true;
8856
8857 // Otherwise they may not be equivalent.
8858 return false;
8859}
8860
Dale Johannesen4945c652009-03-03 21:26:39 +00008861// If this instruction has two uses, one of which is a llvm.dbg.declare,
8862// return the llvm.dbg.declare.
8863DbgDeclareInst *InstCombiner::hasOneUsePlusDeclare(Value *V) {
8864 if (!V->hasNUses(2))
8865 return 0;
8866 for (Value::use_iterator UI = V->use_begin(), E = V->use_end();
8867 UI != E; ++UI) {
8868 if (DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(UI))
8869 return DI;
8870 if (isa<BitCastInst>(UI) && UI->hasOneUse()) {
8871 if (DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(UI->use_begin()))
8872 return DI;
8873 }
8874 }
8875 return 0;
8876}
8877
Chris Lattner2f503e62005-01-31 05:36:43 +00008878Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
8879 Value *Val = SI.getOperand(0);
8880 Value *Ptr = SI.getOperand(1);
8881
Chris Lattner836692d2007-01-15 06:51:56 +00008882 // If the RHS is an alloca with a single use, zapify the store, making the
8883 // alloca dead.
Dale Johannesen4945c652009-03-03 21:26:39 +00008884 // If the RHS is an alloca with a two uses, the other one being a
8885 // llvm.dbg.declare, zapify the store and the declare, making the
8886 // alloca dead. We must do this to prevent declare's from affecting
8887 // codegen.
8888 if (!SI.isVolatile()) {
8889 if (Ptr->hasOneUse()) {
8890 if (isa<AllocaInst>(Ptr)) {
Chris Lattner836692d2007-01-15 06:51:56 +00008891 EraseInstFromFunction(SI);
8892 ++NumCombined;
8893 return 0;
8894 }
Dale Johannesen4945c652009-03-03 21:26:39 +00008895 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr)) {
8896 if (isa<AllocaInst>(GEP->getOperand(0))) {
8897 if (GEP->getOperand(0)->hasOneUse()) {
8898 EraseInstFromFunction(SI);
8899 ++NumCombined;
8900 return 0;
8901 }
8902 if (DbgDeclareInst *DI = hasOneUsePlusDeclare(GEP->getOperand(0))) {
8903 EraseInstFromFunction(*DI);
8904 EraseInstFromFunction(SI);
8905 ++NumCombined;
8906 return 0;
8907 }
8908 }
8909 }
8910 }
8911 if (DbgDeclareInst *DI = hasOneUsePlusDeclare(Ptr)) {
8912 EraseInstFromFunction(*DI);
8913 EraseInstFromFunction(SI);
8914 ++NumCombined;
8915 return 0;
8916 }
Chris Lattner836692d2007-01-15 06:51:56 +00008917 }
Chris Lattner2f503e62005-01-31 05:36:43 +00008918
Dan Gohman9941f742007-07-20 16:34:21 +00008919 // Attempt to improve the alignment.
Dan Gohmance9fe9f2009-07-21 23:21:54 +00008920 if (TD) {
8921 unsigned KnownAlign =
8922 GetOrEnforceKnownAlignment(Ptr, TD->getPrefTypeAlignment(Val->getType()));
8923 if (KnownAlign >
8924 (SI.getAlignment() == 0 ? TD->getABITypeAlignment(Val->getType()) :
8925 SI.getAlignment()))
8926 SI.setAlignment(KnownAlign);
8927 }
Dan Gohman9941f742007-07-20 16:34:21 +00008928
Dale Johannesenacb51a32009-03-03 01:43:03 +00008929 // Do really simple DSE, to catch cases where there are several consecutive
Chris Lattner9ca96412006-02-08 03:25:32 +00008930 // stores to the same location, separated by a few arithmetic operations. This
8931 // situation often occurs with bitfield accesses.
8932 BasicBlock::iterator BBI = &SI;
8933 for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
8934 --ScanInsts) {
Dale Johannesen0d6596b2009-03-04 01:20:34 +00008935 --BBI;
Dale Johannesencdb16aa2009-03-04 01:53:05 +00008936 // Don't count debug info directives, lest they affect codegen,
8937 // and we skip pointer-to-pointer bitcasts, which are NOPs.
8938 // It is necessary for correctness to skip those that feed into a
8939 // llvm.dbg.declare, as these are not present when debugging is off.
Dale Johannesen4ded40a2009-03-03 22:36:47 +00008940 if (isa<DbgInfoIntrinsic>(BBI) ||
Dale Johannesencdb16aa2009-03-04 01:53:05 +00008941 (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType()))) {
Dale Johannesenacb51a32009-03-03 01:43:03 +00008942 ScanInsts++;
Dale Johannesenacb51a32009-03-03 01:43:03 +00008943 continue;
8944 }
Chris Lattner9ca96412006-02-08 03:25:32 +00008945
8946 if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
8947 // Prev store isn't volatile, and stores to the same location?
Chris Lattner4aebaee2008-11-27 08:56:30 +00008948 if (!PrevSI->isVolatile() &&equivalentAddressValues(PrevSI->getOperand(1),
8949 SI.getOperand(1))) {
Chris Lattner9ca96412006-02-08 03:25:32 +00008950 ++NumDeadStore;
8951 ++BBI;
8952 EraseInstFromFunction(*PrevSI);
8953 continue;
8954 }
8955 break;
8956 }
8957
Chris Lattnerb4db97f2006-05-26 19:19:20 +00008958 // If this is a load, we have to stop. However, if the loaded value is from
8959 // the pointer we're loading and is producing the pointer we're storing,
8960 // then *this* store is dead (X = load P; store X -> P).
8961 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
Dan Gohman2276a7b2008-10-15 23:19:35 +00008962 if (LI == Val && equivalentAddressValues(LI->getOperand(0), Ptr) &&
8963 !SI.isVolatile()) {
Chris Lattnerb4db97f2006-05-26 19:19:20 +00008964 EraseInstFromFunction(SI);
8965 ++NumCombined;
8966 return 0;
8967 }
8968 // Otherwise, this is a load from some other location. Stores before it
8969 // may not be dead.
8970 break;
8971 }
8972
Chris Lattner9ca96412006-02-08 03:25:32 +00008973 // Don't skip over loads or things that can modify memory.
Chris Lattner0ef546e2008-05-08 17:20:30 +00008974 if (BBI->mayWriteToMemory() || BBI->mayReadFromMemory())
Chris Lattner9ca96412006-02-08 03:25:32 +00008975 break;
8976 }
8977
8978
8979 if (SI.isVolatile()) return 0; // Don't hack volatile stores.
Chris Lattner2f503e62005-01-31 05:36:43 +00008980
8981 // store X, null -> turns into 'unreachable' in SimplifyCFG
Chris Lattner8a67ac52009-08-30 20:06:40 +00008982 if (isa<ConstantPointerNull>(Ptr) && SI.getPointerAddressSpace() == 0) {
Chris Lattner2f503e62005-01-31 05:36:43 +00008983 if (!isa<UndefValue>(Val)) {
Owen Anderson9e9a0d52009-07-30 23:03:37 +00008984 SI.setOperand(0, UndefValue::get(Val->getType()));
Chris Lattner2f503e62005-01-31 05:36:43 +00008985 if (Instruction *U = dyn_cast<Instruction>(Val))
Chris Lattner7a1e9242009-08-30 06:13:40 +00008986 Worklist.Add(U); // Dropped a use.
Chris Lattner2f503e62005-01-31 05:36:43 +00008987 ++NumCombined;
8988 }
8989 return 0; // Do not modify these!
8990 }
8991
8992 // store undef, Ptr -> noop
8993 if (isa<UndefValue>(Val)) {
Chris Lattner9ca96412006-02-08 03:25:32 +00008994 EraseInstFromFunction(SI);
Chris Lattner2f503e62005-01-31 05:36:43 +00008995 ++NumCombined;
8996 return 0;
8997 }
8998
Chris Lattnerfcfe33a2005-01-31 05:51:45 +00008999 // If the pointer destination is a cast, see if we can fold the cast into the
9000 // source instead.
Reid Spencer3ed469c2006-11-02 20:25:50 +00009001 if (isa<CastInst>(Ptr))
Chris Lattnerfcfe33a2005-01-31 05:51:45 +00009002 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
9003 return Res;
9004 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
Reid Spencer3da59db2006-11-27 01:05:10 +00009005 if (CE->isCast())
Chris Lattnerfcfe33a2005-01-31 05:51:45 +00009006 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
9007 return Res;
9008
Chris Lattner408902b2005-09-12 23:23:25 +00009009
Dale Johannesen4084c4e2009-03-05 02:06:48 +00009010 // If this store is the last instruction in the basic block (possibly
9011 // excepting debug info instructions and the pointer bitcasts that feed
9012 // into them), and if the block ends with an unconditional branch, try
9013 // to move it to the successor block.
9014 BBI = &SI;
9015 do {
9016 ++BBI;
9017 } while (isa<DbgInfoIntrinsic>(BBI) ||
9018 (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType())));
Chris Lattner408902b2005-09-12 23:23:25 +00009019 if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
Chris Lattner3284d1f2007-04-15 00:07:55 +00009020 if (BI->isUnconditional())
9021 if (SimplifyStoreAtEndOfBlock(SI))
9022 return 0; // xform done!
Chris Lattner408902b2005-09-12 23:23:25 +00009023
Chris Lattner2f503e62005-01-31 05:36:43 +00009024 return 0;
9025}
9026
Chris Lattner3284d1f2007-04-15 00:07:55 +00009027/// SimplifyStoreAtEndOfBlock - Turn things like:
9028/// if () { *P = v1; } else { *P = v2 }
9029/// into a phi node with a store in the successor.
9030///
Chris Lattner31755a02007-04-15 01:02:18 +00009031/// Simplify things like:
9032/// *P = v1; if () { *P = v2; }
9033/// into a phi node with a store in the successor.
9034///
Chris Lattner3284d1f2007-04-15 00:07:55 +00009035bool InstCombiner::SimplifyStoreAtEndOfBlock(StoreInst &SI) {
9036 BasicBlock *StoreBB = SI.getParent();
9037
9038 // Check to see if the successor block has exactly two incoming edges. If
9039 // so, see if the other predecessor contains a store to the same location.
9040 // if so, insert a PHI node (if needed) and move the stores down.
Chris Lattner31755a02007-04-15 01:02:18 +00009041 BasicBlock *DestBB = StoreBB->getTerminator()->getSuccessor(0);
Chris Lattner3284d1f2007-04-15 00:07:55 +00009042
9043 // Determine whether Dest has exactly two predecessors and, if so, compute
9044 // the other predecessor.
Chris Lattner31755a02007-04-15 01:02:18 +00009045 pred_iterator PI = pred_begin(DestBB);
9046 BasicBlock *OtherBB = 0;
Chris Lattner3284d1f2007-04-15 00:07:55 +00009047 if (*PI != StoreBB)
Chris Lattner31755a02007-04-15 01:02:18 +00009048 OtherBB = *PI;
Chris Lattner3284d1f2007-04-15 00:07:55 +00009049 ++PI;
Chris Lattner31755a02007-04-15 01:02:18 +00009050 if (PI == pred_end(DestBB))
Chris Lattner3284d1f2007-04-15 00:07:55 +00009051 return false;
9052
9053 if (*PI != StoreBB) {
Chris Lattner31755a02007-04-15 01:02:18 +00009054 if (OtherBB)
Chris Lattner3284d1f2007-04-15 00:07:55 +00009055 return false;
Chris Lattner31755a02007-04-15 01:02:18 +00009056 OtherBB = *PI;
Chris Lattner3284d1f2007-04-15 00:07:55 +00009057 }
Chris Lattner31755a02007-04-15 01:02:18 +00009058 if (++PI != pred_end(DestBB))
Chris Lattner3284d1f2007-04-15 00:07:55 +00009059 return false;
Eli Friedman66fe80a2008-06-13 21:17:49 +00009060
9061 // Bail out if all the relevant blocks aren't distinct (this can happen,
9062 // for example, if SI is in an infinite loop)
9063 if (StoreBB == DestBB || OtherBB == DestBB)
9064 return false;
9065
Chris Lattner31755a02007-04-15 01:02:18 +00009066 // Verify that the other block ends in a branch and is not otherwise empty.
9067 BasicBlock::iterator BBI = OtherBB->getTerminator();
Chris Lattner3284d1f2007-04-15 00:07:55 +00009068 BranchInst *OtherBr = dyn_cast<BranchInst>(BBI);
Chris Lattner31755a02007-04-15 01:02:18 +00009069 if (!OtherBr || BBI == OtherBB->begin())
Chris Lattner3284d1f2007-04-15 00:07:55 +00009070 return false;
9071
Chris Lattner31755a02007-04-15 01:02:18 +00009072 // If the other block ends in an unconditional branch, check for the 'if then
9073 // else' case. there is an instruction before the branch.
9074 StoreInst *OtherStore = 0;
9075 if (OtherBr->isUnconditional()) {
Chris Lattner31755a02007-04-15 01:02:18 +00009076 --BBI;
Dale Johannesen4084c4e2009-03-05 02:06:48 +00009077 // Skip over debugging info.
9078 while (isa<DbgInfoIntrinsic>(BBI) ||
9079 (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType()))) {
9080 if (BBI==OtherBB->begin())
9081 return false;
9082 --BBI;
9083 }
Chris Lattner7ebbabf2009-11-02 02:06:37 +00009084 // If this isn't a store, isn't a store to the same location, or if the
9085 // alignments differ, bail out.
Chris Lattner31755a02007-04-15 01:02:18 +00009086 OtherStore = dyn_cast<StoreInst>(BBI);
Chris Lattner7ebbabf2009-11-02 02:06:37 +00009087 if (!OtherStore || OtherStore->getOperand(1) != SI.getOperand(1) ||
9088 OtherStore->getAlignment() != SI.getAlignment())
Chris Lattner31755a02007-04-15 01:02:18 +00009089 return false;
9090 } else {
Chris Lattnerd717c182007-05-05 22:32:24 +00009091 // Otherwise, the other block ended with a conditional branch. If one of the
Chris Lattner31755a02007-04-15 01:02:18 +00009092 // destinations is StoreBB, then we have the if/then case.
9093 if (OtherBr->getSuccessor(0) != StoreBB &&
9094 OtherBr->getSuccessor(1) != StoreBB)
9095 return false;
9096
9097 // Okay, we know that OtherBr now goes to Dest and StoreBB, so this is an
Chris Lattnerd717c182007-05-05 22:32:24 +00009098 // if/then triangle. See if there is a store to the same ptr as SI that
9099 // lives in OtherBB.
Chris Lattner31755a02007-04-15 01:02:18 +00009100 for (;; --BBI) {
9101 // Check to see if we find the matching store.
9102 if ((OtherStore = dyn_cast<StoreInst>(BBI))) {
Chris Lattner7ebbabf2009-11-02 02:06:37 +00009103 if (OtherStore->getOperand(1) != SI.getOperand(1) ||
9104 OtherStore->getAlignment() != SI.getAlignment())
Chris Lattner31755a02007-04-15 01:02:18 +00009105 return false;
9106 break;
9107 }
Eli Friedman6903a242008-06-13 22:02:12 +00009108 // If we find something that may be using or overwriting the stored
9109 // value, or if we run out of instructions, we can't do the xform.
9110 if (BBI->mayReadFromMemory() || BBI->mayWriteToMemory() ||
Chris Lattner31755a02007-04-15 01:02:18 +00009111 BBI == OtherBB->begin())
9112 return false;
9113 }
9114
9115 // In order to eliminate the store in OtherBr, we have to
Eli Friedman6903a242008-06-13 22:02:12 +00009116 // make sure nothing reads or overwrites the stored value in
9117 // StoreBB.
Chris Lattner31755a02007-04-15 01:02:18 +00009118 for (BasicBlock::iterator I = StoreBB->begin(); &*I != &SI; ++I) {
9119 // FIXME: This should really be AA driven.
Eli Friedman6903a242008-06-13 22:02:12 +00009120 if (I->mayReadFromMemory() || I->mayWriteToMemory())
Chris Lattner31755a02007-04-15 01:02:18 +00009121 return false;
9122 }
9123 }
Chris Lattner3284d1f2007-04-15 00:07:55 +00009124
Chris Lattner31755a02007-04-15 01:02:18 +00009125 // Insert a PHI node now if we need it.
Chris Lattner3284d1f2007-04-15 00:07:55 +00009126 Value *MergedVal = OtherStore->getOperand(0);
9127 if (MergedVal != SI.getOperand(0)) {
Gabor Greif051a9502008-04-06 20:25:17 +00009128 PHINode *PN = PHINode::Create(MergedVal->getType(), "storemerge");
Chris Lattner3284d1f2007-04-15 00:07:55 +00009129 PN->reserveOperandSpace(2);
9130 PN->addIncoming(SI.getOperand(0), SI.getParent());
Chris Lattner31755a02007-04-15 01:02:18 +00009131 PN->addIncoming(OtherStore->getOperand(0), OtherBB);
9132 MergedVal = InsertNewInstBefore(PN, DestBB->front());
Chris Lattner3284d1f2007-04-15 00:07:55 +00009133 }
9134
9135 // Advance to a place where it is safe to insert the new store and
9136 // insert it.
Dan Gohman02dea8b2008-05-23 21:05:58 +00009137 BBI = DestBB->getFirstNonPHI();
Chris Lattner3284d1f2007-04-15 00:07:55 +00009138 InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
Chris Lattner7ebbabf2009-11-02 02:06:37 +00009139 OtherStore->isVolatile(),
9140 SI.getAlignment()), *BBI);
Chris Lattner3284d1f2007-04-15 00:07:55 +00009141
9142 // Nuke the old stores.
9143 EraseInstFromFunction(SI);
9144 EraseInstFromFunction(*OtherStore);
9145 ++NumCombined;
9146 return true;
9147}
9148
Chris Lattner2f503e62005-01-31 05:36:43 +00009149
Chris Lattnerc4d10eb2003-06-04 04:46:00 +00009150Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
9151 // Change br (not X), label True, label False to: br X, label False, True
Reid Spencer4b828e62005-06-18 17:37:34 +00009152 Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +00009153 BasicBlock *TrueDest;
9154 BasicBlock *FalseDest;
Dan Gohman4ae51262009-08-12 16:23:25 +00009155 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
Chris Lattneracd1f0f2004-07-30 07:50:03 +00009156 !isa<Constant>(X)) {
9157 // Swap Destinations and condition...
9158 BI.setCondition(X);
9159 BI.setSuccessor(0, FalseDest);
9160 BI.setSuccessor(1, TrueDest);
9161 return &BI;
9162 }
9163
Reid Spencere4d87aa2006-12-23 06:05:41 +00009164 // Cannonicalize fcmp_one -> fcmp_oeq
9165 FCmpInst::Predicate FPred; Value *Y;
9166 if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)),
Chris Lattner7a1e9242009-08-30 06:13:40 +00009167 TrueDest, FalseDest)) &&
9168 BI.getCondition()->hasOneUse())
9169 if (FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
9170 FPred == FCmpInst::FCMP_OGE) {
9171 FCmpInst *Cond = cast<FCmpInst>(BI.getCondition());
9172 Cond->setPredicate(FCmpInst::getInversePredicate(FPred));
9173
9174 // Swap Destinations and condition.
Reid Spencere4d87aa2006-12-23 06:05:41 +00009175 BI.setSuccessor(0, FalseDest);
9176 BI.setSuccessor(1, TrueDest);
Chris Lattner7a1e9242009-08-30 06:13:40 +00009177 Worklist.Add(Cond);
Reid Spencere4d87aa2006-12-23 06:05:41 +00009178 return &BI;
9179 }
9180
9181 // Cannonicalize icmp_ne -> icmp_eq
9182 ICmpInst::Predicate IPred;
9183 if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
Chris Lattner7a1e9242009-08-30 06:13:40 +00009184 TrueDest, FalseDest)) &&
9185 BI.getCondition()->hasOneUse())
9186 if (IPred == ICmpInst::ICMP_NE || IPred == ICmpInst::ICMP_ULE ||
9187 IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
9188 IPred == ICmpInst::ICMP_SGE) {
9189 ICmpInst *Cond = cast<ICmpInst>(BI.getCondition());
9190 Cond->setPredicate(ICmpInst::getInversePredicate(IPred));
9191 // Swap Destinations and condition.
Chris Lattner40f5d702003-06-04 05:10:11 +00009192 BI.setSuccessor(0, FalseDest);
9193 BI.setSuccessor(1, TrueDest);
Chris Lattner7a1e9242009-08-30 06:13:40 +00009194 Worklist.Add(Cond);
Chris Lattner40f5d702003-06-04 05:10:11 +00009195 return &BI;
9196 }
Misha Brukmanfd939082005-04-21 23:48:37 +00009197
Chris Lattnerc4d10eb2003-06-04 04:46:00 +00009198 return 0;
9199}
Chris Lattner0864acf2002-11-04 16:18:53 +00009200
Chris Lattner46238a62004-07-03 00:26:11 +00009201Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
9202 Value *Cond = SI.getCondition();
9203 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
9204 if (I->getOpcode() == Instruction::Add)
9205 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
9206 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
9207 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
Owen Andersond672ecb2009-07-03 00:17:18 +00009208 SI.setOperand(i,
Owen Andersonbaf3c402009-07-29 18:55:55 +00009209 ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
Chris Lattner46238a62004-07-03 00:26:11 +00009210 AddRHS));
9211 SI.setOperand(0, I->getOperand(0));
Chris Lattner7a1e9242009-08-30 06:13:40 +00009212 Worklist.Add(I);
Chris Lattner46238a62004-07-03 00:26:11 +00009213 return &SI;
9214 }
9215 }
9216 return 0;
9217}
9218
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +00009219Instruction *InstCombiner::visitExtractValueInst(ExtractValueInst &EV) {
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +00009220 Value *Agg = EV.getAggregateOperand();
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +00009221
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +00009222 if (!EV.hasIndices())
9223 return ReplaceInstUsesWith(EV, Agg);
9224
9225 if (Constant *C = dyn_cast<Constant>(Agg)) {
9226 if (isa<UndefValue>(C))
Owen Anderson9e9a0d52009-07-30 23:03:37 +00009227 return ReplaceInstUsesWith(EV, UndefValue::get(EV.getType()));
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +00009228
9229 if (isa<ConstantAggregateZero>(C))
Owen Andersona7235ea2009-07-31 20:28:14 +00009230 return ReplaceInstUsesWith(EV, Constant::getNullValue(EV.getType()));
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +00009231
9232 if (isa<ConstantArray>(C) || isa<ConstantStruct>(C)) {
9233 // Extract the element indexed by the first index out of the constant
9234 Value *V = C->getOperand(*EV.idx_begin());
9235 if (EV.getNumIndices() > 1)
9236 // Extract the remaining indices out of the constant indexed by the
9237 // first index
9238 return ExtractValueInst::Create(V, EV.idx_begin() + 1, EV.idx_end());
9239 else
9240 return ReplaceInstUsesWith(EV, V);
9241 }
9242 return 0; // Can't handle other constants
9243 }
9244 if (InsertValueInst *IV = dyn_cast<InsertValueInst>(Agg)) {
9245 // We're extracting from an insertvalue instruction, compare the indices
9246 const unsigned *exti, *exte, *insi, *inse;
9247 for (exti = EV.idx_begin(), insi = IV->idx_begin(),
9248 exte = EV.idx_end(), inse = IV->idx_end();
9249 exti != exte && insi != inse;
9250 ++exti, ++insi) {
9251 if (*insi != *exti)
9252 // The insert and extract both reference distinctly different elements.
9253 // This means the extract is not influenced by the insert, and we can
9254 // replace the aggregate operand of the extract with the aggregate
9255 // operand of the insert. i.e., replace
9256 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
9257 // %E = extractvalue { i32, { i32 } } %I, 0
9258 // with
9259 // %E = extractvalue { i32, { i32 } } %A, 0
9260 return ExtractValueInst::Create(IV->getAggregateOperand(),
9261 EV.idx_begin(), EV.idx_end());
9262 }
9263 if (exti == exte && insi == inse)
9264 // Both iterators are at the end: Index lists are identical. Replace
9265 // %B = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
9266 // %C = extractvalue { i32, { i32 } } %B, 1, 0
9267 // with "i32 42"
9268 return ReplaceInstUsesWith(EV, IV->getInsertedValueOperand());
9269 if (exti == exte) {
9270 // The extract list is a prefix of the insert list. i.e. replace
9271 // %I = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
9272 // %E = extractvalue { i32, { i32 } } %I, 1
9273 // with
9274 // %X = extractvalue { i32, { i32 } } %A, 1
9275 // %E = insertvalue { i32 } %X, i32 42, 0
9276 // by switching the order of the insert and extract (though the
9277 // insertvalue should be left in, since it may have other uses).
Chris Lattnerf925cbd2009-08-30 18:50:58 +00009278 Value *NewEV = Builder->CreateExtractValue(IV->getAggregateOperand(),
9279 EV.idx_begin(), EV.idx_end());
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +00009280 return InsertValueInst::Create(NewEV, IV->getInsertedValueOperand(),
9281 insi, inse);
9282 }
9283 if (insi == inse)
9284 // The insert list is a prefix of the extract list
9285 // We can simply remove the common indices from the extract and make it
9286 // operate on the inserted value instead of the insertvalue result.
9287 // i.e., replace
9288 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
9289 // %E = extractvalue { i32, { i32 } } %I, 1, 0
9290 // with
9291 // %E extractvalue { i32 } { i32 42 }, 0
9292 return ExtractValueInst::Create(IV->getInsertedValueOperand(),
9293 exti, exte);
9294 }
Chris Lattner7e606e22009-11-09 07:07:56 +00009295 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Agg)) {
9296 // We're extracting from an intrinsic, see if we're the only user, which
9297 // allows us to simplify multiple result intrinsics to simpler things that
9298 // just get one value..
9299 if (II->hasOneUse()) {
9300 // Check if we're grabbing the overflow bit or the result of a 'with
9301 // overflow' intrinsic. If it's the latter we can remove the intrinsic
9302 // and replace it with a traditional binary instruction.
9303 switch (II->getIntrinsicID()) {
9304 case Intrinsic::uadd_with_overflow:
9305 case Intrinsic::sadd_with_overflow:
9306 if (*EV.idx_begin() == 0) { // Normal result.
9307 Value *LHS = II->getOperand(1), *RHS = II->getOperand(2);
9308 II->replaceAllUsesWith(UndefValue::get(II->getType()));
9309 EraseInstFromFunction(*II);
9310 return BinaryOperator::CreateAdd(LHS, RHS);
9311 }
9312 break;
9313 case Intrinsic::usub_with_overflow:
9314 case Intrinsic::ssub_with_overflow:
9315 if (*EV.idx_begin() == 0) { // Normal result.
9316 Value *LHS = II->getOperand(1), *RHS = II->getOperand(2);
9317 II->replaceAllUsesWith(UndefValue::get(II->getType()));
9318 EraseInstFromFunction(*II);
9319 return BinaryOperator::CreateSub(LHS, RHS);
9320 }
9321 break;
9322 case Intrinsic::umul_with_overflow:
9323 case Intrinsic::smul_with_overflow:
9324 if (*EV.idx_begin() == 0) { // Normal result.
9325 Value *LHS = II->getOperand(1), *RHS = II->getOperand(2);
9326 II->replaceAllUsesWith(UndefValue::get(II->getType()));
9327 EraseInstFromFunction(*II);
9328 return BinaryOperator::CreateMul(LHS, RHS);
9329 }
9330 break;
9331 default:
9332 break;
9333 }
9334 }
9335 }
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +00009336 // Can't simplify extracts from other values. Note that nested extracts are
9337 // already simplified implicitely by the above (extract ( extract (insert) )
9338 // will be translated into extract ( insert ( extract ) ) first and then just
9339 // the value inserted, if appropriate).
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +00009340 return 0;
9341}
9342
Chris Lattner220b0cf2006-03-05 00:22:33 +00009343/// CheapToScalarize - Return true if the value is cheaper to scalarize than it
9344/// is to leave as a vector operation.
9345static bool CheapToScalarize(Value *V, bool isConstant) {
9346 if (isa<ConstantAggregateZero>(V))
9347 return true;
Reid Spencer9d6565a2007-02-15 02:26:10 +00009348 if (ConstantVector *C = dyn_cast<ConstantVector>(V)) {
Chris Lattner220b0cf2006-03-05 00:22:33 +00009349 if (isConstant) return true;
9350 // If all elts are the same, we can extract.
9351 Constant *Op0 = C->getOperand(0);
9352 for (unsigned i = 1; i < C->getNumOperands(); ++i)
9353 if (C->getOperand(i) != Op0)
9354 return false;
9355 return true;
9356 }
9357 Instruction *I = dyn_cast<Instruction>(V);
9358 if (!I) return false;
9359
9360 // Insert element gets simplified to the inserted element or is deleted if
9361 // this is constant idx extract element and its a constant idx insertelt.
9362 if (I->getOpcode() == Instruction::InsertElement && isConstant &&
9363 isa<ConstantInt>(I->getOperand(2)))
9364 return true;
9365 if (I->getOpcode() == Instruction::Load && I->hasOneUse())
9366 return true;
9367 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
9368 if (BO->hasOneUse() &&
9369 (CheapToScalarize(BO->getOperand(0), isConstant) ||
9370 CheapToScalarize(BO->getOperand(1), isConstant)))
9371 return true;
Reid Spencere4d87aa2006-12-23 06:05:41 +00009372 if (CmpInst *CI = dyn_cast<CmpInst>(I))
9373 if (CI->hasOneUse() &&
9374 (CheapToScalarize(CI->getOperand(0), isConstant) ||
9375 CheapToScalarize(CI->getOperand(1), isConstant)))
9376 return true;
Chris Lattner220b0cf2006-03-05 00:22:33 +00009377
9378 return false;
9379}
9380
Chris Lattnerd2b7cec2007-02-14 05:52:17 +00009381/// Read and decode a shufflevector mask.
9382///
9383/// It turns undef elements into values that are larger than the number of
9384/// elements in the input.
Chris Lattner863bcff2006-05-25 23:48:38 +00009385static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
9386 unsigned NElts = SVI->getType()->getNumElements();
9387 if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
9388 return std::vector<unsigned>(NElts, 0);
9389 if (isa<UndefValue>(SVI->getOperand(2)))
9390 return std::vector<unsigned>(NElts, 2*NElts);
9391
9392 std::vector<unsigned> Result;
Reid Spencer9d6565a2007-02-15 02:26:10 +00009393 const ConstantVector *CP = cast<ConstantVector>(SVI->getOperand(2));
Gabor Greif177dd3f2008-06-12 21:37:33 +00009394 for (User::const_op_iterator i = CP->op_begin(), e = CP->op_end(); i!=e; ++i)
9395 if (isa<UndefValue>(*i))
Chris Lattner863bcff2006-05-25 23:48:38 +00009396 Result.push_back(NElts*2); // undef -> 8
9397 else
Gabor Greif177dd3f2008-06-12 21:37:33 +00009398 Result.push_back(cast<ConstantInt>(*i)->getZExtValue());
Chris Lattner863bcff2006-05-25 23:48:38 +00009399 return Result;
9400}
9401
Chris Lattner6e6b0da2006-03-31 23:01:56 +00009402/// FindScalarElement - Given a vector and an element number, see if the scalar
9403/// value is already around as a register, for example if it were inserted then
9404/// extracted from the vector.
Chris Lattner4de84762010-01-04 07:02:48 +00009405static Value *FindScalarElement(Value *V, unsigned EltNo) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00009406 assert(isa<VectorType>(V->getType()) && "Not looking at a vector?");
9407 const VectorType *PTy = cast<VectorType>(V->getType());
Chris Lattner389a6f52006-04-10 23:06:36 +00009408 unsigned Width = PTy->getNumElements();
9409 if (EltNo >= Width) // Out of range access.
Owen Anderson9e9a0d52009-07-30 23:03:37 +00009410 return UndefValue::get(PTy->getElementType());
Chris Lattner6e6b0da2006-03-31 23:01:56 +00009411
9412 if (isa<UndefValue>(V))
Owen Anderson9e9a0d52009-07-30 23:03:37 +00009413 return UndefValue::get(PTy->getElementType());
Chris Lattner6e6b0da2006-03-31 23:01:56 +00009414 else if (isa<ConstantAggregateZero>(V))
Owen Andersona7235ea2009-07-31 20:28:14 +00009415 return Constant::getNullValue(PTy->getElementType());
Reid Spencer9d6565a2007-02-15 02:26:10 +00009416 else if (ConstantVector *CP = dyn_cast<ConstantVector>(V))
Chris Lattner6e6b0da2006-03-31 23:01:56 +00009417 return CP->getOperand(EltNo);
9418 else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
9419 // If this is an insert to a variable element, we don't know what it is.
Reid Spencerb83eb642006-10-20 07:07:24 +00009420 if (!isa<ConstantInt>(III->getOperand(2)))
9421 return 0;
9422 unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
Chris Lattner6e6b0da2006-03-31 23:01:56 +00009423
9424 // If this is an insert to the element we are looking for, return the
9425 // inserted value.
Reid Spencerb83eb642006-10-20 07:07:24 +00009426 if (EltNo == IIElt)
9427 return III->getOperand(1);
Chris Lattner6e6b0da2006-03-31 23:01:56 +00009428
9429 // Otherwise, the insertelement doesn't modify the value, recurse on its
9430 // vector input.
Chris Lattner4de84762010-01-04 07:02:48 +00009431 return FindScalarElement(III->getOperand(0), EltNo);
Chris Lattner389a6f52006-04-10 23:06:36 +00009432 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
Mon P Wangaeb06d22008-11-10 04:46:22 +00009433 unsigned LHSWidth =
9434 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
Chris Lattner863bcff2006-05-25 23:48:38 +00009435 unsigned InEl = getShuffleMask(SVI)[EltNo];
Mon P Wangaeb06d22008-11-10 04:46:22 +00009436 if (InEl < LHSWidth)
Chris Lattner4de84762010-01-04 07:02:48 +00009437 return FindScalarElement(SVI->getOperand(0), InEl);
Mon P Wangaeb06d22008-11-10 04:46:22 +00009438 else if (InEl < LHSWidth*2)
Chris Lattner4de84762010-01-04 07:02:48 +00009439 return FindScalarElement(SVI->getOperand(1), InEl - LHSWidth);
Chris Lattner863bcff2006-05-25 23:48:38 +00009440 else
Owen Anderson9e9a0d52009-07-30 23:03:37 +00009441 return UndefValue::get(PTy->getElementType());
Chris Lattner6e6b0da2006-03-31 23:01:56 +00009442 }
9443
9444 // Otherwise, we don't know.
9445 return 0;
9446}
9447
Robert Bocchino1d7456d2006-01-13 22:48:06 +00009448Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
Dan Gohman07a96762007-07-16 14:29:03 +00009449 // If vector val is undef, replace extract with scalar undef.
Chris Lattner1f13c882006-03-31 18:25:14 +00009450 if (isa<UndefValue>(EI.getOperand(0)))
Owen Anderson9e9a0d52009-07-30 23:03:37 +00009451 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
Chris Lattner1f13c882006-03-31 18:25:14 +00009452
Dan Gohman07a96762007-07-16 14:29:03 +00009453 // If vector val is constant 0, replace extract with scalar 0.
Chris Lattner1f13c882006-03-31 18:25:14 +00009454 if (isa<ConstantAggregateZero>(EI.getOperand(0)))
Owen Andersona7235ea2009-07-31 20:28:14 +00009455 return ReplaceInstUsesWith(EI, Constant::getNullValue(EI.getType()));
Chris Lattner1f13c882006-03-31 18:25:14 +00009456
Reid Spencer9d6565a2007-02-15 02:26:10 +00009457 if (ConstantVector *C = dyn_cast<ConstantVector>(EI.getOperand(0))) {
Matthijs Kooijmanb4d6a5a2008-06-11 09:00:12 +00009458 // If vector val is constant with all elements the same, replace EI with
9459 // that element. When the elements are not identical, we cannot replace yet
9460 // (we do that below, but only when the index is constant).
Chris Lattner220b0cf2006-03-05 00:22:33 +00009461 Constant *op0 = C->getOperand(0);
Chris Lattner4cb81bd2009-09-08 03:44:51 +00009462 for (unsigned i = 1; i != C->getNumOperands(); ++i)
Chris Lattner220b0cf2006-03-05 00:22:33 +00009463 if (C->getOperand(i) != op0) {
9464 op0 = 0;
9465 break;
9466 }
9467 if (op0)
9468 return ReplaceInstUsesWith(EI, op0);
Robert Bocchino1d7456d2006-01-13 22:48:06 +00009469 }
Eli Friedman76e7ba82009-07-18 19:04:16 +00009470
Chris Lattner6e6b0da2006-03-31 23:01:56 +00009471 // If extracting a specified index from the vector, see if we can recursively
9472 // find a previously computed scalar that was inserted into the vector.
Reid Spencerb83eb642006-10-20 07:07:24 +00009473 if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
Chris Lattner85464092007-04-09 01:37:55 +00009474 unsigned IndexVal = IdxC->getZExtValue();
Chris Lattner4cb81bd2009-09-08 03:44:51 +00009475 unsigned VectorWidth = EI.getVectorOperandType()->getNumElements();
Chris Lattner85464092007-04-09 01:37:55 +00009476
9477 // If this is extracting an invalid index, turn this into undef, to avoid
9478 // crashing the code below.
9479 if (IndexVal >= VectorWidth)
Owen Anderson9e9a0d52009-07-30 23:03:37 +00009480 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
Chris Lattner85464092007-04-09 01:37:55 +00009481
Chris Lattner867b99f2006-10-05 06:55:50 +00009482 // This instruction only demands the single element from the input vector.
9483 // If the input vector has a single use, simplify it based on this use
9484 // property.
Eli Friedman76e7ba82009-07-18 19:04:16 +00009485 if (EI.getOperand(0)->hasOneUse() && VectorWidth != 1) {
Evan Cheng388df622009-02-03 10:05:09 +00009486 APInt UndefElts(VectorWidth, 0);
9487 APInt DemandedMask(VectorWidth, 1 << IndexVal);
Chris Lattner867b99f2006-10-05 06:55:50 +00009488 if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
Evan Cheng388df622009-02-03 10:05:09 +00009489 DemandedMask, UndefElts)) {
Chris Lattner867b99f2006-10-05 06:55:50 +00009490 EI.setOperand(0, V);
9491 return &EI;
9492 }
9493 }
9494
Chris Lattner4de84762010-01-04 07:02:48 +00009495 if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal))
Chris Lattner6e6b0da2006-03-31 23:01:56 +00009496 return ReplaceInstUsesWith(EI, Elt);
Chris Lattnerb7300fa2007-04-14 23:02:14 +00009497
9498 // If the this extractelement is directly using a bitcast from a vector of
9499 // the same number of elements, see if we can find the source element from
9500 // it. In this case, we will end up needing to bitcast the scalars.
9501 if (BitCastInst *BCI = dyn_cast<BitCastInst>(EI.getOperand(0))) {
9502 if (const VectorType *VT =
9503 dyn_cast<VectorType>(BCI->getOperand(0)->getType()))
9504 if (VT->getNumElements() == VectorWidth)
Chris Lattner4de84762010-01-04 07:02:48 +00009505 if (Value *Elt = FindScalarElement(BCI->getOperand(0), IndexVal))
Chris Lattnerb7300fa2007-04-14 23:02:14 +00009506 return new BitCastInst(Elt, EI.getType());
9507 }
Chris Lattner389a6f52006-04-10 23:06:36 +00009508 }
Chris Lattner6e6b0da2006-03-31 23:01:56 +00009509
Chris Lattner73fa49d2006-05-25 22:53:38 +00009510 if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
Chris Lattner275a6d62009-09-08 18:48:01 +00009511 // Push extractelement into predecessor operation if legal and
9512 // profitable to do so
9513 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
9514 if (I->hasOneUse() &&
9515 CheapToScalarize(BO, isa<ConstantInt>(EI.getOperand(1)))) {
9516 Value *newEI0 =
9517 Builder->CreateExtractElement(BO->getOperand(0), EI.getOperand(1),
9518 EI.getName()+".lhs");
9519 Value *newEI1 =
9520 Builder->CreateExtractElement(BO->getOperand(1), EI.getOperand(1),
9521 EI.getName()+".rhs");
9522 return BinaryOperator::Create(BO->getOpcode(), newEI0, newEI1);
Chris Lattner73fa49d2006-05-25 22:53:38 +00009523 }
Chris Lattner275a6d62009-09-08 18:48:01 +00009524 } else if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
Chris Lattner73fa49d2006-05-25 22:53:38 +00009525 // Extracting the inserted element?
9526 if (IE->getOperand(2) == EI.getOperand(1))
9527 return ReplaceInstUsesWith(EI, IE->getOperand(1));
9528 // If the inserted and extracted elements are constants, they must not
9529 // be the same value, extract from the pre-inserted value instead.
Chris Lattner08142f22009-08-30 19:47:22 +00009530 if (isa<Constant>(IE->getOperand(2)) && isa<Constant>(EI.getOperand(1))) {
Chris Lattner3c4e38e2009-08-30 06:27:41 +00009531 Worklist.AddValue(EI.getOperand(0));
Chris Lattner73fa49d2006-05-25 22:53:38 +00009532 EI.setOperand(0, IE->getOperand(0));
9533 return &EI;
9534 }
9535 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
9536 // If this is extracting an element from a shufflevector, figure out where
9537 // it came from and extract from the appropriate input element instead.
Reid Spencerb83eb642006-10-20 07:07:24 +00009538 if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
9539 unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
Chris Lattner863bcff2006-05-25 23:48:38 +00009540 Value *Src;
Mon P Wangaeb06d22008-11-10 04:46:22 +00009541 unsigned LHSWidth =
9542 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
9543
9544 if (SrcIdx < LHSWidth)
Chris Lattner863bcff2006-05-25 23:48:38 +00009545 Src = SVI->getOperand(0);
Mon P Wangaeb06d22008-11-10 04:46:22 +00009546 else if (SrcIdx < LHSWidth*2) {
9547 SrcIdx -= LHSWidth;
Chris Lattner863bcff2006-05-25 23:48:38 +00009548 Src = SVI->getOperand(1);
9549 } else {
Owen Anderson9e9a0d52009-07-30 23:03:37 +00009550 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
Chris Lattnerdf084ff2006-03-30 22:02:40 +00009551 }
Eric Christophera3500da2009-07-25 02:28:41 +00009552 return ExtractElementInst::Create(Src,
Chris Lattner4de84762010-01-04 07:02:48 +00009553 ConstantInt::get(Type::getInt32Ty(EI.getContext()),
9554 SrcIdx, false));
Robert Bocchino1d7456d2006-01-13 22:48:06 +00009555 }
9556 }
Eli Friedman2451a642009-07-18 23:06:53 +00009557 // FIXME: Canonicalize extractelement(bitcast) -> bitcast(extractelement)
Chris Lattner73fa49d2006-05-25 22:53:38 +00009558 }
Robert Bocchino1d7456d2006-01-13 22:48:06 +00009559 return 0;
9560}
9561
Chris Lattner7f6cc0c2006-04-16 00:51:47 +00009562/// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
9563/// elements from either LHS or RHS, return the shuffle mask and true.
9564/// Otherwise, return false.
9565static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
Chris Lattner4de84762010-01-04 07:02:48 +00009566 std::vector<Constant*> &Mask) {
Chris Lattner7f6cc0c2006-04-16 00:51:47 +00009567 assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
9568 "Invalid CollectSingleShuffleElements");
Reid Spencer9d6565a2007-02-15 02:26:10 +00009569 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
Chris Lattner7f6cc0c2006-04-16 00:51:47 +00009570
9571 if (isa<UndefValue>(V)) {
Chris Lattner4de84762010-01-04 07:02:48 +00009572 Mask.assign(NumElts, UndefValue::get(Type::getInt32Ty(V->getContext())));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +00009573 return true;
Chris Lattner4de84762010-01-04 07:02:48 +00009574 }
9575
9576 if (V == LHS) {
Chris Lattner7f6cc0c2006-04-16 00:51:47 +00009577 for (unsigned i = 0; i != NumElts; ++i)
Chris Lattner4de84762010-01-04 07:02:48 +00009578 Mask.push_back(ConstantInt::get(Type::getInt32Ty(V->getContext()), i));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +00009579 return true;
Chris Lattner4de84762010-01-04 07:02:48 +00009580 }
9581
9582 if (V == RHS) {
Chris Lattner7f6cc0c2006-04-16 00:51:47 +00009583 for (unsigned i = 0; i != NumElts; ++i)
Chris Lattner4de84762010-01-04 07:02:48 +00009584 Mask.push_back(ConstantInt::get(Type::getInt32Ty(V->getContext()),
9585 i+NumElts));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +00009586 return true;
Chris Lattner4de84762010-01-04 07:02:48 +00009587 }
9588
9589 if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
Chris Lattner7f6cc0c2006-04-16 00:51:47 +00009590 // If this is an insert of an extract from some other vector, include it.
9591 Value *VecOp = IEI->getOperand(0);
9592 Value *ScalarOp = IEI->getOperand(1);
9593 Value *IdxOp = IEI->getOperand(2);
9594
Chris Lattnerd929f062006-04-27 21:14:21 +00009595 if (!isa<ConstantInt>(IdxOp))
9596 return false;
Reid Spencerb83eb642006-10-20 07:07:24 +00009597 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerd929f062006-04-27 21:14:21 +00009598
9599 if (isa<UndefValue>(ScalarOp)) { // inserting undef into vector.
9600 // Okay, we can handle this if the vector we are insertinting into is
9601 // transitively ok.
Chris Lattner4de84762010-01-04 07:02:48 +00009602 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
Chris Lattnerd929f062006-04-27 21:14:21 +00009603 // If so, update the mask to reflect the inserted undef.
Chris Lattner4de84762010-01-04 07:02:48 +00009604 Mask[InsertedIdx] = UndefValue::get(Type::getInt32Ty(V->getContext()));
Chris Lattnerd929f062006-04-27 21:14:21 +00009605 return true;
9606 }
9607 } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
9608 if (isa<ConstantInt>(EI->getOperand(1)) &&
Chris Lattner7f6cc0c2006-04-16 00:51:47 +00009609 EI->getOperand(0)->getType() == V->getType()) {
9610 unsigned ExtractedIdx =
Reid Spencerb83eb642006-10-20 07:07:24 +00009611 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
Chris Lattner7f6cc0c2006-04-16 00:51:47 +00009612
9613 // This must be extracting from either LHS or RHS.
9614 if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
9615 // Okay, we can handle this if the vector we are insertinting into is
9616 // transitively ok.
Chris Lattner4de84762010-01-04 07:02:48 +00009617 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
Chris Lattner7f6cc0c2006-04-16 00:51:47 +00009618 // If so, update the mask to reflect the inserted value.
9619 if (EI->getOperand(0) == LHS) {
Mon P Wang4f5ca2c2008-08-20 02:23:25 +00009620 Mask[InsertedIdx % NumElts] =
Chris Lattner4de84762010-01-04 07:02:48 +00009621 ConstantInt::get(Type::getInt32Ty(V->getContext()),
9622 ExtractedIdx);
Chris Lattner7f6cc0c2006-04-16 00:51:47 +00009623 } else {
9624 assert(EI->getOperand(0) == RHS);
Mon P Wang4f5ca2c2008-08-20 02:23:25 +00009625 Mask[InsertedIdx % NumElts] =
Chris Lattner4de84762010-01-04 07:02:48 +00009626 ConstantInt::get(Type::getInt32Ty(V->getContext()),
9627 ExtractedIdx+NumElts);
Chris Lattner7f6cc0c2006-04-16 00:51:47 +00009628
9629 }
9630 return true;
9631 }
9632 }
9633 }
9634 }
9635 }
9636 // TODO: Handle shufflevector here!
9637
9638 return false;
9639}
9640
9641/// CollectShuffleElements - We are building a shuffle of V, using RHS as the
9642/// RHS of the shuffle instruction, if it is not null. Return a shuffle mask
9643/// that computes V and the LHS value of the shuffle.
Chris Lattnerefb47352006-04-15 01:39:45 +00009644static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
Chris Lattner4de84762010-01-04 07:02:48 +00009645 Value *&RHS) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00009646 assert(isa<VectorType>(V->getType()) &&
Chris Lattner7f6cc0c2006-04-16 00:51:47 +00009647 (RHS == 0 || V->getType() == RHS->getType()) &&
Chris Lattnerefb47352006-04-15 01:39:45 +00009648 "Invalid shuffle!");
Reid Spencer9d6565a2007-02-15 02:26:10 +00009649 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
Chris Lattnerefb47352006-04-15 01:39:45 +00009650
9651 if (isa<UndefValue>(V)) {
Chris Lattner4de84762010-01-04 07:02:48 +00009652 Mask.assign(NumElts, UndefValue::get(Type::getInt32Ty(V->getContext())));
Chris Lattnerefb47352006-04-15 01:39:45 +00009653 return V;
9654 } else if (isa<ConstantAggregateZero>(V)) {
Chris Lattner4de84762010-01-04 07:02:48 +00009655 Mask.assign(NumElts, ConstantInt::get(Type::getInt32Ty(V->getContext()),0));
Chris Lattnerefb47352006-04-15 01:39:45 +00009656 return V;
9657 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
9658 // If this is an insert of an extract from some other vector, include it.
9659 Value *VecOp = IEI->getOperand(0);
9660 Value *ScalarOp = IEI->getOperand(1);
9661 Value *IdxOp = IEI->getOperand(2);
9662
9663 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
9664 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
9665 EI->getOperand(0)->getType() == V->getType()) {
9666 unsigned ExtractedIdx =
Reid Spencerb83eb642006-10-20 07:07:24 +00009667 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
9668 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerefb47352006-04-15 01:39:45 +00009669
9670 // Either the extracted from or inserted into vector must be RHSVec,
9671 // otherwise we'd end up with a shuffle of three inputs.
Chris Lattner7f6cc0c2006-04-16 00:51:47 +00009672 if (EI->getOperand(0) == RHS || RHS == 0) {
9673 RHS = EI->getOperand(0);
Chris Lattner4de84762010-01-04 07:02:48 +00009674 Value *V = CollectShuffleElements(VecOp, Mask, RHS);
Mon P Wang4f5ca2c2008-08-20 02:23:25 +00009675 Mask[InsertedIdx % NumElts] =
Chris Lattner4de84762010-01-04 07:02:48 +00009676 ConstantInt::get(Type::getInt32Ty(V->getContext()),
9677 NumElts+ExtractedIdx);
Chris Lattnerefb47352006-04-15 01:39:45 +00009678 return V;
9679 }
9680
Chris Lattner7f6cc0c2006-04-16 00:51:47 +00009681 if (VecOp == RHS) {
Chris Lattner4de84762010-01-04 07:02:48 +00009682 Value *V = CollectShuffleElements(EI->getOperand(0), Mask, RHS);
Chris Lattnerefb47352006-04-15 01:39:45 +00009683 // Everything but the extracted element is replaced with the RHS.
9684 for (unsigned i = 0; i != NumElts; ++i) {
9685 if (i != InsertedIdx)
Chris Lattner4de84762010-01-04 07:02:48 +00009686 Mask[i] = ConstantInt::get(Type::getInt32Ty(V->getContext()),
9687 NumElts+i);
Chris Lattnerefb47352006-04-15 01:39:45 +00009688 }
9689 return V;
9690 }
Chris Lattner7f6cc0c2006-04-16 00:51:47 +00009691
9692 // If this insertelement is a chain that comes from exactly these two
9693 // vectors, return the vector and the effective shuffle.
Chris Lattner4de84762010-01-04 07:02:48 +00009694 if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask))
Chris Lattner7f6cc0c2006-04-16 00:51:47 +00009695 return EI->getOperand(0);
Chris Lattnerefb47352006-04-15 01:39:45 +00009696 }
9697 }
9698 }
Chris Lattner7f6cc0c2006-04-16 00:51:47 +00009699 // TODO: Handle shufflevector here!
Chris Lattnerefb47352006-04-15 01:39:45 +00009700
9701 // Otherwise, can't do anything fancy. Return an identity vector.
9702 for (unsigned i = 0; i != NumElts; ++i)
Chris Lattner4de84762010-01-04 07:02:48 +00009703 Mask.push_back(ConstantInt::get(Type::getInt32Ty(V->getContext()), i));
Chris Lattnerefb47352006-04-15 01:39:45 +00009704 return V;
9705}
9706
9707Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
9708 Value *VecOp = IE.getOperand(0);
9709 Value *ScalarOp = IE.getOperand(1);
9710 Value *IdxOp = IE.getOperand(2);
9711
Chris Lattner599ded12007-04-09 01:11:16 +00009712 // Inserting an undef or into an undefined place, remove this.
9713 if (isa<UndefValue>(ScalarOp) || isa<UndefValue>(IdxOp))
9714 ReplaceInstUsesWith(IE, VecOp);
Eli Friedman76e7ba82009-07-18 19:04:16 +00009715
Chris Lattnerefb47352006-04-15 01:39:45 +00009716 // If the inserted element was extracted from some other vector, and if the
9717 // indexes are constant, try to turn this into a shufflevector operation.
9718 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
9719 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
9720 EI->getOperand(0)->getType() == IE.getType()) {
Eli Friedman76e7ba82009-07-18 19:04:16 +00009721 unsigned NumVectorElts = IE.getType()->getNumElements();
Chris Lattnere34e9a22007-04-14 23:32:02 +00009722 unsigned ExtractedIdx =
9723 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
Reid Spencerb83eb642006-10-20 07:07:24 +00009724 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerefb47352006-04-15 01:39:45 +00009725
9726 if (ExtractedIdx >= NumVectorElts) // Out of range extract.
9727 return ReplaceInstUsesWith(IE, VecOp);
9728
9729 if (InsertedIdx >= NumVectorElts) // Out of range insert.
Owen Anderson9e9a0d52009-07-30 23:03:37 +00009730 return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
Chris Lattnerefb47352006-04-15 01:39:45 +00009731
9732 // If we are extracting a value from a vector, then inserting it right
9733 // back into the same place, just use the input vector.
9734 if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
9735 return ReplaceInstUsesWith(IE, VecOp);
9736
Chris Lattnerefb47352006-04-15 01:39:45 +00009737 // If this insertelement isn't used by some other insertelement, turn it
9738 // (and any insertelements it points to), into one big shuffle.
9739 if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
9740 std::vector<Constant*> Mask;
Chris Lattner7f6cc0c2006-04-16 00:51:47 +00009741 Value *RHS = 0;
Chris Lattner4de84762010-01-04 07:02:48 +00009742 Value *LHS = CollectShuffleElements(&IE, Mask, RHS);
Owen Anderson9e9a0d52009-07-30 23:03:37 +00009743 if (RHS == 0) RHS = UndefValue::get(LHS->getType());
Chris Lattner7f6cc0c2006-04-16 00:51:47 +00009744 // We now have a shuffle of LHS, RHS, Mask.
Owen Andersond672ecb2009-07-03 00:17:18 +00009745 return new ShuffleVectorInst(LHS, RHS,
Owen Andersonaf7ec972009-07-28 21:19:26 +00009746 ConstantVector::get(Mask));
Chris Lattnerefb47352006-04-15 01:39:45 +00009747 }
9748 }
9749 }
9750
Eli Friedmanb9a4cac2009-06-06 20:08:03 +00009751 unsigned VWidth = cast<VectorType>(VecOp->getType())->getNumElements();
9752 APInt UndefElts(VWidth, 0);
9753 APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
9754 if (SimplifyDemandedVectorElts(&IE, AllOnesEltMask, UndefElts))
9755 return &IE;
9756
Chris Lattnerefb47352006-04-15 01:39:45 +00009757 return 0;
9758}
9759
9760
Chris Lattnera844fc4c2006-04-10 22:45:52 +00009761Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
9762 Value *LHS = SVI.getOperand(0);
9763 Value *RHS = SVI.getOperand(1);
Chris Lattner863bcff2006-05-25 23:48:38 +00009764 std::vector<unsigned> Mask = getShuffleMask(&SVI);
Chris Lattnera844fc4c2006-04-10 22:45:52 +00009765
9766 bool MadeChange = false;
Mon P Wangaeb06d22008-11-10 04:46:22 +00009767
Chris Lattner867b99f2006-10-05 06:55:50 +00009768 // Undefined shuffle mask -> undefined value.
Chris Lattner863bcff2006-05-25 23:48:38 +00009769 if (isa<UndefValue>(SVI.getOperand(2)))
Owen Anderson9e9a0d52009-07-30 23:03:37 +00009770 return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
Dan Gohman488fbfc2008-09-09 18:11:14 +00009771
Dan Gohman488fbfc2008-09-09 18:11:14 +00009772 unsigned VWidth = cast<VectorType>(SVI.getType())->getNumElements();
Mon P Wangaeb06d22008-11-10 04:46:22 +00009773
9774 if (VWidth != cast<VectorType>(LHS->getType())->getNumElements())
9775 return 0;
9776
Evan Cheng388df622009-02-03 10:05:09 +00009777 APInt UndefElts(VWidth, 0);
9778 APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
9779 if (SimplifyDemandedVectorElts(&SVI, AllOnesEltMask, UndefElts)) {
Dan Gohman3139ff82008-09-11 22:47:57 +00009780 LHS = SVI.getOperand(0);
9781 RHS = SVI.getOperand(1);
Dan Gohman488fbfc2008-09-09 18:11:14 +00009782 MadeChange = true;
Dan Gohman3139ff82008-09-11 22:47:57 +00009783 }
Chris Lattnerefb47352006-04-15 01:39:45 +00009784
Chris Lattner863bcff2006-05-25 23:48:38 +00009785 // Canonicalize shuffle(x ,x,mask) -> shuffle(x, undef,mask')
9786 // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
9787 if (LHS == RHS || isa<UndefValue>(LHS)) {
9788 if (isa<UndefValue>(LHS) && LHS == RHS) {
Chris Lattnera844fc4c2006-04-10 22:45:52 +00009789 // shuffle(undef,undef,mask) -> undef.
9790 return ReplaceInstUsesWith(SVI, LHS);
9791 }
9792
Chris Lattner863bcff2006-05-25 23:48:38 +00009793 // Remap any references to RHS to use LHS.
9794 std::vector<Constant*> Elts;
9795 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
Chris Lattner7b2e27922006-05-26 00:29:06 +00009796 if (Mask[i] >= 2*e)
Chris Lattner4de84762010-01-04 07:02:48 +00009797 Elts.push_back(UndefValue::get(Type::getInt32Ty(SVI.getContext())));
Chris Lattner7b2e27922006-05-26 00:29:06 +00009798 else {
9799 if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
Dan Gohman4ce96272008-08-06 18:17:32 +00009800 (Mask[i] < e && isa<UndefValue>(LHS))) {
Chris Lattner7b2e27922006-05-26 00:29:06 +00009801 Mask[i] = 2*e; // Turn into undef.
Chris Lattner4de84762010-01-04 07:02:48 +00009802 Elts.push_back(UndefValue::get(Type::getInt32Ty(SVI.getContext())));
Dan Gohman4ce96272008-08-06 18:17:32 +00009803 } else {
Mon P Wang4f5ca2c2008-08-20 02:23:25 +00009804 Mask[i] = Mask[i] % e; // Force to LHS.
Chris Lattner4de84762010-01-04 07:02:48 +00009805 Elts.push_back(ConstantInt::get(Type::getInt32Ty(SVI.getContext()),
9806 Mask[i]));
Dan Gohman4ce96272008-08-06 18:17:32 +00009807 }
Chris Lattner7b2e27922006-05-26 00:29:06 +00009808 }
Chris Lattnera844fc4c2006-04-10 22:45:52 +00009809 }
Chris Lattner863bcff2006-05-25 23:48:38 +00009810 SVI.setOperand(0, SVI.getOperand(1));
Owen Anderson9e9a0d52009-07-30 23:03:37 +00009811 SVI.setOperand(1, UndefValue::get(RHS->getType()));
Owen Andersonaf7ec972009-07-28 21:19:26 +00009812 SVI.setOperand(2, ConstantVector::get(Elts));
Chris Lattner7b2e27922006-05-26 00:29:06 +00009813 LHS = SVI.getOperand(0);
9814 RHS = SVI.getOperand(1);
Chris Lattnera844fc4c2006-04-10 22:45:52 +00009815 MadeChange = true;
9816 }
9817
Chris Lattner7b2e27922006-05-26 00:29:06 +00009818 // Analyze the shuffle, are the LHS or RHS and identity shuffles?
Chris Lattner863bcff2006-05-25 23:48:38 +00009819 bool isLHSID = true, isRHSID = true;
Chris Lattner706126d2006-04-16 00:03:56 +00009820
Chris Lattner863bcff2006-05-25 23:48:38 +00009821 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
9822 if (Mask[i] >= e*2) continue; // Ignore undef values.
9823 // Is this an identity shuffle of the LHS value?
9824 isLHSID &= (Mask[i] == i);
9825
9826 // Is this an identity shuffle of the RHS value?
9827 isRHSID &= (Mask[i]-e == i);
Chris Lattner706126d2006-04-16 00:03:56 +00009828 }
Chris Lattnera844fc4c2006-04-10 22:45:52 +00009829
Chris Lattner863bcff2006-05-25 23:48:38 +00009830 // Eliminate identity shuffles.
9831 if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
9832 if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
Chris Lattnera844fc4c2006-04-10 22:45:52 +00009833
Chris Lattner7b2e27922006-05-26 00:29:06 +00009834 // If the LHS is a shufflevector itself, see if we can combine it with this
9835 // one without producing an unusual shuffle. Here we are really conservative:
9836 // we are absolutely afraid of producing a shuffle mask not in the input
9837 // program, because the code gen may not be smart enough to turn a merged
9838 // shuffle into two specific shuffles: it may produce worse code. As such,
9839 // we only merge two shuffles if the result is one of the two input shuffle
9840 // masks. In this case, merging the shuffles just removes one instruction,
9841 // which we know is safe. This is good for things like turning:
9842 // (splat(splat)) -> splat.
9843 if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
9844 if (isa<UndefValue>(RHS)) {
9845 std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
9846
David Greenef941d292009-11-16 21:52:23 +00009847 if (LHSMask.size() == Mask.size()) {
9848 std::vector<unsigned> NewMask;
9849 for (unsigned i = 0, e = Mask.size(); i != e; ++i)
Duncan Sands76700ba2009-11-20 13:19:51 +00009850 if (Mask[i] >= e)
David Greenef941d292009-11-16 21:52:23 +00009851 NewMask.push_back(2*e);
9852 else
9853 NewMask.push_back(LHSMask[Mask[i]]);
Chris Lattner7b2e27922006-05-26 00:29:06 +00009854
David Greenef941d292009-11-16 21:52:23 +00009855 // If the result mask is equal to the src shuffle or this
9856 // shuffle mask, do the replacement.
9857 if (NewMask == LHSMask || NewMask == Mask) {
9858 unsigned LHSInNElts =
9859 cast<VectorType>(LHSSVI->getOperand(0)->getType())->
9860 getNumElements();
9861 std::vector<Constant*> Elts;
9862 for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
9863 if (NewMask[i] >= LHSInNElts*2) {
Chris Lattner4de84762010-01-04 07:02:48 +00009864 Elts.push_back(UndefValue::get(
9865 Type::getInt32Ty(SVI.getContext())));
David Greenef941d292009-11-16 21:52:23 +00009866 } else {
Chris Lattner4de84762010-01-04 07:02:48 +00009867 Elts.push_back(ConstantInt::get(
9868 Type::getInt32Ty(SVI.getContext()),
David Greenef941d292009-11-16 21:52:23 +00009869 NewMask[i]));
9870 }
Chris Lattner7b2e27922006-05-26 00:29:06 +00009871 }
David Greenef941d292009-11-16 21:52:23 +00009872 return new ShuffleVectorInst(LHSSVI->getOperand(0),
9873 LHSSVI->getOperand(1),
9874 ConstantVector::get(Elts));
Chris Lattner7b2e27922006-05-26 00:29:06 +00009875 }
Chris Lattner7b2e27922006-05-26 00:29:06 +00009876 }
9877 }
9878 }
Chris Lattnerc5eff442007-01-30 22:32:46 +00009879
Chris Lattnera844fc4c2006-04-10 22:45:52 +00009880 return MadeChange ? &SVI : 0;
9881}
9882
9883
Robert Bocchino1d7456d2006-01-13 22:48:06 +00009884
Chris Lattnerea1c4542004-12-08 23:43:58 +00009885
9886/// TryToSinkInstruction - Try to move the specified instruction from its
9887/// current block into the beginning of DestBlock, which can only happen if it's
9888/// safe to move the instruction past all of the instructions between it and the
9889/// end of its block.
9890static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
9891 assert(I->hasOneUse() && "Invariants didn't hold!");
9892
Chris Lattner108e9022005-10-27 17:13:11 +00009893 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
Duncan Sands7af1c782009-05-06 06:49:50 +00009894 if (isa<PHINode>(I) || I->mayHaveSideEffects() || isa<TerminatorInst>(I))
Chris Lattnerbfc538c2008-05-09 15:07:33 +00009895 return false;
Misha Brukmanfd939082005-04-21 23:48:37 +00009896
Chris Lattnerea1c4542004-12-08 23:43:58 +00009897 // Do not sink alloca instructions out of the entry block.
Dan Gohmanecb7a772007-03-22 16:38:57 +00009898 if (isa<AllocaInst>(I) && I->getParent() ==
9899 &DestBlock->getParent()->getEntryBlock())
Chris Lattnerea1c4542004-12-08 23:43:58 +00009900 return false;
9901
Chris Lattner96a52a62004-12-09 07:14:34 +00009902 // We can only sink load instructions if there is nothing between the load and
9903 // the end of block that could change the value.
Chris Lattner2539e332008-05-08 17:37:37 +00009904 if (I->mayReadFromMemory()) {
9905 for (BasicBlock::iterator Scan = I, E = I->getParent()->end();
Chris Lattner96a52a62004-12-09 07:14:34 +00009906 Scan != E; ++Scan)
9907 if (Scan->mayWriteToMemory())
9908 return false;
Chris Lattner96a52a62004-12-09 07:14:34 +00009909 }
Chris Lattnerea1c4542004-12-08 23:43:58 +00009910
Dan Gohman02dea8b2008-05-23 21:05:58 +00009911 BasicBlock::iterator InsertPos = DestBlock->getFirstNonPHI();
Chris Lattnerea1c4542004-12-08 23:43:58 +00009912
Dale Johannesenbd8e6502009-03-03 01:09:07 +00009913 CopyPrecedingStopPoint(I, InsertPos);
Chris Lattner4bc5f802005-08-08 19:11:57 +00009914 I->moveBefore(InsertPos);
Chris Lattnerea1c4542004-12-08 23:43:58 +00009915 ++NumSunkInst;
9916 return true;
9917}
9918
Chris Lattnerf4f5a772006-05-10 19:00:36 +00009919
9920/// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
9921/// all reachable code to the worklist.
9922///
9923/// This has a couple of tricks to make the code faster and more powerful. In
9924/// particular, we constant fold and DCE instructions as we go, to avoid adding
9925/// them to the worklist (this significantly speeds up instcombine on code where
9926/// many instructions are dead or constant). Additionally, if we find a branch
9927/// whose condition is a known constant, we only visit the reachable successors.
9928///
Chris Lattner2ee743b2009-10-15 04:59:28 +00009929static bool AddReachableCodeToWorklist(BasicBlock *BB,
Chris Lattner1f87a582007-02-15 19:41:52 +00009930 SmallPtrSet<BasicBlock*, 64> &Visited,
Chris Lattnerdbab3862007-03-02 21:28:56 +00009931 InstCombiner &IC,
Chris Lattner8c8c66a2006-05-11 17:11:52 +00009932 const TargetData *TD) {
Chris Lattner2ee743b2009-10-15 04:59:28 +00009933 bool MadeIRChange = false;
Chris Lattner2806dff2008-08-15 04:03:01 +00009934 SmallVector<BasicBlock*, 256> Worklist;
Chris Lattner2c7718a2007-03-23 19:17:18 +00009935 Worklist.push_back(BB);
Chris Lattner67f7d542009-10-12 03:58:40 +00009936
9937 std::vector<Instruction*> InstrsForInstCombineWorklist;
9938 InstrsForInstCombineWorklist.reserve(128);
Chris Lattnerf4f5a772006-05-10 19:00:36 +00009939
Chris Lattner2ee743b2009-10-15 04:59:28 +00009940 SmallPtrSet<ConstantExpr*, 64> FoldedConstants;
9941
Chris Lattner2c7718a2007-03-23 19:17:18 +00009942 while (!Worklist.empty()) {
9943 BB = Worklist.back();
9944 Worklist.pop_back();
9945
9946 // We have now visited this block! If we've already been here, ignore it.
9947 if (!Visited.insert(BB)) continue;
Devang Patel7fe1dec2008-11-19 18:56:50 +00009948
Chris Lattner2c7718a2007-03-23 19:17:18 +00009949 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
9950 Instruction *Inst = BBI++;
Chris Lattnerf4f5a772006-05-10 19:00:36 +00009951
Chris Lattner2c7718a2007-03-23 19:17:18 +00009952 // DCE instruction if trivially dead.
9953 if (isInstructionTriviallyDead(Inst)) {
9954 ++NumDeadInst;
Chris Lattnerbdff5482009-08-23 04:37:46 +00009955 DEBUG(errs() << "IC: DCE: " << *Inst << '\n');
Chris Lattner2c7718a2007-03-23 19:17:18 +00009956 Inst->eraseFromParent();
9957 continue;
9958 }
9959
9960 // ConstantProp instruction if trivially constant.
Chris Lattnere2cc1ad2009-10-15 04:13:44 +00009961 if (!Inst->use_empty() && isa<Constant>(Inst->getOperand(0)))
Chris Lattner7b550cc2009-11-06 04:27:31 +00009962 if (Constant *C = ConstantFoldInstruction(Inst, TD)) {
Chris Lattnere2cc1ad2009-10-15 04:13:44 +00009963 DEBUG(errs() << "IC: ConstFold to: " << *C << " from: "
9964 << *Inst << '\n');
9965 Inst->replaceAllUsesWith(C);
9966 ++NumConstProp;
9967 Inst->eraseFromParent();
9968 continue;
9969 }
Chris Lattner2ee743b2009-10-15 04:59:28 +00009970
9971
9972
9973 if (TD) {
9974 // See if we can constant fold its operands.
9975 for (User::op_iterator i = Inst->op_begin(), e = Inst->op_end();
9976 i != e; ++i) {
9977 ConstantExpr *CE = dyn_cast<ConstantExpr>(i);
9978 if (CE == 0) continue;
9979
9980 // If we already folded this constant, don't try again.
9981 if (!FoldedConstants.insert(CE))
9982 continue;
9983
Chris Lattner7b550cc2009-11-06 04:27:31 +00009984 Constant *NewC = ConstantFoldConstantExpression(CE, TD);
Chris Lattner2ee743b2009-10-15 04:59:28 +00009985 if (NewC && NewC != CE) {
9986 *i = NewC;
9987 MadeIRChange = true;
9988 }
9989 }
9990 }
9991
Devang Patel7fe1dec2008-11-19 18:56:50 +00009992
Chris Lattner67f7d542009-10-12 03:58:40 +00009993 InstrsForInstCombineWorklist.push_back(Inst);
Chris Lattnerf4f5a772006-05-10 19:00:36 +00009994 }
Chris Lattner2c7718a2007-03-23 19:17:18 +00009995
9996 // Recursively visit successors. If this is a branch or switch on a
9997 // constant, only visit the reachable successor.
9998 TerminatorInst *TI = BB->getTerminator();
9999 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
10000 if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
10001 bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
Nick Lewycky91436992008-03-09 08:50:23 +000010002 BasicBlock *ReachableBB = BI->getSuccessor(!CondVal);
Nick Lewycky280a6e62008-04-25 16:53:59 +000010003 Worklist.push_back(ReachableBB);
Chris Lattner2c7718a2007-03-23 19:17:18 +000010004 continue;
10005 }
10006 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
10007 if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
10008 // See if this is an explicit destination.
10009 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
10010 if (SI->getCaseValue(i) == Cond) {
Nick Lewycky91436992008-03-09 08:50:23 +000010011 BasicBlock *ReachableBB = SI->getSuccessor(i);
Nick Lewycky280a6e62008-04-25 16:53:59 +000010012 Worklist.push_back(ReachableBB);
Chris Lattner2c7718a2007-03-23 19:17:18 +000010013 continue;
10014 }
10015
10016 // Otherwise it is the default destination.
10017 Worklist.push_back(SI->getSuccessor(0));
10018 continue;
10019 }
10020 }
10021
10022 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
10023 Worklist.push_back(TI->getSuccessor(i));
Chris Lattnerf4f5a772006-05-10 19:00:36 +000010024 }
Chris Lattner67f7d542009-10-12 03:58:40 +000010025
10026 // Once we've found all of the instructions to add to instcombine's worklist,
10027 // add them in reverse order. This way instcombine will visit from the top
10028 // of the function down. This jives well with the way that it adds all uses
10029 // of instructions to the worklist after doing a transformation, thus avoiding
10030 // some N^2 behavior in pathological cases.
10031 IC.Worklist.AddInitialGroup(&InstrsForInstCombineWorklist[0],
10032 InstrsForInstCombineWorklist.size());
Chris Lattner2ee743b2009-10-15 04:59:28 +000010033
10034 return MadeIRChange;
Chris Lattnerf4f5a772006-05-10 19:00:36 +000010035}
10036
Chris Lattnerec9c3582007-03-03 02:04:50 +000010037bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) {
Chris Lattnerb0b822c2009-08-31 06:57:37 +000010038 MadeIRChange = false;
Chris Lattnerec9c3582007-03-03 02:04:50 +000010039
Daniel Dunbarce63ffb2009-07-25 00:23:56 +000010040 DEBUG(errs() << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
10041 << F.getNameStr() << "\n");
Chris Lattner8a2a3112001-12-14 16:52:21 +000010042
Chris Lattnerb3d59702005-07-07 20:40:38 +000010043 {
Chris Lattnerf4f5a772006-05-10 19:00:36 +000010044 // Do a depth-first traversal of the function, populate the worklist with
10045 // the reachable instructions. Ignore blocks that are not reachable. Keep
10046 // track of which blocks we visit.
Chris Lattner1f87a582007-02-15 19:41:52 +000010047 SmallPtrSet<BasicBlock*, 64> Visited;
Chris Lattner2ee743b2009-10-15 04:59:28 +000010048 MadeIRChange |= AddReachableCodeToWorklist(F.begin(), Visited, *this, TD);
Jeff Cohen00b168892005-07-27 06:12:32 +000010049
Chris Lattnerb3d59702005-07-07 20:40:38 +000010050 // Do a quick scan over the function. If we find any blocks that are
10051 // unreachable, remove any instructions inside of them. This prevents
10052 // the instcombine code from having to deal with some bad special cases.
10053 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
10054 if (!Visited.count(BB)) {
10055 Instruction *Term = BB->getTerminator();
10056 while (Term != BB->begin()) { // Remove instrs bottom-up
10057 BasicBlock::iterator I = Term; --I;
Chris Lattner6ffe5512004-04-27 15:13:33 +000010058
Chris Lattnerbdff5482009-08-23 04:37:46 +000010059 DEBUG(errs() << "IC: DCE: " << *I << '\n');
Dale Johannesenff278b12009-03-10 21:19:49 +000010060 // A debug intrinsic shouldn't force another iteration if we weren't
10061 // going to do one without it.
10062 if (!isa<DbgInfoIntrinsic>(I)) {
10063 ++NumDeadInst;
Chris Lattnerb0b822c2009-08-31 06:57:37 +000010064 MadeIRChange = true;
Dale Johannesenff278b12009-03-10 21:19:49 +000010065 }
Devang Patel228ebd02009-10-13 22:56:32 +000010066
Devang Patel228ebd02009-10-13 22:56:32 +000010067 // If I is not void type then replaceAllUsesWith undef.
10068 // This allows ValueHandlers and custom metadata to adjust itself.
Devang Patel9674d152009-10-14 17:29:00 +000010069 if (!I->getType()->isVoidTy())
Devang Patel228ebd02009-10-13 22:56:32 +000010070 I->replaceAllUsesWith(UndefValue::get(I->getType()));
Chris Lattnerb3d59702005-07-07 20:40:38 +000010071 I->eraseFromParent();
10072 }
10073 }
10074 }
Chris Lattner8a2a3112001-12-14 16:52:21 +000010075
Chris Lattner873ff012009-08-30 05:55:36 +000010076 while (!Worklist.isEmpty()) {
10077 Instruction *I = Worklist.RemoveOne();
Chris Lattnerdbab3862007-03-02 21:28:56 +000010078 if (I == 0) continue; // skip null values.
Chris Lattner8a2a3112001-12-14 16:52:21 +000010079
Chris Lattner8c8c66a2006-05-11 17:11:52 +000010080 // Check to see if we can DCE the instruction.
Chris Lattner62b14df2002-09-02 04:59:56 +000010081 if (isInstructionTriviallyDead(I)) {
Chris Lattnerbdff5482009-08-23 04:37:46 +000010082 DEBUG(errs() << "IC: DCE: " << *I << '\n');
Chris Lattner7a1e9242009-08-30 06:13:40 +000010083 EraseInstFromFunction(*I);
10084 ++NumDeadInst;
Chris Lattnerb0b822c2009-08-31 06:57:37 +000010085 MadeIRChange = true;
Chris Lattner4bb7c022003-10-06 17:11:01 +000010086 continue;
10087 }
Chris Lattner62b14df2002-09-02 04:59:56 +000010088
Chris Lattner8c8c66a2006-05-11 17:11:52 +000010089 // Instruction isn't dead, see if we can constant propagate it.
Chris Lattnere2cc1ad2009-10-15 04:13:44 +000010090 if (!I->use_empty() && isa<Constant>(I->getOperand(0)))
Chris Lattner7b550cc2009-11-06 04:27:31 +000010091 if (Constant *C = ConstantFoldInstruction(I, TD)) {
Chris Lattnere2cc1ad2009-10-15 04:13:44 +000010092 DEBUG(errs() << "IC: ConstFold to: " << *C << " from: " << *I << '\n');
Chris Lattnerad5fec12005-01-28 19:32:01 +000010093
Chris Lattnere2cc1ad2009-10-15 04:13:44 +000010094 // Add operands to the worklist.
10095 ReplaceInstUsesWith(*I, C);
10096 ++NumConstProp;
10097 EraseInstFromFunction(*I);
10098 MadeIRChange = true;
10099 continue;
10100 }
Chris Lattner4bb7c022003-10-06 17:11:01 +000010101
Chris Lattnerea1c4542004-12-08 23:43:58 +000010102 // See if we can trivially sink this instruction to a successor basic block.
Dan Gohmanfc74abf2008-07-23 00:34:11 +000010103 if (I->hasOneUse()) {
Chris Lattnerea1c4542004-12-08 23:43:58 +000010104 BasicBlock *BB = I->getParent();
Chris Lattner8db2cd12009-10-14 15:21:58 +000010105 Instruction *UserInst = cast<Instruction>(I->use_back());
10106 BasicBlock *UserParent;
10107
10108 // Get the block the use occurs in.
10109 if (PHINode *PN = dyn_cast<PHINode>(UserInst))
10110 UserParent = PN->getIncomingBlock(I->use_begin().getUse());
10111 else
10112 UserParent = UserInst->getParent();
10113
Chris Lattnerea1c4542004-12-08 23:43:58 +000010114 if (UserParent != BB) {
10115 bool UserIsSuccessor = false;
10116 // See if the user is one of our successors.
10117 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
10118 if (*SI == UserParent) {
10119 UserIsSuccessor = true;
10120 break;
10121 }
10122
10123 // If the user is one of our immediate successors, and if that successor
10124 // only has us as a predecessors (we'd have to split the critical edge
10125 // otherwise), we can keep going.
Chris Lattner8db2cd12009-10-14 15:21:58 +000010126 if (UserIsSuccessor && UserParent->getSinglePredecessor())
Chris Lattnerea1c4542004-12-08 23:43:58 +000010127 // Okay, the CFG is simple enough, try to sink this instruction.
Chris Lattnerb0b822c2009-08-31 06:57:37 +000010128 MadeIRChange |= TryToSinkInstruction(I, UserParent);
Chris Lattnerea1c4542004-12-08 23:43:58 +000010129 }
10130 }
10131
Chris Lattner74381062009-08-30 07:44:24 +000010132 // Now that we have an instruction, try combining it to simplify it.
10133 Builder->SetInsertPoint(I->getParent(), I);
10134
Reid Spencera9b81012007-03-26 17:44:01 +000010135#ifndef NDEBUG
10136 std::string OrigI;
10137#endif
Chris Lattnerbdff5482009-08-23 04:37:46 +000010138 DEBUG(raw_string_ostream SS(OrigI); I->print(SS); OrigI = SS.str(););
Jeffrey Yasskin43069632009-10-08 00:12:24 +000010139 DEBUG(errs() << "IC: Visiting: " << OrigI << '\n');
10140
Chris Lattner90ac28c2002-08-02 19:29:35 +000010141 if (Instruction *Result = visit(*I)) {
Chris Lattner3dec1f22002-05-10 15:38:35 +000010142 ++NumCombined;
Chris Lattnerdd841ae2002-04-18 17:39:14 +000010143 // Should we replace the old instruction with a new one?
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +000010144 if (Result != I) {
Chris Lattnerbdff5482009-08-23 04:37:46 +000010145 DEBUG(errs() << "IC: Old = " << *I << '\n'
10146 << " New = " << *Result << '\n');
Chris Lattner0cea42a2004-03-13 23:54:27 +000010147
Chris Lattnerf523d062004-06-09 05:08:07 +000010148 // Everything uses the new instruction now.
10149 I->replaceAllUsesWith(Result);
10150
10151 // Push the new instruction and any users onto the worklist.
Chris Lattner7a1e9242009-08-30 06:13:40 +000010152 Worklist.Add(Result);
Chris Lattnere5ecdb52009-08-30 06:22:51 +000010153 Worklist.AddUsersToWorkList(*Result);
Chris Lattner4bb7c022003-10-06 17:11:01 +000010154
Chris Lattner6934a042007-02-11 01:23:03 +000010155 // Move the name to the new instruction first.
10156 Result->takeName(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +000010157
10158 // Insert the new instruction into the basic block...
10159 BasicBlock *InstParent = I->getParent();
Chris Lattnerbac32862004-11-14 19:13:23 +000010160 BasicBlock::iterator InsertPos = I;
10161
10162 if (!isa<PHINode>(Result)) // If combining a PHI, don't insert
10163 while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
10164 ++InsertPos;
10165
10166 InstParent->getInstList().insert(InsertPos, Result);
Chris Lattner4bb7c022003-10-06 17:11:01 +000010167
Chris Lattner7a1e9242009-08-30 06:13:40 +000010168 EraseInstFromFunction(*I);
Chris Lattner7e708292002-06-25 16:13:24 +000010169 } else {
Evan Chengc7baf682007-03-27 16:44:48 +000010170#ifndef NDEBUG
Chris Lattnerbdff5482009-08-23 04:37:46 +000010171 DEBUG(errs() << "IC: Mod = " << OrigI << '\n'
10172 << " New = " << *I << '\n');
Evan Chengc7baf682007-03-27 16:44:48 +000010173#endif
Chris Lattner0cea42a2004-03-13 23:54:27 +000010174
Chris Lattner90ac28c2002-08-02 19:29:35 +000010175 // If the instruction was modified, it's possible that it is now dead.
10176 // if so, remove it.
Chris Lattner00d51312004-05-01 23:27:23 +000010177 if (isInstructionTriviallyDead(I)) {
Chris Lattner7a1e9242009-08-30 06:13:40 +000010178 EraseInstFromFunction(*I);
Chris Lattnerf523d062004-06-09 05:08:07 +000010179 } else {
Chris Lattner7a1e9242009-08-30 06:13:40 +000010180 Worklist.Add(I);
Chris Lattnere5ecdb52009-08-30 06:22:51 +000010181 Worklist.AddUsersToWorkList(*I);
Chris Lattner90ac28c2002-08-02 19:29:35 +000010182 }
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +000010183 }
Chris Lattnerb0b822c2009-08-31 06:57:37 +000010184 MadeIRChange = true;
Chris Lattner8a2a3112001-12-14 16:52:21 +000010185 }
10186 }
10187
Chris Lattner873ff012009-08-30 05:55:36 +000010188 Worklist.Zap();
Chris Lattnerb0b822c2009-08-31 06:57:37 +000010189 return MadeIRChange;
Chris Lattnerbd0ef772002-02-26 21:46:54 +000010190}
10191
Chris Lattnerec9c3582007-03-03 02:04:50 +000010192
10193bool InstCombiner::runOnFunction(Function &F) {
Chris Lattnerf964f322007-03-04 04:27:24 +000010194 MustPreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
Chris Lattnere2cc1ad2009-10-15 04:13:44 +000010195 TD = getAnalysisIfAvailable<TargetData>();
10196
Chris Lattner74381062009-08-30 07:44:24 +000010197
10198 /// Builder - This is an IRBuilder that automatically inserts new
10199 /// instructions into the worklist when they are created.
Chris Lattnere2cc1ad2009-10-15 04:13:44 +000010200 IRBuilder<true, TargetFolder, InstCombineIRInserter>
Chris Lattnerf55eeb92009-11-06 05:59:53 +000010201 TheBuilder(F.getContext(), TargetFolder(TD),
Chris Lattner74381062009-08-30 07:44:24 +000010202 InstCombineIRInserter(Worklist));
10203 Builder = &TheBuilder;
10204
Chris Lattnerec9c3582007-03-03 02:04:50 +000010205 bool EverMadeChange = false;
10206
10207 // Iterate while there is work to do.
10208 unsigned Iteration = 0;
Bill Wendlinga6c31122008-05-14 22:45:20 +000010209 while (DoOneIteration(F, Iteration++))
Chris Lattnerec9c3582007-03-03 02:04:50 +000010210 EverMadeChange = true;
Chris Lattner74381062009-08-30 07:44:24 +000010211
10212 Builder = 0;
Chris Lattnerec9c3582007-03-03 02:04:50 +000010213 return EverMadeChange;
10214}
10215
Brian Gaeke96d4bf72004-07-27 17:43:21 +000010216FunctionPass *llvm::createInstructionCombiningPass() {
Chris Lattnerdd841ae2002-04-18 17:39:14 +000010217 return new InstCombiner();
Chris Lattnerbd0ef772002-02-26 21:46:54 +000010218}