blob: 13f0ac6f7c97ba3d0da448fbc5c6c2673812fc66 [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 Lattnerbd0ef772002-02-26 21:46:54 +000041#include "llvm/Pass.h"
Chris Lattner0864acf2002-11-04 16:18:53 +000042#include "llvm/DerivedTypes.h"
Chris Lattner833b8a42003-06-26 05:06:25 +000043#include "llvm/GlobalVariable.h"
Dan Gohmanca178902009-07-17 20:47:02 +000044#include "llvm/Operator.h"
Chris Lattner79066fa2007-01-30 23:46:24 +000045#include "llvm/Analysis/ConstantFolding.h"
Chris Lattner9dbb4292009-11-09 23:28:39 +000046#include "llvm/Analysis/InstructionSimplify.h"
Victor Hernandezf006b182009-10-27 20:05:49 +000047#include "llvm/Analysis/MemoryBuiltins.h"
Chris Lattner173234a2008-06-02 01:18:21 +000048#include "llvm/Analysis/ValueTracking.h"
Chris Lattnerbc61e662003-11-02 05:57:39 +000049#include "llvm/Target/TargetData.h"
50#include "llvm/Transforms/Utils/BasicBlockUtils.h"
51#include "llvm/Transforms/Utils/Local.h"
Chris Lattner28977af2004-04-05 01:30:19 +000052#include "llvm/Support/CallSite.h"
Nick Lewycky5be29202008-02-03 16:33:09 +000053#include "llvm/Support/ConstantRange.h"
Chris Lattnerea1c4542004-12-08 23:43:58 +000054#include "llvm/Support/Debug.h"
Torok Edwin7d696d82009-07-11 13:10:19 +000055#include "llvm/Support/ErrorHandling.h"
Chris Lattner28977af2004-04-05 01:30:19 +000056#include "llvm/Support/GetElementPtrTypeIterator.h"
Chris Lattnerdd841ae2002-04-18 17:39:14 +000057#include "llvm/Support/InstVisitor.h"
Chris Lattner74381062009-08-30 07:44:24 +000058#include "llvm/Support/IRBuilder.h"
Chris Lattnerbcd7db52005-08-02 19:16:58 +000059#include "llvm/Support/MathExtras.h"
Chris Lattneracd1f0f2004-07-30 07:50:03 +000060#include "llvm/Support/PatternMatch.h"
Chris Lattnere2cc1ad2009-10-15 04:13:44 +000061#include "llvm/Support/TargetFolder.h"
Chris Lattner1f87a582007-02-15 19:41:52 +000062#include "llvm/ADT/SmallPtrSet.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000063#include "llvm/ADT/Statistic.h"
Chris Lattnerea1c4542004-12-08 23:43:58 +000064#include "llvm/ADT/STLExtras.h"
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +000065#include <algorithm>
Torok Edwin3eaee312008-04-20 08:33:11 +000066#include <climits>
Chris Lattner67b1e1b2003-12-07 01:24:23 +000067using namespace llvm;
Chris Lattneracd1f0f2004-07-30 07:50:03 +000068using namespace llvm::PatternMatch;
Brian Gaeked0fde302003-11-11 22:41:34 +000069
Chris Lattner0e5f4992006-12-19 21:40:18 +000070STATISTIC(NumCombined , "Number of insts combined");
71STATISTIC(NumConstProp, "Number of constant folds");
72STATISTIC(NumDeadInst , "Number of dead inst eliminated");
73STATISTIC(NumDeadStore, "Number of dead stores eliminated");
74STATISTIC(NumSunkInst , "Number of instructions sunk");
Chris Lattnera92f6962002-10-01 22:38:41 +000075
Chris Lattnerdd841ae2002-04-18 17:39:14 +000076
Dan Gohman844731a2008-05-13 00:00:25 +000077char InstCombiner::ID = 0;
78static RegisterPass<InstCombiner>
79X("instcombine", "Combine redundant instructions");
80
Chris Lattner4f98c562003-03-10 21:43:22 +000081// getComplexity: Assign a complexity or rank value to LLVM Values...
Chris Lattnere87597f2004-10-16 18:11:37 +000082// 0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
Dan Gohman14ef4f02009-08-29 23:39:38 +000083static unsigned getComplexity(Value *V) {
Chris Lattner4f98c562003-03-10 21:43:22 +000084 if (isa<Instruction>(V)) {
Owen Andersonfa82b6e2009-07-13 22:18:28 +000085 if (BinaryOperator::isNeg(V) ||
86 BinaryOperator::isFNeg(V) ||
Dan Gohmanae3a0be2009-06-04 22:49:04 +000087 BinaryOperator::isNot(V))
Chris Lattnere87597f2004-10-16 18:11:37 +000088 return 3;
89 return 4;
Chris Lattner4f98c562003-03-10 21:43:22 +000090 }
Chris Lattnere87597f2004-10-16 18:11:37 +000091 if (isa<Argument>(V)) return 3;
92 return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
Chris Lattner4f98c562003-03-10 21:43:22 +000093}
Chris Lattnerdd841ae2002-04-18 17:39:14 +000094
Chris Lattnerc8802d22003-03-11 00:12:48 +000095// isOnlyUse - Return true if this instruction will be deleted if we stop using
96// it.
97static bool isOnlyUse(Value *V) {
Chris Lattnerfd059242003-10-15 16:48:29 +000098 return V->hasOneUse() || isa<Constant>(V);
Chris Lattnerc8802d22003-03-11 00:12:48 +000099}
100
Chris Lattner4cb170c2004-02-23 06:38:22 +0000101// getPromotedType - Return the specified type promoted as it would be to pass
102// though a va_arg area...
103static const Type *getPromotedType(const Type *Ty) {
Reid Spencera54b7cb2007-01-12 07:05:14 +0000104 if (const IntegerType* ITy = dyn_cast<IntegerType>(Ty)) {
105 if (ITy->getBitWidth() < 32)
Owen Anderson1d0be152009-08-13 21:58:54 +0000106 return Type::getInt32Ty(Ty->getContext());
Chris Lattner2b7e0ad2007-05-23 01:17:04 +0000107 }
Reid Spencera54b7cb2007-01-12 07:05:14 +0000108 return Ty;
Chris Lattner4cb170c2004-02-23 06:38:22 +0000109}
110
Chris Lattnerc22d4d12009-11-10 07:23:37 +0000111/// ShouldChangeType - Return true if it is desirable to convert a computation
112/// from 'From' to 'To'. We don't want to convert from a legal to an illegal
113/// type for example, or from a smaller to a larger illegal type.
114static bool ShouldChangeType(const Type *From, const Type *To,
115 const TargetData *TD) {
116 assert(isa<IntegerType>(From) && isa<IntegerType>(To));
117
118 // If we don't have TD, we don't know if the source/dest are legal.
119 if (!TD) return false;
120
121 unsigned FromWidth = From->getPrimitiveSizeInBits();
122 unsigned ToWidth = To->getPrimitiveSizeInBits();
123 bool FromLegal = TD->isLegalInteger(FromWidth);
124 bool ToLegal = TD->isLegalInteger(ToWidth);
125
126 // If this is a legal integer from type, and the result would be an illegal
127 // type, don't do the transformation.
128 if (FromLegal && !ToLegal)
129 return false;
130
131 // Otherwise, if both are illegal, do not increase the size of the result. We
132 // do allow things like i160 -> i64, but not i64 -> i160.
133 if (!FromLegal && !ToLegal && ToWidth > FromWidth)
134 return false;
135
136 return true;
137}
138
Matthijs Kooijman7e6d9b92008-10-13 15:17:01 +0000139/// getBitCastOperand - If the specified operand is a CastInst, a constant
140/// expression bitcast, or a GetElementPtrInst with all zero indices, return the
141/// operand value, otherwise return null.
Reid Spencer3da59db2006-11-27 01:05:10 +0000142static Value *getBitCastOperand(Value *V) {
Dan Gohman016de812009-07-17 23:55:56 +0000143 if (Operator *O = dyn_cast<Operator>(V)) {
144 if (O->getOpcode() == Instruction::BitCast)
145 return O->getOperand(0);
146 if (GEPOperator *GEP = dyn_cast<GEPOperator>(V))
147 if (GEP->hasAllZeroIndices())
148 return GEP->getPointerOperand();
Matthijs Kooijman7e6d9b92008-10-13 15:17:01 +0000149 }
Chris Lattnereed48272005-09-13 00:40:14 +0000150 return 0;
151}
152
Reid Spencer3da59db2006-11-27 01:05:10 +0000153/// This function is a wrapper around CastInst::isEliminableCastPair. It
154/// simply extracts arguments and returns what that function returns.
Reid Spencer3da59db2006-11-27 01:05:10 +0000155static Instruction::CastOps
156isEliminableCastPair(
157 const CastInst *CI, ///< The first cast instruction
158 unsigned opcode, ///< The opcode of the second cast instruction
159 const Type *DstTy, ///< The target type for the second cast instruction
160 TargetData *TD ///< The target data for pointer size
161) {
Dan Gohmance9fe9f2009-07-21 23:21:54 +0000162
Reid Spencer3da59db2006-11-27 01:05:10 +0000163 const Type *SrcTy = CI->getOperand(0)->getType(); // A from above
164 const Type *MidTy = CI->getType(); // B from above
Chris Lattner33a61132006-05-06 09:00:16 +0000165
Reid Spencer3da59db2006-11-27 01:05:10 +0000166 // Get the opcodes of the two Cast instructions
167 Instruction::CastOps firstOp = Instruction::CastOps(CI->getOpcode());
168 Instruction::CastOps secondOp = Instruction::CastOps(opcode);
Chris Lattner33a61132006-05-06 09:00:16 +0000169
Chris Lattnera0e69692009-03-24 18:35:40 +0000170 unsigned Res = CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy,
Dan Gohmance9fe9f2009-07-21 23:21:54 +0000171 DstTy,
Owen Anderson1d0be152009-08-13 21:58:54 +0000172 TD ? TD->getIntPtrType(CI->getContext()) : 0);
Chris Lattnera0e69692009-03-24 18:35:40 +0000173
174 // We don't want to form an inttoptr or ptrtoint that converts to an integer
175 // type that differs from the pointer size.
Owen Anderson1d0be152009-08-13 21:58:54 +0000176 if ((Res == Instruction::IntToPtr &&
Dan Gohman5e9bb732009-08-19 23:38:22 +0000177 (!TD || SrcTy != TD->getIntPtrType(CI->getContext()))) ||
Owen Anderson1d0be152009-08-13 21:58:54 +0000178 (Res == Instruction::PtrToInt &&
Dan Gohman5e9bb732009-08-19 23:38:22 +0000179 (!TD || DstTy != TD->getIntPtrType(CI->getContext()))))
Chris Lattnera0e69692009-03-24 18:35:40 +0000180 Res = 0;
181
182 return Instruction::CastOps(Res);
Chris Lattner33a61132006-05-06 09:00:16 +0000183}
184
185/// ValueRequiresCast - Return true if the cast from "V to Ty" actually results
186/// in any code being generated. It does not require codegen if V is simple
187/// enough or if the cast can be folded into other casts.
Reid Spencere4d87aa2006-12-23 06:05:41 +0000188static bool ValueRequiresCast(Instruction::CastOps opcode, const Value *V,
189 const Type *Ty, TargetData *TD) {
Chris Lattner33a61132006-05-06 09:00:16 +0000190 if (V->getType() == Ty || isa<Constant>(V)) return false;
191
Chris Lattner01575b72006-05-25 23:24:33 +0000192 // If this is another cast that can be eliminated, it isn't codegen either.
Chris Lattner33a61132006-05-06 09:00:16 +0000193 if (const CastInst *CI = dyn_cast<CastInst>(V))
Dan Gohmance9fe9f2009-07-21 23:21:54 +0000194 if (isEliminableCastPair(CI, opcode, Ty, TD))
Chris Lattner33a61132006-05-06 09:00:16 +0000195 return false;
196 return true;
197}
198
Chris Lattner4f98c562003-03-10 21:43:22 +0000199// SimplifyCommutative - This performs a few simplifications for commutative
200// operators:
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000201//
Chris Lattner4f98c562003-03-10 21:43:22 +0000202// 1. Order operands such that they are listed from right (least complex) to
203// left (most complex). This puts constants before unary operators before
204// binary operators.
205//
Chris Lattnerc8802d22003-03-11 00:12:48 +0000206// 2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
207// 3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattner4f98c562003-03-10 21:43:22 +0000208//
Chris Lattnerc8802d22003-03-11 00:12:48 +0000209bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +0000210 bool Changed = false;
Dan Gohman14ef4f02009-08-29 23:39:38 +0000211 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
Chris Lattner4f98c562003-03-10 21:43:22 +0000212 Changed = !I.swapOperands();
Misha Brukmanfd939082005-04-21 23:48:37 +0000213
Chris Lattner4f98c562003-03-10 21:43:22 +0000214 if (!I.isAssociative()) return Changed;
215 Instruction::BinaryOps Opcode = I.getOpcode();
Chris Lattnerc8802d22003-03-11 00:12:48 +0000216 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
217 if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
218 if (isa<Constant>(I.getOperand(1))) {
Owen Andersonbaf3c402009-07-29 18:55:55 +0000219 Constant *Folded = ConstantExpr::get(I.getOpcode(),
Chris Lattner2a9c8472003-05-27 16:40:51 +0000220 cast<Constant>(I.getOperand(1)),
221 cast<Constant>(Op->getOperand(1)));
Chris Lattnerc8802d22003-03-11 00:12:48 +0000222 I.setOperand(0, Op->getOperand(0));
223 I.setOperand(1, Folded);
224 return true;
225 } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
226 if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
227 isOnlyUse(Op) && isOnlyUse(Op1)) {
228 Constant *C1 = cast<Constant>(Op->getOperand(1));
229 Constant *C2 = cast<Constant>(Op1->getOperand(1));
230
231 // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Owen Andersonbaf3c402009-07-29 18:55:55 +0000232 Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000233 Instruction *New = BinaryOperator::Create(Opcode, Op->getOperand(0),
Chris Lattnerc8802d22003-03-11 00:12:48 +0000234 Op1->getOperand(0),
235 Op1->getName(), &I);
Chris Lattner7a1e9242009-08-30 06:13:40 +0000236 Worklist.Add(New);
Chris Lattnerc8802d22003-03-11 00:12:48 +0000237 I.setOperand(0, New);
238 I.setOperand(1, Folded);
239 return true;
Misha Brukmanfd939082005-04-21 23:48:37 +0000240 }
Chris Lattner4f98c562003-03-10 21:43:22 +0000241 }
Chris Lattner4f98c562003-03-10 21:43:22 +0000242 return Changed;
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000243}
Chris Lattner8a2a3112001-12-14 16:52:21 +0000244
Chris Lattner8d969642003-03-10 23:06:50 +0000245// dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
246// if the LHS is a constant zero (which is the 'negate' form).
Chris Lattnerb35dde12002-05-06 16:49:18 +0000247//
Dan Gohman186a6362009-08-12 16:04:34 +0000248static inline Value *dyn_castNegVal(Value *V) {
Owen Andersonfa82b6e2009-07-13 22:18:28 +0000249 if (BinaryOperator::isNeg(V))
Chris Lattnera1df33c2005-04-24 07:30:14 +0000250 return BinaryOperator::getNegArgument(V);
Chris Lattner8d969642003-03-10 23:06:50 +0000251
Chris Lattner0ce85802004-12-14 20:08:06 +0000252 // Constants can be considered to be negated values if they can be folded.
253 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
Owen Andersonbaf3c402009-07-29 18:55:55 +0000254 return ConstantExpr::getNeg(C);
Nick Lewycky18b3da62008-05-23 04:54:45 +0000255
256 if (ConstantVector *C = dyn_cast<ConstantVector>(V))
257 if (C->getType()->getElementType()->isInteger())
Owen Andersonbaf3c402009-07-29 18:55:55 +0000258 return ConstantExpr::getNeg(C);
Nick Lewycky18b3da62008-05-23 04:54:45 +0000259
Chris Lattner8d969642003-03-10 23:06:50 +0000260 return 0;
Chris Lattnerb35dde12002-05-06 16:49:18 +0000261}
262
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000263// dyn_castFNegVal - Given a 'fsub' instruction, return the RHS of the
264// instruction if the LHS is a constant negative zero (which is the 'negate'
265// form).
266//
Dan Gohman186a6362009-08-12 16:04:34 +0000267static inline Value *dyn_castFNegVal(Value *V) {
Owen Andersonfa82b6e2009-07-13 22:18:28 +0000268 if (BinaryOperator::isFNeg(V))
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000269 return BinaryOperator::getFNegArgument(V);
270
271 // Constants can be considered to be negated values if they can be folded.
272 if (ConstantFP *C = dyn_cast<ConstantFP>(V))
Owen Andersonbaf3c402009-07-29 18:55:55 +0000273 return ConstantExpr::getFNeg(C);
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000274
275 if (ConstantVector *C = dyn_cast<ConstantVector>(V))
276 if (C->getType()->getElementType()->isFloatingPoint())
Owen Andersonbaf3c402009-07-29 18:55:55 +0000277 return ConstantExpr::getFNeg(C);
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000278
279 return 0;
280}
281
Chris Lattnerb109b5c2009-12-21 06:03:05 +0000282/// MatchSelectPattern - Pattern match integer [SU]MIN, [SU]MAX, and ABS idioms,
283/// returning the kind and providing the out parameter results if we
284/// successfully match.
285static SelectPatternFlavor
286MatchSelectPattern(Value *V, Value *&LHS, Value *&RHS) {
287 SelectInst *SI = dyn_cast<SelectInst>(V);
288 if (SI == 0) return SPF_UNKNOWN;
289
290 ICmpInst *ICI = dyn_cast<ICmpInst>(SI->getCondition());
291 if (ICI == 0) return SPF_UNKNOWN;
292
293 LHS = ICI->getOperand(0);
294 RHS = ICI->getOperand(1);
295
296 // (icmp X, Y) ? X : Y
297 if (SI->getTrueValue() == ICI->getOperand(0) &&
298 SI->getFalseValue() == ICI->getOperand(1)) {
299 switch (ICI->getPredicate()) {
300 default: return SPF_UNKNOWN; // Equality.
301 case ICmpInst::ICMP_UGT:
302 case ICmpInst::ICMP_UGE: return SPF_UMAX;
303 case ICmpInst::ICMP_SGT:
304 case ICmpInst::ICMP_SGE: return SPF_SMAX;
305 case ICmpInst::ICMP_ULT:
306 case ICmpInst::ICMP_ULE: return SPF_UMIN;
307 case ICmpInst::ICMP_SLT:
308 case ICmpInst::ICMP_SLE: return SPF_SMIN;
309 }
310 }
311
312 // (icmp X, Y) ? Y : X
313 if (SI->getTrueValue() == ICI->getOperand(1) &&
314 SI->getFalseValue() == ICI->getOperand(0)) {
315 switch (ICI->getPredicate()) {
316 default: return SPF_UNKNOWN; // Equality.
317 case ICmpInst::ICMP_UGT:
318 case ICmpInst::ICMP_UGE: return SPF_UMIN;
319 case ICmpInst::ICMP_SGT:
320 case ICmpInst::ICMP_SGE: return SPF_SMIN;
321 case ICmpInst::ICMP_ULT:
322 case ICmpInst::ICMP_ULE: return SPF_UMAX;
323 case ICmpInst::ICMP_SLT:
324 case ICmpInst::ICMP_SLE: return SPF_SMAX;
325 }
326 }
327
328 // TODO: (X > 4) ? X : 5 --> (X >= 5) ? X : 5 --> MAX(X, 5)
329
330 return SPF_UNKNOWN;
331}
332
Chris Lattner48b59ec2009-10-26 15:40:07 +0000333/// isFreeToInvert - Return true if the specified value is free to invert (apply
334/// ~ to). This happens in cases where the ~ can be eliminated.
335static inline bool isFreeToInvert(Value *V) {
336 // ~(~(X)) -> X.
Evan Cheng85def162009-10-26 03:51:32 +0000337 if (BinaryOperator::isNot(V))
Chris Lattner48b59ec2009-10-26 15:40:07 +0000338 return true;
339
340 // Constants can be considered to be not'ed values.
341 if (isa<ConstantInt>(V))
342 return true;
343
344 // Compares can be inverted if they have a single use.
345 if (CmpInst *CI = dyn_cast<CmpInst>(V))
346 return CI->hasOneUse();
347
348 return false;
349}
350
351static inline Value *dyn_castNotVal(Value *V) {
352 // If this is not(not(x)) don't return that this is a not: we want the two
353 // not's to be folded first.
354 if (BinaryOperator::isNot(V)) {
355 Value *Operand = BinaryOperator::getNotArgument(V);
356 if (!isFreeToInvert(Operand))
357 return Operand;
358 }
Chris Lattner8d969642003-03-10 23:06:50 +0000359
360 // Constants can be considered to be not'ed values...
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000361 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
Dan Gohman186a6362009-08-12 16:04:34 +0000362 return ConstantInt::get(C->getType(), ~C->getValue());
Chris Lattner8d969642003-03-10 23:06:50 +0000363 return 0;
364}
365
Chris Lattner48b59ec2009-10-26 15:40:07 +0000366
367
Chris Lattnerc8802d22003-03-11 00:12:48 +0000368// dyn_castFoldableMul - If this value is a multiply that can be folded into
369// other computations (because it has a constant operand), return the
Chris Lattner50af16a2004-11-13 19:50:12 +0000370// non-constant operand of the multiply, and set CST to point to the multiplier.
371// Otherwise, return null.
Chris Lattnerc8802d22003-03-11 00:12:48 +0000372//
Dan Gohman186a6362009-08-12 16:04:34 +0000373static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST) {
Chris Lattner42a75512007-01-15 02:27:26 +0000374 if (V->hasOneUse() && V->getType()->isInteger())
Chris Lattner50af16a2004-11-13 19:50:12 +0000375 if (Instruction *I = dyn_cast<Instruction>(V)) {
Chris Lattnerc8802d22003-03-11 00:12:48 +0000376 if (I->getOpcode() == Instruction::Mul)
Chris Lattner50e60c72004-11-15 05:54:07 +0000377 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
Chris Lattnerc8802d22003-03-11 00:12:48 +0000378 return I->getOperand(0);
Chris Lattner50af16a2004-11-13 19:50:12 +0000379 if (I->getOpcode() == Instruction::Shl)
Chris Lattner50e60c72004-11-15 05:54:07 +0000380 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
Chris Lattner50af16a2004-11-13 19:50:12 +0000381 // The multiplier is really 1 << CST.
Zhou Sheng97b52c22007-03-29 01:57:21 +0000382 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +0000383 uint32_t CSTVal = CST->getLimitedValue(BitWidth);
Dan Gohman186a6362009-08-12 16:04:34 +0000384 CST = ConstantInt::get(V->getType()->getContext(),
385 APInt(BitWidth, 1).shl(CSTVal));
Chris Lattner50af16a2004-11-13 19:50:12 +0000386 return I->getOperand(0);
387 }
388 }
Chris Lattnerc8802d22003-03-11 00:12:48 +0000389 return 0;
Chris Lattnera2881962003-02-18 19:28:33 +0000390}
Chris Lattneraf2930e2002-08-14 17:51:49 +0000391
Reid Spencer7177c3a2007-03-25 05:33:51 +0000392/// AddOne - Add one to a ConstantInt
Dan Gohman186a6362009-08-12 16:04:34 +0000393static Constant *AddOne(Constant *C) {
Owen Andersonbaf3c402009-07-29 18:55:55 +0000394 return ConstantExpr::getAdd(C,
Owen Andersoneed707b2009-07-24 23:12:02 +0000395 ConstantInt::get(C->getType(), 1));
Chris Lattner955f3312004-09-28 21:48:02 +0000396}
Reid Spencer7177c3a2007-03-25 05:33:51 +0000397/// SubOne - Subtract one from a ConstantInt
Dan Gohman186a6362009-08-12 16:04:34 +0000398static Constant *SubOne(ConstantInt *C) {
Owen Andersonbaf3c402009-07-29 18:55:55 +0000399 return ConstantExpr::getSub(C,
Owen Andersoneed707b2009-07-24 23:12:02 +0000400 ConstantInt::get(C->getType(), 1));
Chris Lattner955f3312004-09-28 21:48:02 +0000401}
Nick Lewyckye0cfecf2008-02-18 22:48:05 +0000402/// MultiplyOverflows - True if the multiply can not be expressed in an int
403/// this size.
Dan Gohman186a6362009-08-12 16:04:34 +0000404static bool MultiplyOverflows(ConstantInt *C1, ConstantInt *C2, bool sign) {
Nick Lewyckye0cfecf2008-02-18 22:48:05 +0000405 uint32_t W = C1->getBitWidth();
406 APInt LHSExt = C1->getValue(), RHSExt = C2->getValue();
407 if (sign) {
408 LHSExt.sext(W * 2);
409 RHSExt.sext(W * 2);
410 } else {
411 LHSExt.zext(W * 2);
412 RHSExt.zext(W * 2);
413 }
414
415 APInt MulExt = LHSExt * RHSExt;
416
Chris Lattnerb109b5c2009-12-21 06:03:05 +0000417 if (!sign)
Nick Lewyckye0cfecf2008-02-18 22:48:05 +0000418 return MulExt.ugt(APInt::getLowBitsSet(W * 2, W));
Chris Lattnerb109b5c2009-12-21 06:03:05 +0000419
420 APInt Min = APInt::getSignedMinValue(W).sext(W * 2);
421 APInt Max = APInt::getSignedMaxValue(W).sext(W * 2);
422 return MulExt.slt(Min) || MulExt.sgt(Max);
Nick Lewyckye0cfecf2008-02-18 22:48:05 +0000423}
Chris Lattner955f3312004-09-28 21:48:02 +0000424
Reid Spencere7816b52007-03-08 01:52:58 +0000425
Chris Lattner255d8912006-02-11 09:31:47 +0000426/// ShrinkDemandedConstant - Check to see if the specified operand of the
427/// specified instruction is a constant integer. If so, check to see if there
428/// are any bits set in the constant that are not demanded. If so, shrink the
429/// constant and return true.
430static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo,
Dan Gohman186a6362009-08-12 16:04:34 +0000431 APInt Demanded) {
Reid Spencer6b79e2d2007-03-12 17:15:10 +0000432 assert(I && "No instruction?");
433 assert(OpNo < I->getNumOperands() && "Operand index too large");
434
435 // If the operand is not a constant integer, nothing to do.
436 ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
437 if (!OpC) return false;
438
439 // If there are no bits set that aren't demanded, nothing to do.
440 Demanded.zextOrTrunc(OpC->getValue().getBitWidth());
441 if ((~Demanded & OpC->getValue()) == 0)
442 return false;
443
444 // This instruction is producing bits that are not demanded. Shrink the RHS.
445 Demanded &= OpC->getValue();
Dan Gohman186a6362009-08-12 16:04:34 +0000446 I->setOperand(OpNo, ConstantInt::get(OpC->getType(), Demanded));
Reid Spencer6b79e2d2007-03-12 17:15:10 +0000447 return true;
448}
449
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000450// ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a
451// set of known zero and one bits, compute the maximum and minimum values that
452// could have the specified known zero and known one bits, returning them in
453// min/max.
Dan Gohman1c8491e2009-04-25 17:12:48 +0000454static void ComputeSignedMinMaxValuesFromKnownBits(const APInt& KnownZero,
Reid Spencer0460fb32007-03-22 20:36:03 +0000455 const APInt& KnownOne,
456 APInt& Min, APInt& Max) {
Dan Gohman1c8491e2009-04-25 17:12:48 +0000457 assert(KnownZero.getBitWidth() == KnownOne.getBitWidth() &&
458 KnownZero.getBitWidth() == Min.getBitWidth() &&
459 KnownZero.getBitWidth() == Max.getBitWidth() &&
460 "KnownZero, KnownOne and Min, Max must have equal bitwidth.");
Reid Spencer2f549172007-03-25 04:26:16 +0000461 APInt UnknownBits = ~(KnownZero|KnownOne);
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000462
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000463 // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
464 // bit if it is unknown.
465 Min = KnownOne;
466 Max = KnownOne|UnknownBits;
467
Dan Gohman1c8491e2009-04-25 17:12:48 +0000468 if (UnknownBits.isNegative()) { // Sign bit is unknown
469 Min.set(Min.getBitWidth()-1);
470 Max.clear(Max.getBitWidth()-1);
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000471 }
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000472}
473
474// ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
475// a set of known zero and one bits, compute the maximum and minimum values that
476// could have the specified known zero and known one bits, returning them in
477// min/max.
Dan Gohman1c8491e2009-04-25 17:12:48 +0000478static void ComputeUnsignedMinMaxValuesFromKnownBits(const APInt &KnownZero,
Chris Lattnera9ff5eb2007-08-05 08:47:58 +0000479 const APInt &KnownOne,
480 APInt &Min, APInt &Max) {
Dan Gohman1c8491e2009-04-25 17:12:48 +0000481 assert(KnownZero.getBitWidth() == KnownOne.getBitWidth() &&
482 KnownZero.getBitWidth() == Min.getBitWidth() &&
483 KnownZero.getBitWidth() == Max.getBitWidth() &&
Reid Spencer0460fb32007-03-22 20:36:03 +0000484 "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
Reid Spencer2f549172007-03-25 04:26:16 +0000485 APInt UnknownBits = ~(KnownZero|KnownOne);
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000486
487 // The minimum value is when the unknown bits are all zeros.
488 Min = KnownOne;
489 // The maximum value is when the unknown bits are all ones.
490 Max = KnownOne|UnknownBits;
491}
Chris Lattner255d8912006-02-11 09:31:47 +0000492
Chris Lattner886ab6c2009-01-31 08:15:18 +0000493/// SimplifyDemandedInstructionBits - Inst is an integer instruction that
494/// SimplifyDemandedBits knows about. See if the instruction has any
495/// properties that allow us to simplify its operands.
496bool InstCombiner::SimplifyDemandedInstructionBits(Instruction &Inst) {
Dan Gohman6de29f82009-06-15 22:12:54 +0000497 unsigned BitWidth = Inst.getType()->getScalarSizeInBits();
Chris Lattner886ab6c2009-01-31 08:15:18 +0000498 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
499 APInt DemandedMask(APInt::getAllOnesValue(BitWidth));
500
501 Value *V = SimplifyDemandedUseBits(&Inst, DemandedMask,
502 KnownZero, KnownOne, 0);
503 if (V == 0) return false;
504 if (V == &Inst) return true;
505 ReplaceInstUsesWith(Inst, V);
506 return true;
507}
508
509/// SimplifyDemandedBits - This form of SimplifyDemandedBits simplifies the
510/// specified instruction operand if possible, updating it in place. It returns
511/// true if it made any change and false otherwise.
512bool InstCombiner::SimplifyDemandedBits(Use &U, APInt DemandedMask,
513 APInt &KnownZero, APInt &KnownOne,
514 unsigned Depth) {
515 Value *NewVal = SimplifyDemandedUseBits(U.get(), DemandedMask,
516 KnownZero, KnownOne, Depth);
517 if (NewVal == 0) return false;
Dan Gohmane41a1152009-10-05 16:31:55 +0000518 U = NewVal;
Chris Lattner886ab6c2009-01-31 08:15:18 +0000519 return true;
520}
521
522
523/// SimplifyDemandedUseBits - This function attempts to replace V with a simpler
524/// value based on the demanded bits. When this function is called, it is known
Reid Spencer8cb68342007-03-12 17:25:59 +0000525/// that only the bits set in DemandedMask of the result of V are ever used
526/// downstream. Consequently, depending on the mask and V, it may be possible
527/// to replace V with a constant or one of its operands. In such cases, this
528/// function does the replacement and returns true. In all other cases, it
529/// returns false after analyzing the expression and setting KnownOne and known
Chris Lattner886ab6c2009-01-31 08:15:18 +0000530/// to be one in the expression. KnownZero contains all the bits that are known
Reid Spencer8cb68342007-03-12 17:25:59 +0000531/// to be zero in the expression. These are provided to potentially allow the
532/// caller (which might recursively be SimplifyDemandedBits itself) to simplify
533/// the expression. KnownOne and KnownZero always follow the invariant that
534/// KnownOne & KnownZero == 0. That is, a bit can't be both 1 and 0. Note that
535/// the bits in KnownOne and KnownZero may only be accurate for those bits set
536/// in DemandedMask. Note also that the bitwidth of V, DemandedMask, KnownZero
537/// and KnownOne must all be the same.
Chris Lattner886ab6c2009-01-31 08:15:18 +0000538///
539/// This returns null if it did not change anything and it permits no
540/// simplification. This returns V itself if it did some simplification of V's
541/// operands based on the information about what bits are demanded. This returns
542/// some other non-null value if it found out that V is equal to another value
543/// in the context where the specified bits are demanded, but not for all users.
544Value *InstCombiner::SimplifyDemandedUseBits(Value *V, APInt DemandedMask,
545 APInt &KnownZero, APInt &KnownOne,
546 unsigned Depth) {
Reid Spencer8cb68342007-03-12 17:25:59 +0000547 assert(V != 0 && "Null pointer of Value???");
548 assert(Depth <= 6 && "Limit Search Depth");
549 uint32_t BitWidth = DemandedMask.getBitWidth();
Dan Gohman1c8491e2009-04-25 17:12:48 +0000550 const Type *VTy = V->getType();
551 assert((TD || !isa<PointerType>(VTy)) &&
552 "SimplifyDemandedBits needs to know bit widths!");
Dan Gohman6de29f82009-06-15 22:12:54 +0000553 assert((!TD || TD->getTypeSizeInBits(VTy->getScalarType()) == BitWidth) &&
554 (!VTy->isIntOrIntVector() ||
555 VTy->getScalarSizeInBits() == BitWidth) &&
Dan Gohman1c8491e2009-04-25 17:12:48 +0000556 KnownZero.getBitWidth() == BitWidth &&
Reid Spencer8cb68342007-03-12 17:25:59 +0000557 KnownOne.getBitWidth() == BitWidth &&
Dan Gohman6de29f82009-06-15 22:12:54 +0000558 "Value *V, DemandedMask, KnownZero and KnownOne "
559 "must have same BitWidth");
Reid Spencer8cb68342007-03-12 17:25:59 +0000560 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
561 // We know all of the bits for a constant!
562 KnownOne = CI->getValue() & DemandedMask;
563 KnownZero = ~KnownOne & DemandedMask;
Chris Lattner886ab6c2009-01-31 08:15:18 +0000564 return 0;
Reid Spencer8cb68342007-03-12 17:25:59 +0000565 }
Dan Gohman1c8491e2009-04-25 17:12:48 +0000566 if (isa<ConstantPointerNull>(V)) {
567 // We know all of the bits for a constant!
568 KnownOne.clear();
569 KnownZero = DemandedMask;
570 return 0;
571 }
572
Chris Lattner08d2cc72009-01-31 07:26:06 +0000573 KnownZero.clear();
Zhou Sheng96704452007-03-14 03:21:24 +0000574 KnownOne.clear();
Chris Lattner886ab6c2009-01-31 08:15:18 +0000575 if (DemandedMask == 0) { // Not demanding any bits from V.
576 if (isa<UndefValue>(V))
577 return 0;
Owen Anderson9e9a0d52009-07-30 23:03:37 +0000578 return UndefValue::get(VTy);
Reid Spencer8cb68342007-03-12 17:25:59 +0000579 }
580
Chris Lattner4598c942009-01-31 08:24:16 +0000581 if (Depth == 6) // Limit search depth.
582 return 0;
583
Chris Lattnerd1b5e3f2009-01-31 08:40:03 +0000584 APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
585 APInt &RHSKnownZero = KnownZero, &RHSKnownOne = KnownOne;
586
Dan Gohman1c8491e2009-04-25 17:12:48 +0000587 Instruction *I = dyn_cast<Instruction>(V);
588 if (!I) {
589 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
590 return 0; // Only analyze instructions.
591 }
592
Chris Lattner4598c942009-01-31 08:24:16 +0000593 // If there are multiple uses of this value and we aren't at the root, then
594 // we can't do any simplifications of the operands, because DemandedMask
595 // only reflects the bits demanded by *one* of the users.
596 if (Depth != 0 && !I->hasOneUse()) {
Chris Lattnerd1b5e3f2009-01-31 08:40:03 +0000597 // Despite the fact that we can't simplify this instruction in all User's
598 // context, we can at least compute the knownzero/knownone bits, and we can
599 // do simplifications that apply to *just* the one user if we know that
600 // this instruction has a simpler value in that context.
601 if (I->getOpcode() == Instruction::And) {
602 // If either the LHS or the RHS are Zero, the result is zero.
603 ComputeMaskedBits(I->getOperand(1), DemandedMask,
604 RHSKnownZero, RHSKnownOne, Depth+1);
605 ComputeMaskedBits(I->getOperand(0), DemandedMask & ~RHSKnownZero,
606 LHSKnownZero, LHSKnownOne, Depth+1);
607
608 // If all of the demanded bits are known 1 on one side, return the other.
609 // These bits cannot contribute to the result of the 'and' in this
610 // context.
611 if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) ==
612 (DemandedMask & ~LHSKnownZero))
613 return I->getOperand(0);
614 if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) ==
615 (DemandedMask & ~RHSKnownZero))
616 return I->getOperand(1);
617
618 // If all of the demanded bits in the inputs are known zeros, return zero.
619 if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
Owen Andersona7235ea2009-07-31 20:28:14 +0000620 return Constant::getNullValue(VTy);
Chris Lattnerd1b5e3f2009-01-31 08:40:03 +0000621
622 } else if (I->getOpcode() == Instruction::Or) {
623 // We can simplify (X|Y) -> X or Y in the user's context if we know that
624 // only bits from X or Y are demanded.
625
626 // If either the LHS or the RHS are One, the result is One.
627 ComputeMaskedBits(I->getOperand(1), DemandedMask,
628 RHSKnownZero, RHSKnownOne, Depth+1);
629 ComputeMaskedBits(I->getOperand(0), DemandedMask & ~RHSKnownOne,
630 LHSKnownZero, LHSKnownOne, Depth+1);
631
632 // If all of the demanded bits are known zero on one side, return the
633 // other. These bits cannot contribute to the result of the 'or' in this
634 // context.
635 if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) ==
636 (DemandedMask & ~LHSKnownOne))
637 return I->getOperand(0);
638 if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) ==
639 (DemandedMask & ~RHSKnownOne))
640 return I->getOperand(1);
641
642 // If all of the potentially set bits on one side are known to be set on
643 // the other side, just use the 'other' side.
644 if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) ==
645 (DemandedMask & (~RHSKnownZero)))
646 return I->getOperand(0);
647 if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) ==
648 (DemandedMask & (~LHSKnownZero)))
649 return I->getOperand(1);
650 }
651
Chris Lattner4598c942009-01-31 08:24:16 +0000652 // Compute the KnownZero/KnownOne bits to simplify things downstream.
653 ComputeMaskedBits(I, DemandedMask, KnownZero, KnownOne, Depth);
654 return 0;
655 }
656
657 // If this is the root being simplified, allow it to have multiple uses,
658 // just set the DemandedMask to all bits so that we can try to simplify the
659 // operands. This allows visitTruncInst (for example) to simplify the
660 // operand of a trunc without duplicating all the logic below.
661 if (Depth == 0 && !V->hasOneUse())
662 DemandedMask = APInt::getAllOnesValue(BitWidth);
663
Reid Spencer8cb68342007-03-12 17:25:59 +0000664 switch (I->getOpcode()) {
Dan Gohman23e8b712008-04-28 17:02:21 +0000665 default:
Chris Lattner886ab6c2009-01-31 08:15:18 +0000666 ComputeMaskedBits(I, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
Dan Gohman23e8b712008-04-28 17:02:21 +0000667 break;
Reid Spencer8cb68342007-03-12 17:25:59 +0000668 case Instruction::And:
669 // If either the LHS or the RHS are Zero, the result is zero.
Chris Lattner886ab6c2009-01-31 08:15:18 +0000670 if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
671 RHSKnownZero, RHSKnownOne, Depth+1) ||
672 SimplifyDemandedBits(I->getOperandUse(0), DemandedMask & ~RHSKnownZero,
Reid Spencer8cb68342007-03-12 17:25:59 +0000673 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000674 return I;
675 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
676 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +0000677
678 // If all of the demanded bits are known 1 on one side, return the other.
679 // These bits cannot contribute to the result of the 'and'.
680 if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) ==
681 (DemandedMask & ~LHSKnownZero))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000682 return I->getOperand(0);
Reid Spencer8cb68342007-03-12 17:25:59 +0000683 if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) ==
684 (DemandedMask & ~RHSKnownZero))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000685 return I->getOperand(1);
Reid Spencer8cb68342007-03-12 17:25:59 +0000686
687 // If all of the demanded bits in the inputs are known zeros, return zero.
688 if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
Owen Andersona7235ea2009-07-31 20:28:14 +0000689 return Constant::getNullValue(VTy);
Reid Spencer8cb68342007-03-12 17:25:59 +0000690
691 // If the RHS is a constant, see if we can simplify it.
Dan Gohman186a6362009-08-12 16:04:34 +0000692 if (ShrinkDemandedConstant(I, 1, DemandedMask & ~LHSKnownZero))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000693 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +0000694
695 // Output known-1 bits are only known if set in both the LHS & RHS.
696 RHSKnownOne &= LHSKnownOne;
697 // Output known-0 are known to be clear if zero in either the LHS | RHS.
698 RHSKnownZero |= LHSKnownZero;
699 break;
700 case Instruction::Or:
701 // If either the LHS or the RHS are One, the result is One.
Chris Lattner886ab6c2009-01-31 08:15:18 +0000702 if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
703 RHSKnownZero, RHSKnownOne, Depth+1) ||
704 SimplifyDemandedBits(I->getOperandUse(0), DemandedMask & ~RHSKnownOne,
Reid Spencer8cb68342007-03-12 17:25:59 +0000705 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000706 return I;
707 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
708 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +0000709
710 // If all of the demanded bits are known zero on one side, return the other.
711 // These bits cannot contribute to the result of the 'or'.
712 if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) ==
713 (DemandedMask & ~LHSKnownOne))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000714 return I->getOperand(0);
Reid Spencer8cb68342007-03-12 17:25:59 +0000715 if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) ==
716 (DemandedMask & ~RHSKnownOne))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000717 return I->getOperand(1);
Reid Spencer8cb68342007-03-12 17:25:59 +0000718
719 // If all of the potentially set bits on one side are known to be set on
720 // the other side, just use the 'other' side.
721 if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) ==
722 (DemandedMask & (~RHSKnownZero)))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000723 return I->getOperand(0);
Reid Spencer8cb68342007-03-12 17:25:59 +0000724 if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) ==
725 (DemandedMask & (~LHSKnownZero)))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000726 return I->getOperand(1);
Reid Spencer8cb68342007-03-12 17:25:59 +0000727
728 // If the RHS is a constant, see if we can simplify it.
Dan Gohman186a6362009-08-12 16:04:34 +0000729 if (ShrinkDemandedConstant(I, 1, DemandedMask))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000730 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +0000731
732 // Output known-0 bits are only known if clear in both the LHS & RHS.
733 RHSKnownZero &= LHSKnownZero;
734 // Output known-1 are known to be set if set in either the LHS | RHS.
735 RHSKnownOne |= LHSKnownOne;
736 break;
737 case Instruction::Xor: {
Chris Lattner886ab6c2009-01-31 08:15:18 +0000738 if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
739 RHSKnownZero, RHSKnownOne, Depth+1) ||
740 SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
Reid Spencer8cb68342007-03-12 17:25:59 +0000741 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000742 return I;
743 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
744 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +0000745
746 // If all of the demanded bits are known zero on one side, return the other.
747 // These bits cannot contribute to the result of the 'xor'.
748 if ((DemandedMask & RHSKnownZero) == DemandedMask)
Chris Lattner886ab6c2009-01-31 08:15:18 +0000749 return I->getOperand(0);
Reid Spencer8cb68342007-03-12 17:25:59 +0000750 if ((DemandedMask & LHSKnownZero) == DemandedMask)
Chris Lattner886ab6c2009-01-31 08:15:18 +0000751 return I->getOperand(1);
Reid Spencer8cb68342007-03-12 17:25:59 +0000752
753 // Output known-0 bits are known if clear or set in both the LHS & RHS.
754 APInt KnownZeroOut = (RHSKnownZero & LHSKnownZero) |
755 (RHSKnownOne & LHSKnownOne);
756 // Output known-1 are known to be set if set in only one of the LHS, RHS.
757 APInt KnownOneOut = (RHSKnownZero & LHSKnownOne) |
758 (RHSKnownOne & LHSKnownZero);
759
760 // If all of the demanded bits are known to be zero on one side or the
761 // other, turn this into an *inclusive* or.
762 // e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
Chris Lattner95afdfe2009-08-31 04:36:22 +0000763 if ((DemandedMask & ~RHSKnownZero & ~LHSKnownZero) == 0) {
764 Instruction *Or =
765 BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
766 I->getName());
767 return InsertNewInstBefore(Or, *I);
768 }
Reid Spencer8cb68342007-03-12 17:25:59 +0000769
770 // If all of the demanded bits on one side are known, and all of the set
771 // bits on that side are also known to be set on the other side, turn this
772 // into an AND, as we know the bits will be cleared.
773 // e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
774 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask) {
775 // all known
776 if ((RHSKnownOne & LHSKnownOne) == RHSKnownOne) {
Dan Gohman43ee5f72009-08-03 22:07:33 +0000777 Constant *AndC = Constant::getIntegerValue(VTy,
778 ~RHSKnownOne & DemandedMask);
Reid Spencer8cb68342007-03-12 17:25:59 +0000779 Instruction *And =
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000780 BinaryOperator::CreateAnd(I->getOperand(0), AndC, "tmp");
Chris Lattner886ab6c2009-01-31 08:15:18 +0000781 return InsertNewInstBefore(And, *I);
Reid Spencer8cb68342007-03-12 17:25:59 +0000782 }
783 }
784
785 // If the RHS is a constant, see if we can simplify it.
786 // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
Dan Gohman186a6362009-08-12 16:04:34 +0000787 if (ShrinkDemandedConstant(I, 1, DemandedMask))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000788 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +0000789
Chris Lattnerd0883142009-10-11 22:22:13 +0000790 // If our LHS is an 'and' and if it has one use, and if any of the bits we
791 // are flipping are known to be set, then the xor is just resetting those
792 // bits to zero. We can just knock out bits from the 'and' and the 'xor',
793 // simplifying both of them.
794 if (Instruction *LHSInst = dyn_cast<Instruction>(I->getOperand(0)))
795 if (LHSInst->getOpcode() == Instruction::And && LHSInst->hasOneUse() &&
796 isa<ConstantInt>(I->getOperand(1)) &&
797 isa<ConstantInt>(LHSInst->getOperand(1)) &&
798 (LHSKnownOne & RHSKnownOne & DemandedMask) != 0) {
799 ConstantInt *AndRHS = cast<ConstantInt>(LHSInst->getOperand(1));
800 ConstantInt *XorRHS = cast<ConstantInt>(I->getOperand(1));
801 APInt NewMask = ~(LHSKnownOne & RHSKnownOne & DemandedMask);
802
803 Constant *AndC =
804 ConstantInt::get(I->getType(), NewMask & AndRHS->getValue());
805 Instruction *NewAnd =
806 BinaryOperator::CreateAnd(I->getOperand(0), AndC, "tmp");
807 InsertNewInstBefore(NewAnd, *I);
808
809 Constant *XorC =
810 ConstantInt::get(I->getType(), NewMask & XorRHS->getValue());
811 Instruction *NewXor =
812 BinaryOperator::CreateXor(NewAnd, XorC, "tmp");
813 return InsertNewInstBefore(NewXor, *I);
814 }
815
816
Reid Spencer8cb68342007-03-12 17:25:59 +0000817 RHSKnownZero = KnownZeroOut;
818 RHSKnownOne = KnownOneOut;
819 break;
820 }
821 case Instruction::Select:
Chris Lattner886ab6c2009-01-31 08:15:18 +0000822 if (SimplifyDemandedBits(I->getOperandUse(2), DemandedMask,
823 RHSKnownZero, RHSKnownOne, Depth+1) ||
824 SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
Reid Spencer8cb68342007-03-12 17:25:59 +0000825 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000826 return I;
827 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
828 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +0000829
830 // If the operands are constants, see if we can simplify them.
Dan Gohman186a6362009-08-12 16:04:34 +0000831 if (ShrinkDemandedConstant(I, 1, DemandedMask) ||
832 ShrinkDemandedConstant(I, 2, DemandedMask))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000833 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +0000834
835 // Only known if known in both the LHS and RHS.
836 RHSKnownOne &= LHSKnownOne;
837 RHSKnownZero &= LHSKnownZero;
838 break;
839 case Instruction::Trunc: {
Dan Gohman6de29f82009-06-15 22:12:54 +0000840 unsigned truncBf = I->getOperand(0)->getType()->getScalarSizeInBits();
Zhou Sheng01542f32007-03-29 02:26:30 +0000841 DemandedMask.zext(truncBf);
842 RHSKnownZero.zext(truncBf);
843 RHSKnownOne.zext(truncBf);
Chris Lattner886ab6c2009-01-31 08:15:18 +0000844 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
Zhou Sheng01542f32007-03-29 02:26:30 +0000845 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000846 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +0000847 DemandedMask.trunc(BitWidth);
848 RHSKnownZero.trunc(BitWidth);
849 RHSKnownOne.trunc(BitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +0000850 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +0000851 break;
852 }
853 case Instruction::BitCast:
Dan Gohman6cc18fe2009-07-01 21:38:46 +0000854 if (!I->getOperand(0)->getType()->isIntOrIntVector())
Chris Lattner886ab6c2009-01-31 08:15:18 +0000855 return false; // vector->int or fp->int?
Dan Gohman6cc18fe2009-07-01 21:38:46 +0000856
857 if (const VectorType *DstVTy = dyn_cast<VectorType>(I->getType())) {
858 if (const VectorType *SrcVTy =
859 dyn_cast<VectorType>(I->getOperand(0)->getType())) {
860 if (DstVTy->getNumElements() != SrcVTy->getNumElements())
861 // Don't touch a bitcast between vectors of different element counts.
862 return false;
863 } else
864 // Don't touch a scalar-to-vector bitcast.
865 return false;
866 } else if (isa<VectorType>(I->getOperand(0)->getType()))
867 // Don't touch a vector-to-scalar bitcast.
868 return false;
869
Chris Lattner886ab6c2009-01-31 08:15:18 +0000870 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
Reid Spencer8cb68342007-03-12 17:25:59 +0000871 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000872 return I;
873 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +0000874 break;
875 case Instruction::ZExt: {
876 // Compute the bits in the result that are not present in the input.
Dan Gohman6de29f82009-06-15 22:12:54 +0000877 unsigned SrcBitWidth =I->getOperand(0)->getType()->getScalarSizeInBits();
Reid Spencer8cb68342007-03-12 17:25:59 +0000878
Zhou Shengd48653a2007-03-29 04:45:55 +0000879 DemandedMask.trunc(SrcBitWidth);
880 RHSKnownZero.trunc(SrcBitWidth);
881 RHSKnownOne.trunc(SrcBitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +0000882 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
Zhou Sheng01542f32007-03-29 02:26:30 +0000883 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000884 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +0000885 DemandedMask.zext(BitWidth);
886 RHSKnownZero.zext(BitWidth);
887 RHSKnownOne.zext(BitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +0000888 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +0000889 // The top bits are known to be zero.
Zhou Sheng01542f32007-03-29 02:26:30 +0000890 RHSKnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +0000891 break;
892 }
893 case Instruction::SExt: {
894 // Compute the bits in the result that are not present in the input.
Dan Gohman6de29f82009-06-15 22:12:54 +0000895 unsigned SrcBitWidth =I->getOperand(0)->getType()->getScalarSizeInBits();
Reid Spencer8cb68342007-03-12 17:25:59 +0000896
Reid Spencer8cb68342007-03-12 17:25:59 +0000897 APInt InputDemandedBits = DemandedMask &
Zhou Sheng01542f32007-03-29 02:26:30 +0000898 APInt::getLowBitsSet(BitWidth, SrcBitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +0000899
Zhou Sheng01542f32007-03-29 02:26:30 +0000900 APInt NewBits(APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth));
Reid Spencer8cb68342007-03-12 17:25:59 +0000901 // If any of the sign extended bits are demanded, we know that the sign
902 // bit is demanded.
903 if ((NewBits & DemandedMask) != 0)
Zhou Sheng4a1822a2007-04-02 13:45:30 +0000904 InputDemandedBits.set(SrcBitWidth-1);
Reid Spencer8cb68342007-03-12 17:25:59 +0000905
Zhou Shengd48653a2007-03-29 04:45:55 +0000906 InputDemandedBits.trunc(SrcBitWidth);
907 RHSKnownZero.trunc(SrcBitWidth);
908 RHSKnownOne.trunc(SrcBitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +0000909 if (SimplifyDemandedBits(I->getOperandUse(0), InputDemandedBits,
Zhou Sheng01542f32007-03-29 02:26:30 +0000910 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000911 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +0000912 InputDemandedBits.zext(BitWidth);
913 RHSKnownZero.zext(BitWidth);
914 RHSKnownOne.zext(BitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +0000915 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +0000916
917 // If the sign bit of the input is known set or clear, then we know the
918 // top bits of the result.
919
920 // If the input sign bit is known zero, or if the NewBits are not demanded
921 // convert this into a zero extension.
Chris Lattner886ab6c2009-01-31 08:15:18 +0000922 if (RHSKnownZero[SrcBitWidth-1] || (NewBits & ~DemandedMask) == NewBits) {
Reid Spencer8cb68342007-03-12 17:25:59 +0000923 // Convert to ZExt cast
Chris Lattner886ab6c2009-01-31 08:15:18 +0000924 CastInst *NewCast = new ZExtInst(I->getOperand(0), VTy, I->getName());
925 return InsertNewInstBefore(NewCast, *I);
Zhou Sheng01542f32007-03-29 02:26:30 +0000926 } else if (RHSKnownOne[SrcBitWidth-1]) { // Input sign bit known set
Reid Spencer8cb68342007-03-12 17:25:59 +0000927 RHSKnownOne |= NewBits;
Reid Spencer8cb68342007-03-12 17:25:59 +0000928 }
929 break;
930 }
931 case Instruction::Add: {
932 // Figure out what the input bits are. If the top bits of the and result
933 // are not demanded, then the add doesn't demand them from its input
934 // either.
Chris Lattner886ab6c2009-01-31 08:15:18 +0000935 unsigned NLZ = DemandedMask.countLeadingZeros();
Reid Spencer8cb68342007-03-12 17:25:59 +0000936
937 // If there is a constant on the RHS, there are a variety of xformations
938 // we can do.
939 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
940 // If null, this should be simplified elsewhere. Some of the xforms here
941 // won't work if the RHS is zero.
942 if (RHS->isZero())
943 break;
944
945 // If the top bit of the output is demanded, demand everything from the
946 // input. Otherwise, we demand all the input bits except NLZ top bits.
Zhou Sheng01542f32007-03-29 02:26:30 +0000947 APInt InDemandedBits(APInt::getLowBitsSet(BitWidth, BitWidth - NLZ));
Reid Spencer8cb68342007-03-12 17:25:59 +0000948
949 // Find information about known zero/one bits in the input.
Chris Lattner886ab6c2009-01-31 08:15:18 +0000950 if (SimplifyDemandedBits(I->getOperandUse(0), InDemandedBits,
Reid Spencer8cb68342007-03-12 17:25:59 +0000951 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000952 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +0000953
954 // If the RHS of the add has bits set that can't affect the input, reduce
955 // the constant.
Dan Gohman186a6362009-08-12 16:04:34 +0000956 if (ShrinkDemandedConstant(I, 1, InDemandedBits))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000957 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +0000958
959 // Avoid excess work.
960 if (LHSKnownZero == 0 && LHSKnownOne == 0)
961 break;
962
963 // Turn it into OR if input bits are zero.
964 if ((LHSKnownZero & RHS->getValue()) == RHS->getValue()) {
965 Instruction *Or =
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000966 BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
Reid Spencer8cb68342007-03-12 17:25:59 +0000967 I->getName());
Chris Lattner886ab6c2009-01-31 08:15:18 +0000968 return InsertNewInstBefore(Or, *I);
Reid Spencer8cb68342007-03-12 17:25:59 +0000969 }
970
971 // We can say something about the output known-zero and known-one bits,
972 // depending on potential carries from the input constant and the
973 // unknowns. For example if the LHS is known to have at most the 0x0F0F0
974 // bits set and the RHS constant is 0x01001, then we know we have a known
975 // one mask of 0x00001 and a known zero mask of 0xE0F0E.
976
977 // To compute this, we first compute the potential carry bits. These are
978 // the bits which may be modified. I'm not aware of a better way to do
979 // this scan.
Chris Lattner886ab6c2009-01-31 08:15:18 +0000980 const APInt &RHSVal = RHS->getValue();
Zhou Shengb9cb95f2007-03-31 02:38:39 +0000981 APInt CarryBits((~LHSKnownZero + RHSVal) ^ (~LHSKnownZero ^ RHSVal));
Reid Spencer8cb68342007-03-12 17:25:59 +0000982
983 // Now that we know which bits have carries, compute the known-1/0 sets.
984
985 // Bits are known one if they are known zero in one operand and one in the
986 // other, and there is no input carry.
987 RHSKnownOne = ((LHSKnownZero & RHSVal) |
988 (LHSKnownOne & ~RHSVal)) & ~CarryBits;
989
990 // Bits are known zero if they are known zero in both operands and there
991 // is no input carry.
992 RHSKnownZero = LHSKnownZero & ~RHSVal & ~CarryBits;
993 } else {
994 // If the high-bits of this ADD are not demanded, then it does not demand
995 // the high bits of its LHS or RHS.
Zhou Sheng01542f32007-03-29 02:26:30 +0000996 if (DemandedMask[BitWidth-1] == 0) {
Reid Spencer8cb68342007-03-12 17:25:59 +0000997 // Right fill the mask of bits for this ADD to demand the most
998 // significant bit and all those below it.
Zhou Sheng01542f32007-03-29 02:26:30 +0000999 APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
Chris Lattner886ab6c2009-01-31 08:15:18 +00001000 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedFromOps,
1001 LHSKnownZero, LHSKnownOne, Depth+1) ||
1002 SimplifyDemandedBits(I->getOperandUse(1), DemandedFromOps,
Reid Spencer8cb68342007-03-12 17:25:59 +00001003 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001004 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001005 }
1006 }
1007 break;
1008 }
1009 case Instruction::Sub:
1010 // If the high-bits of this SUB are not demanded, then it does not demand
1011 // the high bits of its LHS or RHS.
Zhou Sheng01542f32007-03-29 02:26:30 +00001012 if (DemandedMask[BitWidth-1] == 0) {
Reid Spencer8cb68342007-03-12 17:25:59 +00001013 // Right fill the mask of bits for this SUB to demand the most
1014 // significant bit and all those below it.
Zhou Sheng4351c642007-04-02 08:20:41 +00001015 uint32_t NLZ = DemandedMask.countLeadingZeros();
Zhou Sheng01542f32007-03-29 02:26:30 +00001016 APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
Chris Lattner886ab6c2009-01-31 08:15:18 +00001017 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedFromOps,
1018 LHSKnownZero, LHSKnownOne, Depth+1) ||
1019 SimplifyDemandedBits(I->getOperandUse(1), DemandedFromOps,
Reid Spencer8cb68342007-03-12 17:25:59 +00001020 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001021 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001022 }
Dan Gohman23e8b712008-04-28 17:02:21 +00001023 // Otherwise just hand the sub off to ComputeMaskedBits to fill in
1024 // the known zeros and ones.
1025 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001026 break;
1027 case Instruction::Shl:
1028 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00001029 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
Zhou Sheng01542f32007-03-29 02:26:30 +00001030 APInt DemandedMaskIn(DemandedMask.lshr(ShiftAmt));
Chris Lattner886ab6c2009-01-31 08:15:18 +00001031 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
Reid Spencer8cb68342007-03-12 17:25:59 +00001032 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001033 return I;
1034 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001035 RHSKnownZero <<= ShiftAmt;
1036 RHSKnownOne <<= ShiftAmt;
1037 // low bits known zero.
Zhou Shengadc14952007-03-14 09:07:33 +00001038 if (ShiftAmt)
Zhou Shenge9e03f62007-03-28 15:02:20 +00001039 RHSKnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt);
Reid Spencer8cb68342007-03-12 17:25:59 +00001040 }
1041 break;
1042 case Instruction::LShr:
1043 // For a logical shift right
1044 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00001045 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001046
Reid Spencer8cb68342007-03-12 17:25:59 +00001047 // Unsigned shift right.
Zhou Sheng01542f32007-03-29 02:26:30 +00001048 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
Chris Lattner886ab6c2009-01-31 08:15:18 +00001049 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
Reid Spencer8cb68342007-03-12 17:25:59 +00001050 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001051 return I;
1052 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001053 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1054 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
Zhou Shengadc14952007-03-14 09:07:33 +00001055 if (ShiftAmt) {
1056 // Compute the new bits that are at the top now.
Zhou Sheng01542f32007-03-29 02:26:30 +00001057 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
Zhou Shengadc14952007-03-14 09:07:33 +00001058 RHSKnownZero |= HighBits; // high bits known zero.
1059 }
Reid Spencer8cb68342007-03-12 17:25:59 +00001060 }
1061 break;
1062 case Instruction::AShr:
1063 // If this is an arithmetic shift right and only the low-bit is set, we can
1064 // always convert this into a logical shr, even if the shift amount is
1065 // variable. The low bit of the shift cannot be an input sign bit unless
1066 // the shift amount is >= the size of the datatype, which is undefined.
1067 if (DemandedMask == 1) {
1068 // Perform the logical shift right.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001069 Instruction *NewVal = BinaryOperator::CreateLShr(
Reid Spencer8cb68342007-03-12 17:25:59 +00001070 I->getOperand(0), I->getOperand(1), I->getName());
Chris Lattner886ab6c2009-01-31 08:15:18 +00001071 return InsertNewInstBefore(NewVal, *I);
Reid Spencer8cb68342007-03-12 17:25:59 +00001072 }
Chris Lattner4241e4d2007-07-15 20:54:51 +00001073
1074 // If the sign bit is the only bit demanded by this ashr, then there is no
1075 // need to do it, the shift doesn't change the high bit.
1076 if (DemandedMask.isSignBit())
Chris Lattner886ab6c2009-01-31 08:15:18 +00001077 return I->getOperand(0);
Reid Spencer8cb68342007-03-12 17:25:59 +00001078
1079 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng302748d2007-03-30 17:20:39 +00001080 uint32_t ShiftAmt = SA->getLimitedValue(BitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001081
Reid Spencer8cb68342007-03-12 17:25:59 +00001082 // Signed shift right.
Zhou Sheng01542f32007-03-29 02:26:30 +00001083 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
Lauro Ramos Venanciod0499af2007-06-06 17:08:48 +00001084 // If any of the "high bits" are demanded, we should set the sign bit as
1085 // demanded.
1086 if (DemandedMask.countLeadingZeros() <= ShiftAmt)
1087 DemandedMaskIn.set(BitWidth-1);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001088 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
Reid Spencer8cb68342007-03-12 17:25:59 +00001089 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001090 return I;
1091 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001092 // Compute the new bits that are at the top now.
Zhou Sheng01542f32007-03-29 02:26:30 +00001093 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
Reid Spencer8cb68342007-03-12 17:25:59 +00001094 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1095 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1096
1097 // Handle the sign bits.
1098 APInt SignBit(APInt::getSignBit(BitWidth));
1099 // Adjust to where it is now in the mask.
1100 SignBit = APIntOps::lshr(SignBit, ShiftAmt);
1101
1102 // If the input sign bit is known to be zero, or if none of the top bits
1103 // are demanded, turn this into an unsigned shift right.
Zhou Shengcc419402008-06-06 08:32:05 +00001104 if (BitWidth <= ShiftAmt || RHSKnownZero[BitWidth-ShiftAmt-1] ||
Reid Spencer8cb68342007-03-12 17:25:59 +00001105 (HighBits & ~DemandedMask) == HighBits) {
1106 // Perform the logical shift right.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001107 Instruction *NewVal = BinaryOperator::CreateLShr(
Reid Spencer8cb68342007-03-12 17:25:59 +00001108 I->getOperand(0), SA, I->getName());
Chris Lattner886ab6c2009-01-31 08:15:18 +00001109 return InsertNewInstBefore(NewVal, *I);
Reid Spencer8cb68342007-03-12 17:25:59 +00001110 } else if ((RHSKnownOne & SignBit) != 0) { // New bits are known one.
1111 RHSKnownOne |= HighBits;
1112 }
1113 }
1114 break;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001115 case Instruction::SRem:
1116 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
Nick Lewycky8e394322008-11-02 02:41:50 +00001117 APInt RA = Rem->getValue().abs();
1118 if (RA.isPowerOf2()) {
Eli Friedmana999a512009-06-17 02:57:36 +00001119 if (DemandedMask.ult(RA)) // srem won't affect demanded bits
Chris Lattner886ab6c2009-01-31 08:15:18 +00001120 return I->getOperand(0);
Nick Lewycky3ac9e102008-07-12 05:04:38 +00001121
Nick Lewycky8e394322008-11-02 02:41:50 +00001122 APInt LowBits = RA - 1;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001123 APInt Mask2 = LowBits | APInt::getSignBit(BitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001124 if (SimplifyDemandedBits(I->getOperandUse(0), Mask2,
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001125 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001126 return I;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001127
1128 if (LHSKnownZero[BitWidth-1] || ((LHSKnownZero & LowBits) == LowBits))
1129 LHSKnownZero |= ~LowBits;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001130
1131 KnownZero |= LHSKnownZero & DemandedMask;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001132
Chris Lattner886ab6c2009-01-31 08:15:18 +00001133 assert(!(KnownZero & KnownOne) && "Bits known to be one AND zero?");
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001134 }
1135 }
1136 break;
Dan Gohman23e8b712008-04-28 17:02:21 +00001137 case Instruction::URem: {
Dan Gohman23e8b712008-04-28 17:02:21 +00001138 APInt KnownZero2(BitWidth, 0), KnownOne2(BitWidth, 0);
1139 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001140 if (SimplifyDemandedBits(I->getOperandUse(0), AllOnes,
1141 KnownZero2, KnownOne2, Depth+1) ||
1142 SimplifyDemandedBits(I->getOperandUse(1), AllOnes,
Dan Gohmane85b7582008-05-01 19:13:24 +00001143 KnownZero2, KnownOne2, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001144 return I;
Dan Gohmane85b7582008-05-01 19:13:24 +00001145
Chris Lattner455e9ab2009-01-21 18:09:24 +00001146 unsigned Leaders = KnownZero2.countLeadingOnes();
Dan Gohman23e8b712008-04-28 17:02:21 +00001147 Leaders = std::max(Leaders,
1148 KnownZero2.countLeadingOnes());
1149 KnownZero = APInt::getHighBitsSet(BitWidth, Leaders) & DemandedMask;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001150 break;
Reid Spencer8cb68342007-03-12 17:25:59 +00001151 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00001152 case Instruction::Call:
1153 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
1154 switch (II->getIntrinsicID()) {
1155 default: break;
1156 case Intrinsic::bswap: {
1157 // If the only bits demanded come from one byte of the bswap result,
1158 // just shift the input byte into position to eliminate the bswap.
1159 unsigned NLZ = DemandedMask.countLeadingZeros();
1160 unsigned NTZ = DemandedMask.countTrailingZeros();
1161
1162 // Round NTZ down to the next byte. If we have 11 trailing zeros, then
1163 // we need all the bits down to bit 8. Likewise, round NLZ. If we
1164 // have 14 leading zeros, round to 8.
1165 NLZ &= ~7;
1166 NTZ &= ~7;
1167 // If we need exactly one byte, we can do this transformation.
1168 if (BitWidth-NLZ-NTZ == 8) {
1169 unsigned ResultBit = NTZ;
1170 unsigned InputBit = BitWidth-NTZ-8;
1171
1172 // Replace this with either a left or right shift to get the byte into
1173 // the right place.
1174 Instruction *NewVal;
1175 if (InputBit > ResultBit)
1176 NewVal = BinaryOperator::CreateLShr(I->getOperand(1),
Owen Andersoneed707b2009-07-24 23:12:02 +00001177 ConstantInt::get(I->getType(), InputBit-ResultBit));
Chris Lattner0521e3c2008-06-18 04:33:20 +00001178 else
1179 NewVal = BinaryOperator::CreateShl(I->getOperand(1),
Owen Andersoneed707b2009-07-24 23:12:02 +00001180 ConstantInt::get(I->getType(), ResultBit-InputBit));
Chris Lattner0521e3c2008-06-18 04:33:20 +00001181 NewVal->takeName(I);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001182 return InsertNewInstBefore(NewVal, *I);
Chris Lattner0521e3c2008-06-18 04:33:20 +00001183 }
1184
1185 // TODO: Could compute known zero/one bits based on the input.
1186 break;
1187 }
1188 }
1189 }
Chris Lattner6c3bfba2008-06-18 18:11:55 +00001190 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
Chris Lattner0521e3c2008-06-18 04:33:20 +00001191 break;
Dan Gohman23e8b712008-04-28 17:02:21 +00001192 }
Reid Spencer8cb68342007-03-12 17:25:59 +00001193
1194 // If the client is only demanding bits that we know, return the known
1195 // constant.
Dan Gohman43ee5f72009-08-03 22:07:33 +00001196 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask)
1197 return Constant::getIntegerValue(VTy, RHSKnownOne);
Reid Spencer8cb68342007-03-12 17:25:59 +00001198 return false;
1199}
1200
Chris Lattner867b99f2006-10-05 06:55:50 +00001201
Mon P Wangaeb06d22008-11-10 04:46:22 +00001202/// SimplifyDemandedVectorElts - The specified value produces a vector with
Evan Cheng388df622009-02-03 10:05:09 +00001203/// any number of elements. DemandedElts contains the set of elements that are
Chris Lattner867b99f2006-10-05 06:55:50 +00001204/// actually used by the caller. This method analyzes which elements of the
1205/// operand are undef and returns that information in UndefElts.
1206///
1207/// If the information about demanded elements can be used to simplify the
1208/// operation, the operation is simplified, then the resultant value is
1209/// returned. This returns null if no change was made.
Evan Cheng388df622009-02-03 10:05:09 +00001210Value *InstCombiner::SimplifyDemandedVectorElts(Value *V, APInt DemandedElts,
1211 APInt& UndefElts,
Chris Lattner867b99f2006-10-05 06:55:50 +00001212 unsigned Depth) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00001213 unsigned VWidth = cast<VectorType>(V->getType())->getNumElements();
Evan Cheng388df622009-02-03 10:05:09 +00001214 APInt EltMask(APInt::getAllOnesValue(VWidth));
Dan Gohman488fbfc2008-09-09 18:11:14 +00001215 assert((DemandedElts & ~EltMask) == 0 && "Invalid DemandedElts!");
Chris Lattner867b99f2006-10-05 06:55:50 +00001216
1217 if (isa<UndefValue>(V)) {
1218 // If the entire vector is undefined, just return this info.
1219 UndefElts = EltMask;
1220 return 0;
1221 } else if (DemandedElts == 0) { // If nothing is demanded, provide undef.
1222 UndefElts = EltMask;
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001223 return UndefValue::get(V->getType());
Chris Lattner867b99f2006-10-05 06:55:50 +00001224 }
Mon P Wangaeb06d22008-11-10 04:46:22 +00001225
Chris Lattner867b99f2006-10-05 06:55:50 +00001226 UndefElts = 0;
Reid Spencer9d6565a2007-02-15 02:26:10 +00001227 if (ConstantVector *CP = dyn_cast<ConstantVector>(V)) {
1228 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001229 Constant *Undef = UndefValue::get(EltTy);
Chris Lattner867b99f2006-10-05 06:55:50 +00001230
1231 std::vector<Constant*> Elts;
1232 for (unsigned i = 0; i != VWidth; ++i)
Evan Cheng388df622009-02-03 10:05:09 +00001233 if (!DemandedElts[i]) { // If not demanded, set to undef.
Chris Lattner867b99f2006-10-05 06:55:50 +00001234 Elts.push_back(Undef);
Evan Cheng388df622009-02-03 10:05:09 +00001235 UndefElts.set(i);
Chris Lattner867b99f2006-10-05 06:55:50 +00001236 } else if (isa<UndefValue>(CP->getOperand(i))) { // Already undef.
1237 Elts.push_back(Undef);
Evan Cheng388df622009-02-03 10:05:09 +00001238 UndefElts.set(i);
Chris Lattner867b99f2006-10-05 06:55:50 +00001239 } else { // Otherwise, defined.
1240 Elts.push_back(CP->getOperand(i));
1241 }
Mon P Wangaeb06d22008-11-10 04:46:22 +00001242
Chris Lattner867b99f2006-10-05 06:55:50 +00001243 // If we changed the constant, return it.
Owen Andersonaf7ec972009-07-28 21:19:26 +00001244 Constant *NewCP = ConstantVector::get(Elts);
Chris Lattner867b99f2006-10-05 06:55:50 +00001245 return NewCP != CP ? NewCP : 0;
1246 } else if (isa<ConstantAggregateZero>(V)) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00001247 // Simplify the CAZ to a ConstantVector where the non-demanded elements are
Chris Lattner867b99f2006-10-05 06:55:50 +00001248 // set to undef.
Mon P Wange0b436a2008-11-06 22:52:21 +00001249
1250 // Check if this is identity. If so, return 0 since we are not simplifying
1251 // anything.
1252 if (DemandedElts == ((1ULL << VWidth) -1))
1253 return 0;
1254
Reid Spencer9d6565a2007-02-15 02:26:10 +00001255 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
Owen Andersona7235ea2009-07-31 20:28:14 +00001256 Constant *Zero = Constant::getNullValue(EltTy);
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001257 Constant *Undef = UndefValue::get(EltTy);
Chris Lattner867b99f2006-10-05 06:55:50 +00001258 std::vector<Constant*> Elts;
Evan Cheng388df622009-02-03 10:05:09 +00001259 for (unsigned i = 0; i != VWidth; ++i) {
1260 Constant *Elt = DemandedElts[i] ? Zero : Undef;
1261 Elts.push_back(Elt);
1262 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001263 UndefElts = DemandedElts ^ EltMask;
Owen Andersonaf7ec972009-07-28 21:19:26 +00001264 return ConstantVector::get(Elts);
Chris Lattner867b99f2006-10-05 06:55:50 +00001265 }
1266
Dan Gohman488fbfc2008-09-09 18:11:14 +00001267 // Limit search depth.
1268 if (Depth == 10)
Dan Gohman2fe4d0a2009-04-25 17:28:45 +00001269 return 0;
Dan Gohman488fbfc2008-09-09 18:11:14 +00001270
1271 // If multiple users are using the root value, procede with
1272 // simplification conservatively assuming that all elements
1273 // are needed.
1274 if (!V->hasOneUse()) {
1275 // Quit if we find multiple users of a non-root value though.
1276 // They'll be handled when it's their turn to be visited by
1277 // the main instcombine process.
1278 if (Depth != 0)
Chris Lattner867b99f2006-10-05 06:55:50 +00001279 // TODO: Just compute the UndefElts information recursively.
Dan Gohman2fe4d0a2009-04-25 17:28:45 +00001280 return 0;
Dan Gohman488fbfc2008-09-09 18:11:14 +00001281
1282 // Conservatively assume that all elements are needed.
1283 DemandedElts = EltMask;
Chris Lattner867b99f2006-10-05 06:55:50 +00001284 }
1285
1286 Instruction *I = dyn_cast<Instruction>(V);
Dan Gohman2fe4d0a2009-04-25 17:28:45 +00001287 if (!I) return 0; // Only analyze instructions.
Chris Lattner867b99f2006-10-05 06:55:50 +00001288
1289 bool MadeChange = false;
Evan Cheng388df622009-02-03 10:05:09 +00001290 APInt UndefElts2(VWidth, 0);
Chris Lattner867b99f2006-10-05 06:55:50 +00001291 Value *TmpV;
1292 switch (I->getOpcode()) {
1293 default: break;
1294
1295 case Instruction::InsertElement: {
1296 // If this is a variable index, we don't know which element it overwrites.
1297 // demand exactly the same input as we produce.
Reid Spencerb83eb642006-10-20 07:07:24 +00001298 ConstantInt *Idx = dyn_cast<ConstantInt>(I->getOperand(2));
Chris Lattner867b99f2006-10-05 06:55:50 +00001299 if (Idx == 0) {
1300 // Note that we can't propagate undef elt info, because we don't know
1301 // which elt is getting updated.
1302 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1303 UndefElts2, Depth+1);
1304 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1305 break;
1306 }
1307
1308 // If this is inserting an element that isn't demanded, remove this
1309 // insertelement.
Reid Spencerb83eb642006-10-20 07:07:24 +00001310 unsigned IdxNo = Idx->getZExtValue();
Chris Lattnerc3a3e362009-08-30 06:20:05 +00001311 if (IdxNo >= VWidth || !DemandedElts[IdxNo]) {
1312 Worklist.Add(I);
1313 return I->getOperand(0);
1314 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001315
1316 // Otherwise, the element inserted overwrites whatever was there, so the
1317 // input demanded set is simpler than the output set.
Evan Cheng388df622009-02-03 10:05:09 +00001318 APInt DemandedElts2 = DemandedElts;
1319 DemandedElts2.clear(IdxNo);
1320 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts2,
Chris Lattner867b99f2006-10-05 06:55:50 +00001321 UndefElts, Depth+1);
1322 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1323
1324 // The inserted element is defined.
Evan Cheng388df622009-02-03 10:05:09 +00001325 UndefElts.clear(IdxNo);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001326 break;
1327 }
1328 case Instruction::ShuffleVector: {
1329 ShuffleVectorInst *Shuffle = cast<ShuffleVectorInst>(I);
Mon P Wangaeb06d22008-11-10 04:46:22 +00001330 uint64_t LHSVWidth =
1331 cast<VectorType>(Shuffle->getOperand(0)->getType())->getNumElements();
Evan Cheng388df622009-02-03 10:05:09 +00001332 APInt LeftDemanded(LHSVWidth, 0), RightDemanded(LHSVWidth, 0);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001333 for (unsigned i = 0; i < VWidth; i++) {
Evan Cheng388df622009-02-03 10:05:09 +00001334 if (DemandedElts[i]) {
Dan Gohman488fbfc2008-09-09 18:11:14 +00001335 unsigned MaskVal = Shuffle->getMaskValue(i);
1336 if (MaskVal != -1u) {
Mon P Wangaeb06d22008-11-10 04:46:22 +00001337 assert(MaskVal < LHSVWidth * 2 &&
Dan Gohman488fbfc2008-09-09 18:11:14 +00001338 "shufflevector mask index out of range!");
Mon P Wangaeb06d22008-11-10 04:46:22 +00001339 if (MaskVal < LHSVWidth)
Evan Cheng388df622009-02-03 10:05:09 +00001340 LeftDemanded.set(MaskVal);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001341 else
Evan Cheng388df622009-02-03 10:05:09 +00001342 RightDemanded.set(MaskVal - LHSVWidth);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001343 }
1344 }
1345 }
1346
Nate Begeman7b254672009-02-11 22:36:25 +00001347 APInt UndefElts4(LHSVWidth, 0);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001348 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), LeftDemanded,
Nate Begeman7b254672009-02-11 22:36:25 +00001349 UndefElts4, Depth+1);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001350 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1351
Nate Begeman7b254672009-02-11 22:36:25 +00001352 APInt UndefElts3(LHSVWidth, 0);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001353 TmpV = SimplifyDemandedVectorElts(I->getOperand(1), RightDemanded,
1354 UndefElts3, Depth+1);
1355 if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1356
1357 bool NewUndefElts = false;
1358 for (unsigned i = 0; i < VWidth; i++) {
1359 unsigned MaskVal = Shuffle->getMaskValue(i);
Dan Gohmancb893092008-09-10 01:09:32 +00001360 if (MaskVal == -1u) {
Evan Cheng388df622009-02-03 10:05:09 +00001361 UndefElts.set(i);
Mon P Wangaeb06d22008-11-10 04:46:22 +00001362 } else if (MaskVal < LHSVWidth) {
Nate Begeman7b254672009-02-11 22:36:25 +00001363 if (UndefElts4[MaskVal]) {
Evan Cheng388df622009-02-03 10:05:09 +00001364 NewUndefElts = true;
1365 UndefElts.set(i);
1366 }
Dan Gohman488fbfc2008-09-09 18:11:14 +00001367 } else {
Evan Cheng388df622009-02-03 10:05:09 +00001368 if (UndefElts3[MaskVal - LHSVWidth]) {
1369 NewUndefElts = true;
1370 UndefElts.set(i);
1371 }
Dan Gohman488fbfc2008-09-09 18:11:14 +00001372 }
1373 }
1374
1375 if (NewUndefElts) {
1376 // Add additional discovered undefs.
1377 std::vector<Constant*> Elts;
1378 for (unsigned i = 0; i < VWidth; ++i) {
Evan Cheng388df622009-02-03 10:05:09 +00001379 if (UndefElts[i])
Chris Lattner4de84762010-01-04 07:02:48 +00001380 Elts.push_back(UndefValue::get(Type::getInt32Ty(I->getContext())));
Dan Gohman488fbfc2008-09-09 18:11:14 +00001381 else
Chris Lattner4de84762010-01-04 07:02:48 +00001382 Elts.push_back(ConstantInt::get(Type::getInt32Ty(I->getContext()),
Dan Gohman488fbfc2008-09-09 18:11:14 +00001383 Shuffle->getMaskValue(i)));
1384 }
Owen Andersonaf7ec972009-07-28 21:19:26 +00001385 I->setOperand(2, ConstantVector::get(Elts));
Dan Gohman488fbfc2008-09-09 18:11:14 +00001386 MadeChange = true;
1387 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001388 break;
1389 }
Chris Lattner69878332007-04-14 22:29:23 +00001390 case Instruction::BitCast: {
Dan Gohman07a96762007-07-16 14:29:03 +00001391 // Vector->vector casts only.
Chris Lattner69878332007-04-14 22:29:23 +00001392 const VectorType *VTy = dyn_cast<VectorType>(I->getOperand(0)->getType());
1393 if (!VTy) break;
1394 unsigned InVWidth = VTy->getNumElements();
Evan Cheng388df622009-02-03 10:05:09 +00001395 APInt InputDemandedElts(InVWidth, 0);
Chris Lattner69878332007-04-14 22:29:23 +00001396 unsigned Ratio;
1397
1398 if (VWidth == InVWidth) {
Dan Gohman07a96762007-07-16 14:29:03 +00001399 // If we are converting from <4 x i32> -> <4 x f32>, we demand the same
Chris Lattner69878332007-04-14 22:29:23 +00001400 // elements as are demanded of us.
1401 Ratio = 1;
1402 InputDemandedElts = DemandedElts;
1403 } else if (VWidth > InVWidth) {
1404 // Untested so far.
1405 break;
1406
1407 // If there are more elements in the result than there are in the source,
1408 // then an input element is live if any of the corresponding output
1409 // elements are live.
1410 Ratio = VWidth/InVWidth;
1411 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx) {
Evan Cheng388df622009-02-03 10:05:09 +00001412 if (DemandedElts[OutIdx])
1413 InputDemandedElts.set(OutIdx/Ratio);
Chris Lattner69878332007-04-14 22:29:23 +00001414 }
1415 } else {
1416 // Untested so far.
1417 break;
1418
1419 // If there are more elements in the source than there are in the result,
1420 // then an input element is live if the corresponding output element is
1421 // live.
1422 Ratio = InVWidth/VWidth;
1423 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
Evan Cheng388df622009-02-03 10:05:09 +00001424 if (DemandedElts[InIdx/Ratio])
1425 InputDemandedElts.set(InIdx);
Chris Lattner69878332007-04-14 22:29:23 +00001426 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001427
Chris Lattner69878332007-04-14 22:29:23 +00001428 // div/rem demand all inputs, because they don't want divide by zero.
1429 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), InputDemandedElts,
1430 UndefElts2, Depth+1);
1431 if (TmpV) {
1432 I->setOperand(0, TmpV);
1433 MadeChange = true;
1434 }
1435
1436 UndefElts = UndefElts2;
1437 if (VWidth > InVWidth) {
Torok Edwinc23197a2009-07-14 16:55:14 +00001438 llvm_unreachable("Unimp");
Chris Lattner69878332007-04-14 22:29:23 +00001439 // If there are more elements in the result than there are in the source,
1440 // then an output element is undef if the corresponding input element is
1441 // undef.
1442 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx)
Evan Cheng388df622009-02-03 10:05:09 +00001443 if (UndefElts2[OutIdx/Ratio])
1444 UndefElts.set(OutIdx);
Chris Lattner69878332007-04-14 22:29:23 +00001445 } else if (VWidth < InVWidth) {
Torok Edwinc23197a2009-07-14 16:55:14 +00001446 llvm_unreachable("Unimp");
Chris Lattner69878332007-04-14 22:29:23 +00001447 // If there are more elements in the source than there are in the result,
1448 // then a result element is undef if all of the corresponding input
1449 // elements are undef.
1450 UndefElts = ~0ULL >> (64-VWidth); // Start out all undef.
1451 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
Evan Cheng388df622009-02-03 10:05:09 +00001452 if (!UndefElts2[InIdx]) // Not undef?
1453 UndefElts.clear(InIdx/Ratio); // Clear undef bit.
Chris Lattner69878332007-04-14 22:29:23 +00001454 }
1455 break;
1456 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001457 case Instruction::And:
1458 case Instruction::Or:
1459 case Instruction::Xor:
1460 case Instruction::Add:
1461 case Instruction::Sub:
1462 case Instruction::Mul:
1463 // div/rem demand all inputs, because they don't want divide by zero.
1464 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1465 UndefElts, Depth+1);
1466 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1467 TmpV = SimplifyDemandedVectorElts(I->getOperand(1), DemandedElts,
1468 UndefElts2, Depth+1);
1469 if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1470
1471 // Output elements are undefined if both are undefined. Consider things
1472 // like undef&0. The result is known zero, not undef.
1473 UndefElts &= UndefElts2;
1474 break;
1475
1476 case Instruction::Call: {
1477 IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
1478 if (!II) break;
1479 switch (II->getIntrinsicID()) {
1480 default: break;
1481
1482 // Binary vector operations that work column-wise. A dest element is a
1483 // function of the corresponding input elements from the two inputs.
1484 case Intrinsic::x86_sse_sub_ss:
1485 case Intrinsic::x86_sse_mul_ss:
1486 case Intrinsic::x86_sse_min_ss:
1487 case Intrinsic::x86_sse_max_ss:
1488 case Intrinsic::x86_sse2_sub_sd:
1489 case Intrinsic::x86_sse2_mul_sd:
1490 case Intrinsic::x86_sse2_min_sd:
1491 case Intrinsic::x86_sse2_max_sd:
1492 TmpV = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
1493 UndefElts, Depth+1);
1494 if (TmpV) { II->setOperand(1, TmpV); MadeChange = true; }
1495 TmpV = SimplifyDemandedVectorElts(II->getOperand(2), DemandedElts,
1496 UndefElts2, Depth+1);
1497 if (TmpV) { II->setOperand(2, TmpV); MadeChange = true; }
1498
1499 // If only the low elt is demanded and this is a scalarizable intrinsic,
1500 // scalarize it now.
1501 if (DemandedElts == 1) {
1502 switch (II->getIntrinsicID()) {
1503 default: break;
1504 case Intrinsic::x86_sse_sub_ss:
1505 case Intrinsic::x86_sse_mul_ss:
1506 case Intrinsic::x86_sse2_sub_sd:
1507 case Intrinsic::x86_sse2_mul_sd:
1508 // TODO: Lower MIN/MAX/ABS/etc
1509 Value *LHS = II->getOperand(1);
1510 Value *RHS = II->getOperand(2);
1511 // Extract the element as scalars.
Eric Christophera3500da2009-07-25 02:28:41 +00001512 LHS = InsertNewInstBefore(ExtractElementInst::Create(LHS,
Chris Lattner4de84762010-01-04 07:02:48 +00001513 ConstantInt::get(Type::getInt32Ty(I->getContext()), 0U)), *II);
Eric Christophera3500da2009-07-25 02:28:41 +00001514 RHS = InsertNewInstBefore(ExtractElementInst::Create(RHS,
Chris Lattner4de84762010-01-04 07:02:48 +00001515 ConstantInt::get(Type::getInt32Ty(I->getContext()), 0U)), *II);
Chris Lattner867b99f2006-10-05 06:55:50 +00001516
1517 switch (II->getIntrinsicID()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00001518 default: llvm_unreachable("Case stmts out of sync!");
Chris Lattner867b99f2006-10-05 06:55:50 +00001519 case Intrinsic::x86_sse_sub_ss:
1520 case Intrinsic::x86_sse2_sub_sd:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001521 TmpV = InsertNewInstBefore(BinaryOperator::CreateFSub(LHS, RHS,
Chris Lattner867b99f2006-10-05 06:55:50 +00001522 II->getName()), *II);
1523 break;
1524 case Intrinsic::x86_sse_mul_ss:
1525 case Intrinsic::x86_sse2_mul_sd:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001526 TmpV = InsertNewInstBefore(BinaryOperator::CreateFMul(LHS, RHS,
Chris Lattner867b99f2006-10-05 06:55:50 +00001527 II->getName()), *II);
1528 break;
1529 }
1530
1531 Instruction *New =
Owen Andersond672ecb2009-07-03 00:17:18 +00001532 InsertElementInst::Create(
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001533 UndefValue::get(II->getType()), TmpV,
Chris Lattner4de84762010-01-04 07:02:48 +00001534 ConstantInt::get(Type::getInt32Ty(I->getContext()), 0U, false),
1535 II->getName());
Chris Lattner867b99f2006-10-05 06:55:50 +00001536 InsertNewInstBefore(New, *II);
Chris Lattner867b99f2006-10-05 06:55:50 +00001537 return New;
1538 }
1539 }
1540
1541 // Output elements are undefined if both are undefined. Consider things
1542 // like undef&0. The result is known zero, not undef.
1543 UndefElts &= UndefElts2;
1544 break;
1545 }
1546 break;
1547 }
1548 }
1549 return MadeChange ? I : 0;
1550}
1551
Dan Gohman45b4e482008-05-19 22:14:15 +00001552
Chris Lattner564a7272003-08-13 19:01:45 +00001553/// AssociativeOpt - Perform an optimization on an associative operator. This
1554/// function is designed to check a chain of associative operators for a
1555/// potential to apply a certain optimization. Since the optimization may be
1556/// applicable if the expression was reassociated, this checks the chain, then
1557/// reassociates the expression as necessary to expose the optimization
1558/// opportunity. This makes use of a special Functor, which must define
1559/// 'shouldApply' and 'apply' methods.
1560///
1561template<typename Functor>
Dan Gohman186a6362009-08-12 16:04:34 +00001562static Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
Chris Lattner564a7272003-08-13 19:01:45 +00001563 unsigned Opcode = Root.getOpcode();
1564 Value *LHS = Root.getOperand(0);
1565
1566 // Quick check, see if the immediate LHS matches...
1567 if (F.shouldApply(LHS))
1568 return F.apply(Root);
1569
1570 // Otherwise, if the LHS is not of the same opcode as the root, return.
1571 Instruction *LHSI = dyn_cast<Instruction>(LHS);
Chris Lattnerfd059242003-10-15 16:48:29 +00001572 while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
Chris Lattner564a7272003-08-13 19:01:45 +00001573 // Should we apply this transform to the RHS?
1574 bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
1575
1576 // If not to the RHS, check to see if we should apply to the LHS...
1577 if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
1578 cast<BinaryOperator>(LHSI)->swapOperands(); // Make the LHS the RHS
1579 ShouldApply = true;
1580 }
1581
1582 // If the functor wants to apply the optimization to the RHS of LHSI,
1583 // reassociate the expression from ((? op A) op B) to (? op (A op B))
1584 if (ShouldApply) {
Chris Lattner564a7272003-08-13 19:01:45 +00001585 // Now all of the instructions are in the current basic block, go ahead
1586 // and perform the reassociation.
1587 Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
1588
1589 // First move the selected RHS to the LHS of the root...
1590 Root.setOperand(0, LHSI->getOperand(1));
1591
1592 // Make what used to be the LHS of the root be the user of the root...
1593 Value *ExtraOperand = TmpLHSI->getOperand(1);
Chris Lattner65725312004-04-16 18:08:07 +00001594 if (&Root == TmpLHSI) {
Owen Andersona7235ea2009-07-31 20:28:14 +00001595 Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
Chris Lattner15a76c02004-04-05 02:10:19 +00001596 return 0;
1597 }
Chris Lattner65725312004-04-16 18:08:07 +00001598 Root.replaceAllUsesWith(TmpLHSI); // Users now use TmpLHSI
Chris Lattner564a7272003-08-13 19:01:45 +00001599 TmpLHSI->setOperand(1, &Root); // TmpLHSI now uses the root
Chris Lattner65725312004-04-16 18:08:07 +00001600 BasicBlock::iterator ARI = &Root; ++ARI;
Dan Gohmand02d9172008-06-19 17:47:47 +00001601 TmpLHSI->moveBefore(ARI); // Move TmpLHSI to after Root
Chris Lattner65725312004-04-16 18:08:07 +00001602 ARI = Root;
Chris Lattner564a7272003-08-13 19:01:45 +00001603
1604 // Now propagate the ExtraOperand down the chain of instructions until we
1605 // get to LHSI.
1606 while (TmpLHSI != LHSI) {
1607 Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
Chris Lattner65725312004-04-16 18:08:07 +00001608 // Move the instruction to immediately before the chain we are
1609 // constructing to avoid breaking dominance properties.
Dan Gohmand02d9172008-06-19 17:47:47 +00001610 NextLHSI->moveBefore(ARI);
Chris Lattner65725312004-04-16 18:08:07 +00001611 ARI = NextLHSI;
1612
Chris Lattner564a7272003-08-13 19:01:45 +00001613 Value *NextOp = NextLHSI->getOperand(1);
1614 NextLHSI->setOperand(1, ExtraOperand);
1615 TmpLHSI = NextLHSI;
1616 ExtraOperand = NextOp;
1617 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001618
Chris Lattner564a7272003-08-13 19:01:45 +00001619 // Now that the instructions are reassociated, have the functor perform
1620 // the transformation...
1621 return F.apply(Root);
1622 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001623
Chris Lattner564a7272003-08-13 19:01:45 +00001624 LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
1625 }
1626 return 0;
1627}
1628
Dan Gohman844731a2008-05-13 00:00:25 +00001629namespace {
Chris Lattner564a7272003-08-13 19:01:45 +00001630
Nick Lewycky02d639f2008-05-23 04:34:58 +00001631// AddRHS - Implements: X + X --> X << 1
Chris Lattner564a7272003-08-13 19:01:45 +00001632struct AddRHS {
1633 Value *RHS;
Dan Gohman4ae51262009-08-12 16:23:25 +00001634 explicit AddRHS(Value *rhs) : RHS(rhs) {}
Chris Lattner564a7272003-08-13 19:01:45 +00001635 bool shouldApply(Value *LHS) const { return LHS == RHS; }
1636 Instruction *apply(BinaryOperator &Add) const {
Nick Lewycky02d639f2008-05-23 04:34:58 +00001637 return BinaryOperator::CreateShl(Add.getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00001638 ConstantInt::get(Add.getType(), 1));
Chris Lattner564a7272003-08-13 19:01:45 +00001639 }
1640};
1641
1642// AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
1643// iff C1&C2 == 0
1644struct AddMaskingAnd {
1645 Constant *C2;
Dan Gohman4ae51262009-08-12 16:23:25 +00001646 explicit AddMaskingAnd(Constant *c) : C2(c) {}
Chris Lattner564a7272003-08-13 19:01:45 +00001647 bool shouldApply(Value *LHS) const {
Chris Lattneracd1f0f2004-07-30 07:50:03 +00001648 ConstantInt *C1;
Dan Gohman4ae51262009-08-12 16:23:25 +00001649 return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
Owen Andersonbaf3c402009-07-29 18:55:55 +00001650 ConstantExpr::getAnd(C1, C2)->isNullValue();
Chris Lattner564a7272003-08-13 19:01:45 +00001651 }
1652 Instruction *apply(BinaryOperator &Add) const {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001653 return BinaryOperator::CreateOr(Add.getOperand(0), Add.getOperand(1));
Chris Lattner564a7272003-08-13 19:01:45 +00001654 }
1655};
1656
Dan Gohman844731a2008-05-13 00:00:25 +00001657}
1658
Chris Lattner6e7ba452005-01-01 16:22:27 +00001659static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
Chris Lattner2eefe512004-04-09 19:05:30 +00001660 InstCombiner *IC) {
Chris Lattner08142f22009-08-30 19:47:22 +00001661 if (CastInst *CI = dyn_cast<CastInst>(&I))
Chris Lattner2345d1d2009-08-30 20:01:10 +00001662 return IC->Builder->CreateCast(CI->getOpcode(), SO, I.getType());
Chris Lattner6e7ba452005-01-01 16:22:27 +00001663
Chris Lattner2eefe512004-04-09 19:05:30 +00001664 // Figure out if the constant is the left or the right argument.
Chris Lattner6e7ba452005-01-01 16:22:27 +00001665 bool ConstIsRHS = isa<Constant>(I.getOperand(1));
1666 Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
Chris Lattner564a7272003-08-13 19:01:45 +00001667
Chris Lattner2eefe512004-04-09 19:05:30 +00001668 if (Constant *SOC = dyn_cast<Constant>(SO)) {
1669 if (ConstIsRHS)
Owen Andersonbaf3c402009-07-29 18:55:55 +00001670 return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
1671 return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
Chris Lattner2eefe512004-04-09 19:05:30 +00001672 }
1673
1674 Value *Op0 = SO, *Op1 = ConstOperand;
1675 if (!ConstIsRHS)
1676 std::swap(Op0, Op1);
Chris Lattner74381062009-08-30 07:44:24 +00001677
Chris Lattner6e7ba452005-01-01 16:22:27 +00001678 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
Chris Lattner74381062009-08-30 07:44:24 +00001679 return IC->Builder->CreateBinOp(BO->getOpcode(), Op0, Op1,
1680 SO->getName()+".op");
1681 if (ICmpInst *CI = dyn_cast<ICmpInst>(&I))
1682 return IC->Builder->CreateICmp(CI->getPredicate(), Op0, Op1,
1683 SO->getName()+".cmp");
1684 if (FCmpInst *CI = dyn_cast<FCmpInst>(&I))
1685 return IC->Builder->CreateICmp(CI->getPredicate(), Op0, Op1,
1686 SO->getName()+".cmp");
1687 llvm_unreachable("Unknown binary instruction type!");
Chris Lattner6e7ba452005-01-01 16:22:27 +00001688}
1689
1690// FoldOpIntoSelect - Given an instruction with a select as one operand and a
1691// constant as the other operand, try to fold the binary operator into the
1692// select arguments. This also works for Cast instructions, which obviously do
1693// not have a second operand.
1694static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
1695 InstCombiner *IC) {
1696 // Don't modify shared select instructions
1697 if (!SI->hasOneUse()) return 0;
1698 Value *TV = SI->getOperand(1);
1699 Value *FV = SI->getOperand(2);
1700
1701 if (isa<Constant>(TV) || isa<Constant>(FV)) {
Chris Lattner956db272005-04-21 05:43:13 +00001702 // Bool selects with constant operands can be folded to logical ops.
Chris Lattner4de84762010-01-04 07:02:48 +00001703 if (SI->getType() == Type::getInt1Ty(SI->getContext())) return 0;
Chris Lattner956db272005-04-21 05:43:13 +00001704
Chris Lattner6e7ba452005-01-01 16:22:27 +00001705 Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
1706 Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
1707
Gabor Greif051a9502008-04-06 20:25:17 +00001708 return SelectInst::Create(SI->getCondition(), SelectTrueVal,
1709 SelectFalseVal);
Chris Lattner6e7ba452005-01-01 16:22:27 +00001710 }
1711 return 0;
Chris Lattner2eefe512004-04-09 19:05:30 +00001712}
1713
Chris Lattner4e998b22004-09-29 05:07:12 +00001714
Chris Lattner5d1704d2009-09-27 19:57:57 +00001715/// FoldOpIntoPhi - Given a binary operator, cast instruction, or select which
1716/// has a PHI node as operand #0, see if we can fold the instruction into the
1717/// PHI (which is only possible if all operands to the PHI are constants).
Chris Lattner213cd612009-09-27 20:46:36 +00001718///
1719/// If AllowAggressive is true, FoldOpIntoPhi will allow certain transforms
1720/// that would normally be unprofitable because they strongly encourage jump
1721/// threading.
1722Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I,
1723 bool AllowAggressive) {
1724 AllowAggressive = false;
Chris Lattner4e998b22004-09-29 05:07:12 +00001725 PHINode *PN = cast<PHINode>(I.getOperand(0));
Chris Lattnerbac32862004-11-14 19:13:23 +00001726 unsigned NumPHIValues = PN->getNumIncomingValues();
Chris Lattner213cd612009-09-27 20:46:36 +00001727 if (NumPHIValues == 0 ||
1728 // We normally only transform phis with a single use, unless we're trying
1729 // hard to make jump threading happen.
1730 (!PN->hasOneUse() && !AllowAggressive))
1731 return 0;
1732
1733
Chris Lattner5d1704d2009-09-27 19:57:57 +00001734 // Check to see if all of the operands of the PHI are simple constants
1735 // (constantint/constantfp/undef). If there is one non-constant value,
Chris Lattnerc6df8f42009-09-27 20:18:49 +00001736 // remember the BB it is in. If there is more than one or if *it* is a PHI,
1737 // bail out. We don't do arbitrary constant expressions here because moving
1738 // their computation can be expensive without a cost model.
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001739 BasicBlock *NonConstBB = 0;
1740 for (unsigned i = 0; i != NumPHIValues; ++i)
Chris Lattner5d1704d2009-09-27 19:57:57 +00001741 if (!isa<Constant>(PN->getIncomingValue(i)) ||
1742 isa<ConstantExpr>(PN->getIncomingValue(i))) {
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001743 if (NonConstBB) return 0; // More than one non-const value.
Chris Lattnerb3036682007-02-24 01:03:45 +00001744 if (isa<PHINode>(PN->getIncomingValue(i))) return 0; // Itself a phi.
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001745 NonConstBB = PN->getIncomingBlock(i);
1746
1747 // If the incoming non-constant value is in I's block, we have an infinite
1748 // loop.
1749 if (NonConstBB == I.getParent())
1750 return 0;
1751 }
1752
1753 // If there is exactly one non-constant value, we can insert a copy of the
1754 // operation in that block. However, if this is a critical edge, we would be
1755 // inserting the computation one some other paths (e.g. inside a loop). Only
1756 // do this if the pred block is unconditionally branching into the phi block.
Chris Lattner213cd612009-09-27 20:46:36 +00001757 if (NonConstBB != 0 && !AllowAggressive) {
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001758 BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
1759 if (!BI || !BI->isUnconditional()) return 0;
1760 }
Chris Lattner4e998b22004-09-29 05:07:12 +00001761
1762 // Okay, we can do the transformation: create the new PHI node.
Gabor Greif051a9502008-04-06 20:25:17 +00001763 PHINode *NewPN = PHINode::Create(I.getType(), "");
Chris Lattner55517062005-01-29 00:39:08 +00001764 NewPN->reserveOperandSpace(PN->getNumOperands()/2);
Chris Lattner857eb572009-10-21 23:41:58 +00001765 InsertNewInstBefore(NewPN, *PN);
1766 NewPN->takeName(PN);
Chris Lattner4e998b22004-09-29 05:07:12 +00001767
1768 // Next, add all of the operands to the PHI.
Chris Lattner5d1704d2009-09-27 19:57:57 +00001769 if (SelectInst *SI = dyn_cast<SelectInst>(&I)) {
1770 // We only currently try to fold the condition of a select when it is a phi,
1771 // not the true/false values.
Chris Lattnerc6df8f42009-09-27 20:18:49 +00001772 Value *TrueV = SI->getTrueValue();
1773 Value *FalseV = SI->getFalseValue();
Chris Lattner3ddfb212009-09-28 06:49:44 +00001774 BasicBlock *PhiTransBB = PN->getParent();
Chris Lattner5d1704d2009-09-27 19:57:57 +00001775 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattnerc6df8f42009-09-27 20:18:49 +00001776 BasicBlock *ThisBB = PN->getIncomingBlock(i);
Chris Lattner3ddfb212009-09-28 06:49:44 +00001777 Value *TrueVInPred = TrueV->DoPHITranslation(PhiTransBB, ThisBB);
1778 Value *FalseVInPred = FalseV->DoPHITranslation(PhiTransBB, ThisBB);
Chris Lattner5d1704d2009-09-27 19:57:57 +00001779 Value *InV = 0;
1780 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Chris Lattnerc6df8f42009-09-27 20:18:49 +00001781 InV = InC->isNullValue() ? FalseVInPred : TrueVInPred;
Chris Lattner5d1704d2009-09-27 19:57:57 +00001782 } else {
1783 assert(PN->getIncomingBlock(i) == NonConstBB);
Chris Lattnerc6df8f42009-09-27 20:18:49 +00001784 InV = SelectInst::Create(PN->getIncomingValue(i), TrueVInPred,
1785 FalseVInPred,
Chris Lattner5d1704d2009-09-27 19:57:57 +00001786 "phitmp", NonConstBB->getTerminator());
Chris Lattner857eb572009-10-21 23:41:58 +00001787 Worklist.Add(cast<Instruction>(InV));
Chris Lattner5d1704d2009-09-27 19:57:57 +00001788 }
Chris Lattnerc6df8f42009-09-27 20:18:49 +00001789 NewPN->addIncoming(InV, ThisBB);
Chris Lattner5d1704d2009-09-27 19:57:57 +00001790 }
1791 } else if (I.getNumOperands() == 2) {
Chris Lattner4e998b22004-09-29 05:07:12 +00001792 Constant *C = cast<Constant>(I.getOperand(1));
Chris Lattnerbac32862004-11-14 19:13:23 +00001793 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattnera9ff5eb2007-08-05 08:47:58 +00001794 Value *InV = 0;
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001795 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00001796 if (CmpInst *CI = dyn_cast<CmpInst>(&I))
Owen Andersonbaf3c402009-07-29 18:55:55 +00001797 InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C);
Reid Spencere4d87aa2006-12-23 06:05:41 +00001798 else
Owen Andersonbaf3c402009-07-29 18:55:55 +00001799 InV = ConstantExpr::get(I.getOpcode(), InC, C);
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001800 } else {
1801 assert(PN->getIncomingBlock(i) == NonConstBB);
1802 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001803 InV = BinaryOperator::Create(BO->getOpcode(),
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001804 PN->getIncomingValue(i), C, "phitmp",
1805 NonConstBB->getTerminator());
Reid Spencere4d87aa2006-12-23 06:05:41 +00001806 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00001807 InV = CmpInst::Create(CI->getOpcode(),
Reid Spencere4d87aa2006-12-23 06:05:41 +00001808 CI->getPredicate(),
1809 PN->getIncomingValue(i), C, "phitmp",
1810 NonConstBB->getTerminator());
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001811 else
Torok Edwinc23197a2009-07-14 16:55:14 +00001812 llvm_unreachable("Unknown binop!");
Chris Lattner857eb572009-10-21 23:41:58 +00001813
1814 Worklist.Add(cast<Instruction>(InV));
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001815 }
1816 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner4e998b22004-09-29 05:07:12 +00001817 }
Reid Spencer3da59db2006-11-27 01:05:10 +00001818 } else {
1819 CastInst *CI = cast<CastInst>(&I);
1820 const Type *RetTy = CI->getType();
Chris Lattnerbac32862004-11-14 19:13:23 +00001821 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001822 Value *InV;
1823 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00001824 InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001825 } else {
1826 assert(PN->getIncomingBlock(i) == NonConstBB);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001827 InV = CastInst::Create(CI->getOpcode(), PN->getIncomingValue(i),
Reid Spencer3da59db2006-11-27 01:05:10 +00001828 I.getType(), "phitmp",
1829 NonConstBB->getTerminator());
Chris Lattner857eb572009-10-21 23:41:58 +00001830 Worklist.Add(cast<Instruction>(InV));
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001831 }
1832 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner4e998b22004-09-29 05:07:12 +00001833 }
1834 }
1835 return ReplaceInstUsesWith(I, NewPN);
1836}
1837
Chris Lattner2454a2e2008-01-29 06:52:45 +00001838
Chris Lattner3d28b1b2008-05-20 05:46:13 +00001839/// WillNotOverflowSignedAdd - Return true if we can prove that:
1840/// (sext (add LHS, RHS)) === (add (sext LHS), (sext RHS))
1841/// This basically requires proving that the add in the original type would not
1842/// overflow to change the sign bit or have a carry out.
1843bool InstCombiner::WillNotOverflowSignedAdd(Value *LHS, Value *RHS) {
1844 // There are different heuristics we can use for this. Here are some simple
1845 // ones.
1846
1847 // Add has the property that adding any two 2's complement numbers can only
1848 // have one carry bit which can change a sign. As such, if LHS and RHS each
Chris Lattner8aee8ef2009-11-27 17:42:22 +00001849 // have at least two sign bits, we know that the addition of the two values
1850 // will sign extend fine.
Chris Lattner3d28b1b2008-05-20 05:46:13 +00001851 if (ComputeNumSignBits(LHS) > 1 && ComputeNumSignBits(RHS) > 1)
1852 return true;
1853
1854
1855 // If one of the operands only has one non-zero bit, and if the other operand
1856 // has a known-zero bit in a more significant place than it (not including the
1857 // sign bit) the ripple may go up to and fill the zero, but won't change the
1858 // sign. For example, (X & ~4) + 1.
1859
1860 // TODO: Implement.
1861
1862 return false;
1863}
1864
Chris Lattner2454a2e2008-01-29 06:52:45 +00001865
Chris Lattner7e708292002-06-25 16:13:24 +00001866Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00001867 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00001868 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
Chris Lattnerb35dde12002-05-06 16:49:18 +00001869
Chris Lattner8aee8ef2009-11-27 17:42:22 +00001870 if (Value *V = SimplifyAddInst(LHS, RHS, I.hasNoSignedWrap(),
1871 I.hasNoUnsignedWrap(), TD))
1872 return ReplaceInstUsesWith(I, V);
1873
1874
Chris Lattner66331a42004-04-10 22:01:55 +00001875 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
Chris Lattner66331a42004-04-10 22:01:55 +00001876 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
Chris Lattnerb4a2f052006-11-09 05:12:27 +00001877 // X + (signbit) --> X ^ signbit
Zhou Sheng3a507fd2007-04-01 17:13:37 +00001878 const APInt& Val = CI->getValue();
Zhou Sheng4351c642007-04-02 08:20:41 +00001879 uint32_t BitWidth = Val.getBitWidth();
Reid Spencer2ec619a2007-03-23 21:24:59 +00001880 if (Val == APInt::getSignBit(BitWidth))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001881 return BinaryOperator::CreateXor(LHS, RHS);
Chris Lattnerb4a2f052006-11-09 05:12:27 +00001882
1883 // See if SimplifyDemandedBits can simplify this. This handles stuff like
1884 // (X & 254)+1 -> (X&254)|1
Dan Gohman6de29f82009-06-15 22:12:54 +00001885 if (SimplifyDemandedInstructionBits(I))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001886 return &I;
Dan Gohman1975d032008-10-30 20:40:10 +00001887
Eli Friedman709b33d2009-07-13 22:27:52 +00001888 // zext(bool) + C -> bool ? C + 1 : C
Dan Gohman1975d032008-10-30 20:40:10 +00001889 if (ZExtInst *ZI = dyn_cast<ZExtInst>(LHS))
Chris Lattner4de84762010-01-04 07:02:48 +00001890 if (ZI->getSrcTy() == Type::getInt1Ty(I.getContext()))
Dan Gohman186a6362009-08-12 16:04:34 +00001891 return SelectInst::Create(ZI->getOperand(0), AddOne(CI), CI);
Chris Lattner66331a42004-04-10 22:01:55 +00001892 }
Chris Lattner4e998b22004-09-29 05:07:12 +00001893
1894 if (isa<PHINode>(LHS))
1895 if (Instruction *NV = FoldOpIntoPhi(I))
1896 return NV;
Chris Lattner5931c542005-09-24 23:43:33 +00001897
Chris Lattner4f637d42006-01-06 17:59:59 +00001898 ConstantInt *XorRHS = 0;
1899 Value *XorLHS = 0;
Chris Lattnerc5eff442007-01-30 22:32:46 +00001900 if (isa<ConstantInt>(RHSC) &&
Dan Gohman4ae51262009-08-12 16:23:25 +00001901 match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
Dan Gohman6de29f82009-06-15 22:12:54 +00001902 uint32_t TySizeBits = I.getType()->getScalarSizeInBits();
Zhou Sheng3a507fd2007-04-01 17:13:37 +00001903 const APInt& RHSVal = cast<ConstantInt>(RHSC)->getValue();
Chris Lattner5931c542005-09-24 23:43:33 +00001904
Zhou Sheng4351c642007-04-02 08:20:41 +00001905 uint32_t Size = TySizeBits / 2;
Reid Spencer2ec619a2007-03-23 21:24:59 +00001906 APInt C0080Val(APInt(TySizeBits, 1ULL).shl(Size - 1));
1907 APInt CFF80Val(-C0080Val);
Chris Lattner5931c542005-09-24 23:43:33 +00001908 do {
1909 if (TySizeBits > Size) {
Chris Lattner5931c542005-09-24 23:43:33 +00001910 // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
1911 // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
Reid Spencer2ec619a2007-03-23 21:24:59 +00001912 if ((RHSVal == CFF80Val && XorRHS->getValue() == C0080Val) ||
1913 (RHSVal == C0080Val && XorRHS->getValue() == CFF80Val)) {
Chris Lattner5931c542005-09-24 23:43:33 +00001914 // This is a sign extend if the top bits are known zero.
Zhou Sheng290bec52007-03-29 08:15:12 +00001915 if (!MaskedValueIsZero(XorLHS,
1916 APInt::getHighBitsSet(TySizeBits, TySizeBits - Size)))
Chris Lattner5931c542005-09-24 23:43:33 +00001917 Size = 0; // Not a sign ext, but can't be any others either.
Reid Spencer2ec619a2007-03-23 21:24:59 +00001918 break;
Chris Lattner5931c542005-09-24 23:43:33 +00001919 }
1920 }
1921 Size >>= 1;
Reid Spencer2ec619a2007-03-23 21:24:59 +00001922 C0080Val = APIntOps::lshr(C0080Val, Size);
1923 CFF80Val = APIntOps::ashr(CFF80Val, Size);
1924 } while (Size >= 1);
Chris Lattner5931c542005-09-24 23:43:33 +00001925
Reid Spencer35c38852007-03-28 01:36:16 +00001926 // FIXME: This shouldn't be necessary. When the backends can handle types
Chris Lattner0c7a9a02008-05-19 20:25:04 +00001927 // with funny bit widths then this switch statement should be removed. It
1928 // is just here to get the size of the "middle" type back up to something
1929 // that the back ends can handle.
Reid Spencer35c38852007-03-28 01:36:16 +00001930 const Type *MiddleType = 0;
1931 switch (Size) {
1932 default: break;
Chris Lattner4de84762010-01-04 07:02:48 +00001933 case 32:
1934 case 16:
1935 case 8: MiddleType = IntegerType::get(I.getContext(), Size); break;
Reid Spencer35c38852007-03-28 01:36:16 +00001936 }
1937 if (MiddleType) {
Chris Lattner74381062009-08-30 07:44:24 +00001938 Value *NewTrunc = Builder->CreateTrunc(XorLHS, MiddleType, "sext");
Reid Spencer35c38852007-03-28 01:36:16 +00001939 return new SExtInst(NewTrunc, I.getType(), I.getName());
Chris Lattner5931c542005-09-24 23:43:33 +00001940 }
1941 }
Chris Lattner66331a42004-04-10 22:01:55 +00001942 }
Chris Lattnerb35dde12002-05-06 16:49:18 +00001943
Chris Lattner4de84762010-01-04 07:02:48 +00001944 if (I.getType() == Type::getInt1Ty(I.getContext()))
Nick Lewycky9419ddb2008-05-31 17:59:52 +00001945 return BinaryOperator::CreateXor(LHS, RHS);
1946
Nick Lewycky7d26bd82008-05-23 04:39:38 +00001947 // X + X --> X << 1
Nick Lewycky9419ddb2008-05-31 17:59:52 +00001948 if (I.getType()->isInteger()) {
Dan Gohman4ae51262009-08-12 16:23:25 +00001949 if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS)))
Owen Andersond672ecb2009-07-03 00:17:18 +00001950 return Result;
Chris Lattner7edc8c22005-04-07 17:14:51 +00001951
1952 if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
1953 if (RHSI->getOpcode() == Instruction::Sub)
1954 if (LHS == RHSI->getOperand(1)) // A + (B - A) --> B
1955 return ReplaceInstUsesWith(I, RHSI->getOperand(0));
1956 }
1957 if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
1958 if (LHSI->getOpcode() == Instruction::Sub)
1959 if (RHS == LHSI->getOperand(1)) // (B - A) + A --> B
1960 return ReplaceInstUsesWith(I, LHSI->getOperand(0));
1961 }
Robert Bocchino71698282004-07-27 21:02:21 +00001962 }
Chris Lattnere92d2f42003-08-13 04:18:28 +00001963
Chris Lattner5c4afb92002-05-08 22:46:53 +00001964 // -A + B --> B - A
Chris Lattnerdd12f962008-02-17 21:03:36 +00001965 // -A + -B --> -(A + B)
Dan Gohman186a6362009-08-12 16:04:34 +00001966 if (Value *LHSV = dyn_castNegVal(LHS)) {
Chris Lattnere10c0b92008-02-18 17:50:16 +00001967 if (LHS->getType()->isIntOrIntVector()) {
Dan Gohman186a6362009-08-12 16:04:34 +00001968 if (Value *RHSV = dyn_castNegVal(RHS)) {
Chris Lattner74381062009-08-30 07:44:24 +00001969 Value *NewAdd = Builder->CreateAdd(LHSV, RHSV, "sum");
Dan Gohman4ae51262009-08-12 16:23:25 +00001970 return BinaryOperator::CreateNeg(NewAdd);
Chris Lattnere10c0b92008-02-18 17:50:16 +00001971 }
Chris Lattnerdd12f962008-02-17 21:03:36 +00001972 }
1973
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001974 return BinaryOperator::CreateSub(RHS, LHSV);
Chris Lattnerdd12f962008-02-17 21:03:36 +00001975 }
Chris Lattnerb35dde12002-05-06 16:49:18 +00001976
1977 // A + -B --> A - B
Chris Lattner8d969642003-03-10 23:06:50 +00001978 if (!isa<Constant>(RHS))
Dan Gohman186a6362009-08-12 16:04:34 +00001979 if (Value *V = dyn_castNegVal(RHS))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001980 return BinaryOperator::CreateSub(LHS, V);
Chris Lattnerdd841ae2002-04-18 17:39:14 +00001981
Misha Brukmanfd939082005-04-21 23:48:37 +00001982
Chris Lattner50af16a2004-11-13 19:50:12 +00001983 ConstantInt *C2;
Dan Gohman186a6362009-08-12 16:04:34 +00001984 if (Value *X = dyn_castFoldableMul(LHS, C2)) {
Chris Lattner50af16a2004-11-13 19:50:12 +00001985 if (X == RHS) // X*C + X --> X * (C+1)
Dan Gohman186a6362009-08-12 16:04:34 +00001986 return BinaryOperator::CreateMul(RHS, AddOne(C2));
Chris Lattner50af16a2004-11-13 19:50:12 +00001987
1988 // X*C1 + X*C2 --> X * (C1+C2)
1989 ConstantInt *C1;
Dan Gohman186a6362009-08-12 16:04:34 +00001990 if (X == dyn_castFoldableMul(RHS, C1))
Owen Andersonbaf3c402009-07-29 18:55:55 +00001991 return BinaryOperator::CreateMul(X, ConstantExpr::getAdd(C1, C2));
Chris Lattnerad3448c2003-02-18 19:57:07 +00001992 }
1993
1994 // X + X*C --> X * (C+1)
Dan Gohman186a6362009-08-12 16:04:34 +00001995 if (dyn_castFoldableMul(RHS, C2) == LHS)
1996 return BinaryOperator::CreateMul(LHS, AddOne(C2));
Chris Lattner50af16a2004-11-13 19:50:12 +00001997
Chris Lattnere617c9e2007-01-05 02:17:46 +00001998 // X + ~X --> -1 since ~X = -X-1
Dan Gohman186a6362009-08-12 16:04:34 +00001999 if (dyn_castNotVal(LHS) == RHS ||
2000 dyn_castNotVal(RHS) == LHS)
Owen Andersona7235ea2009-07-31 20:28:14 +00002001 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnere617c9e2007-01-05 02:17:46 +00002002
Chris Lattnerad3448c2003-02-18 19:57:07 +00002003
Chris Lattner564a7272003-08-13 19:01:45 +00002004 // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
Dan Gohman4ae51262009-08-12 16:23:25 +00002005 if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
2006 if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2)))
Chris Lattnere617c9e2007-01-05 02:17:46 +00002007 return R;
Chris Lattner5e0d7182008-05-19 20:01:56 +00002008
2009 // A+B --> A|B iff A and B have no bits set in common.
2010 if (const IntegerType *IT = dyn_cast<IntegerType>(I.getType())) {
2011 APInt Mask = APInt::getAllOnesValue(IT->getBitWidth());
2012 APInt LHSKnownOne(IT->getBitWidth(), 0);
2013 APInt LHSKnownZero(IT->getBitWidth(), 0);
2014 ComputeMaskedBits(LHS, Mask, LHSKnownZero, LHSKnownOne);
2015 if (LHSKnownZero != 0) {
2016 APInt RHSKnownOne(IT->getBitWidth(), 0);
2017 APInt RHSKnownZero(IT->getBitWidth(), 0);
2018 ComputeMaskedBits(RHS, Mask, RHSKnownZero, RHSKnownOne);
2019
2020 // No bits in common -> bitwise or.
Chris Lattner9d60ba92008-05-19 20:03:53 +00002021 if ((LHSKnownZero|RHSKnownZero).isAllOnesValue())
Chris Lattner5e0d7182008-05-19 20:01:56 +00002022 return BinaryOperator::CreateOr(LHS, RHS);
Chris Lattner5e0d7182008-05-19 20:01:56 +00002023 }
2024 }
Chris Lattnerc8802d22003-03-11 00:12:48 +00002025
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002026 // W*X + Y*Z --> W * (X+Z) iff W == Y
Nick Lewycky0c2c3f62008-02-03 08:19:11 +00002027 if (I.getType()->isIntOrIntVector()) {
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002028 Value *W, *X, *Y, *Z;
Dan Gohman4ae51262009-08-12 16:23:25 +00002029 if (match(LHS, m_Mul(m_Value(W), m_Value(X))) &&
2030 match(RHS, m_Mul(m_Value(Y), m_Value(Z)))) {
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002031 if (W != Y) {
2032 if (W == Z) {
Bill Wendling587c01d2008-02-26 10:53:30 +00002033 std::swap(Y, Z);
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002034 } else if (Y == X) {
Bill Wendling587c01d2008-02-26 10:53:30 +00002035 std::swap(W, X);
2036 } else if (X == Z) {
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002037 std::swap(Y, Z);
2038 std::swap(W, X);
2039 }
2040 }
2041
2042 if (W == Y) {
Chris Lattner74381062009-08-30 07:44:24 +00002043 Value *NewAdd = Builder->CreateAdd(X, Z, LHS->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002044 return BinaryOperator::CreateMul(W, NewAdd);
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002045 }
2046 }
2047 }
2048
Chris Lattner6b032052003-10-02 15:11:26 +00002049 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
Chris Lattner4f637d42006-01-06 17:59:59 +00002050 Value *X = 0;
Dan Gohman4ae51262009-08-12 16:23:25 +00002051 if (match(LHS, m_Not(m_Value(X)))) // ~X + C --> (C-1) - X
Dan Gohman186a6362009-08-12 16:04:34 +00002052 return BinaryOperator::CreateSub(SubOne(CRHS), X);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002053
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002054 // (X & FF00) + xx00 -> (X+xx00) & FF00
Owen Andersonc7d2ce72009-07-10 17:35:01 +00002055 if (LHS->hasOneUse() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00002056 match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00002057 Constant *Anded = ConstantExpr::getAnd(CRHS, C2);
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002058 if (Anded == CRHS) {
2059 // See if all bits from the first bit set in the Add RHS up are included
2060 // in the mask. First, get the rightmost bit.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002061 const APInt& AddRHSV = CRHS->getValue();
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002062
2063 // Form a mask of all bits from the lowest bit added through the top.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002064 APInt AddRHSHighBits(~((AddRHSV & -AddRHSV)-1));
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002065
2066 // See if the and mask includes all of these bits.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002067 APInt AddRHSHighBitsAnd(AddRHSHighBits & C2->getValue());
Misha Brukmanfd939082005-04-21 23:48:37 +00002068
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002069 if (AddRHSHighBits == AddRHSHighBitsAnd) {
2070 // Okay, the xform is safe. Insert the new add pronto.
Chris Lattner74381062009-08-30 07:44:24 +00002071 Value *NewAdd = Builder->CreateAdd(X, CRHS, LHS->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002072 return BinaryOperator::CreateAnd(NewAdd, C2);
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002073 }
2074 }
2075 }
2076
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002077 // Try to fold constant add into select arguments.
2078 if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002079 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002080 return R;
Chris Lattner6b032052003-10-02 15:11:26 +00002081 }
2082
Chris Lattner42790482007-12-20 01:56:58 +00002083 // add (select X 0 (sub n A)) A --> select X A n
Christopher Lamb30f017a2007-12-18 09:34:41 +00002084 {
2085 SelectInst *SI = dyn_cast<SelectInst>(LHS);
Chris Lattner6046fb72008-11-16 04:46:19 +00002086 Value *A = RHS;
Christopher Lamb30f017a2007-12-18 09:34:41 +00002087 if (!SI) {
2088 SI = dyn_cast<SelectInst>(RHS);
Chris Lattner6046fb72008-11-16 04:46:19 +00002089 A = LHS;
Christopher Lamb30f017a2007-12-18 09:34:41 +00002090 }
Chris Lattner42790482007-12-20 01:56:58 +00002091 if (SI && SI->hasOneUse()) {
Christopher Lamb30f017a2007-12-18 09:34:41 +00002092 Value *TV = SI->getTrueValue();
2093 Value *FV = SI->getFalseValue();
Chris Lattner6046fb72008-11-16 04:46:19 +00002094 Value *N;
Christopher Lamb30f017a2007-12-18 09:34:41 +00002095
2096 // Can we fold the add into the argument of the select?
2097 // We check both true and false select arguments for a matching subtract.
Dan Gohman4ae51262009-08-12 16:23:25 +00002098 if (match(FV, m_Zero()) &&
2099 match(TV, m_Sub(m_Value(N), m_Specific(A))))
Chris Lattner6046fb72008-11-16 04:46:19 +00002100 // Fold the add into the true select value.
Gabor Greif051a9502008-04-06 20:25:17 +00002101 return SelectInst::Create(SI->getCondition(), N, A);
Dan Gohman4ae51262009-08-12 16:23:25 +00002102 if (match(TV, m_Zero()) &&
2103 match(FV, m_Sub(m_Value(N), m_Specific(A))))
Chris Lattner6046fb72008-11-16 04:46:19 +00002104 // Fold the add into the false select value.
Gabor Greif051a9502008-04-06 20:25:17 +00002105 return SelectInst::Create(SI->getCondition(), A, N);
Christopher Lamb30f017a2007-12-18 09:34:41 +00002106 }
2107 }
Andrew Lenharth16d79552006-09-19 18:24:51 +00002108
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002109 // Check for (add (sext x), y), see if we can merge this into an
2110 // integer add followed by a sext.
2111 if (SExtInst *LHSConv = dyn_cast<SExtInst>(LHS)) {
2112 // (add (sext x), cst) --> (sext (add x, cst'))
2113 if (ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS)) {
2114 Constant *CI =
Owen Andersonbaf3c402009-07-29 18:55:55 +00002115 ConstantExpr::getTrunc(RHSC, LHSConv->getOperand(0)->getType());
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002116 if (LHSConv->hasOneUse() &&
Owen Andersonbaf3c402009-07-29 18:55:55 +00002117 ConstantExpr::getSExt(CI, I.getType()) == RHSC &&
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002118 WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2119 // Insert the new, smaller add.
Dan Gohmanfe359552009-10-26 22:14:22 +00002120 Value *NewAdd = Builder->CreateNSWAdd(LHSConv->getOperand(0),
2121 CI, "addconv");
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002122 return new SExtInst(NewAdd, I.getType());
2123 }
2124 }
2125
2126 // (add (sext x), (sext y)) --> (sext (add int x, y))
2127 if (SExtInst *RHSConv = dyn_cast<SExtInst>(RHS)) {
2128 // Only do this if x/y have the same type, if at last one of them has a
2129 // single use (so we don't increase the number of sexts), and if the
2130 // integer add will not overflow.
2131 if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2132 (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2133 WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2134 RHSConv->getOperand(0))) {
2135 // Insert the new integer add.
Dan Gohmanfe359552009-10-26 22:14:22 +00002136 Value *NewAdd = Builder->CreateNSWAdd(LHSConv->getOperand(0),
2137 RHSConv->getOperand(0), "addconv");
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002138 return new SExtInst(NewAdd, I.getType());
2139 }
2140 }
2141 }
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002142
2143 return Changed ? &I : 0;
2144}
2145
2146Instruction *InstCombiner::visitFAdd(BinaryOperator &I) {
2147 bool Changed = SimplifyCommutative(I);
2148 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
2149
2150 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
2151 // X + 0 --> X
2152 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
Owen Anderson6f83c9c2009-07-27 20:59:43 +00002153 if (CFP->isExactlyValue(ConstantFP::getNegativeZero
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002154 (I.getType())->getValueAPF()))
2155 return ReplaceInstUsesWith(I, LHS);
2156 }
2157
2158 if (isa<PHINode>(LHS))
2159 if (Instruction *NV = FoldOpIntoPhi(I))
2160 return NV;
2161 }
2162
2163 // -A + B --> B - A
2164 // -A + -B --> -(A + B)
Dan Gohman186a6362009-08-12 16:04:34 +00002165 if (Value *LHSV = dyn_castFNegVal(LHS))
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002166 return BinaryOperator::CreateFSub(RHS, LHSV);
2167
2168 // A + -B --> A - B
2169 if (!isa<Constant>(RHS))
Dan Gohman186a6362009-08-12 16:04:34 +00002170 if (Value *V = dyn_castFNegVal(RHS))
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002171 return BinaryOperator::CreateFSub(LHS, V);
2172
2173 // Check for X+0.0. Simplify it to X if we know X is not -0.0.
2174 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS))
2175 if (CFP->getValueAPF().isPosZero() && CannotBeNegativeZero(LHS))
2176 return ReplaceInstUsesWith(I, LHS);
2177
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002178 // Check for (add double (sitofp x), y), see if we can merge this into an
2179 // integer add followed by a promotion.
2180 if (SIToFPInst *LHSConv = dyn_cast<SIToFPInst>(LHS)) {
2181 // (add double (sitofp x), fpcst) --> (sitofp (add int x, intcst))
2182 // ... if the constant fits in the integer value. This is useful for things
2183 // like (double)(x & 1234) + 4.0 -> (double)((X & 1234)+4) which no longer
2184 // requires a constant pool load, and generally allows the add to be better
2185 // instcombined.
2186 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS)) {
2187 Constant *CI =
Owen Andersonbaf3c402009-07-29 18:55:55 +00002188 ConstantExpr::getFPToSI(CFP, LHSConv->getOperand(0)->getType());
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002189 if (LHSConv->hasOneUse() &&
Owen Andersonbaf3c402009-07-29 18:55:55 +00002190 ConstantExpr::getSIToFP(CI, I.getType()) == CFP &&
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002191 WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2192 // Insert the new integer add.
Dan Gohmanfe359552009-10-26 22:14:22 +00002193 Value *NewAdd = Builder->CreateNSWAdd(LHSConv->getOperand(0),
2194 CI, "addconv");
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002195 return new SIToFPInst(NewAdd, I.getType());
2196 }
2197 }
2198
2199 // (add double (sitofp x), (sitofp y)) --> (sitofp (add int x, y))
2200 if (SIToFPInst *RHSConv = dyn_cast<SIToFPInst>(RHS)) {
2201 // Only do this if x/y have the same type, if at last one of them has a
2202 // single use (so we don't increase the number of int->fp conversions),
2203 // and if the integer add will not overflow.
2204 if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2205 (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2206 WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2207 RHSConv->getOperand(0))) {
2208 // Insert the new integer add.
Dan Gohmanfe359552009-10-26 22:14:22 +00002209 Value *NewAdd = Builder->CreateNSWAdd(LHSConv->getOperand(0),
Chris Lattner092543c2009-11-04 08:05:20 +00002210 RHSConv->getOperand(0),"addconv");
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002211 return new SIToFPInst(NewAdd, I.getType());
2212 }
2213 }
2214 }
2215
Chris Lattner7e708292002-06-25 16:13:24 +00002216 return Changed ? &I : 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002217}
2218
Chris Lattner092543c2009-11-04 08:05:20 +00002219
2220/// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
2221/// code necessary to compute the offset from the base pointer (without adding
2222/// in the base pointer). Return the result as a signed integer of intptr size.
2223static Value *EmitGEPOffset(User *GEP, InstCombiner &IC) {
2224 TargetData &TD = *IC.getTargetData();
2225 gep_type_iterator GTI = gep_type_begin(GEP);
2226 const Type *IntPtrTy = TD.getIntPtrType(GEP->getContext());
2227 Value *Result = Constant::getNullValue(IntPtrTy);
2228
2229 // Build a mask for high order bits.
2230 unsigned IntPtrWidth = TD.getPointerSizeInBits();
2231 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
2232
2233 for (User::op_iterator i = GEP->op_begin() + 1, e = GEP->op_end(); i != e;
2234 ++i, ++GTI) {
2235 Value *Op = *i;
2236 uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType()) & PtrSizeMask;
2237 if (ConstantInt *OpC = dyn_cast<ConstantInt>(Op)) {
2238 if (OpC->isZero()) continue;
2239
2240 // Handle a struct index, which adds its field offset to the pointer.
2241 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
2242 Size = TD.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
2243
2244 Result = IC.Builder->CreateAdd(Result,
2245 ConstantInt::get(IntPtrTy, Size),
2246 GEP->getName()+".offs");
2247 continue;
2248 }
2249
2250 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
2251 Constant *OC =
2252 ConstantExpr::getIntegerCast(OpC, IntPtrTy, true /*SExt*/);
2253 Scale = ConstantExpr::getMul(OC, Scale);
2254 // Emit an add instruction.
2255 Result = IC.Builder->CreateAdd(Result, Scale, GEP->getName()+".offs");
2256 continue;
2257 }
2258 // Convert to correct type.
2259 if (Op->getType() != IntPtrTy)
2260 Op = IC.Builder->CreateIntCast(Op, IntPtrTy, true, Op->getName()+".c");
2261 if (Size != 1) {
2262 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
2263 // We'll let instcombine(mul) convert this to a shl if possible.
2264 Op = IC.Builder->CreateMul(Op, Scale, GEP->getName()+".idx");
2265 }
2266
2267 // Emit an add instruction.
2268 Result = IC.Builder->CreateAdd(Op, Result, GEP->getName()+".offs");
2269 }
2270 return Result;
2271}
2272
2273
2274/// EvaluateGEPOffsetExpression - Return a value that can be used to compare
2275/// the *offset* implied by a GEP to zero. For example, if we have &A[i], we
2276/// want to return 'i' for "icmp ne i, 0". Note that, in general, indices can
2277/// be complex, and scales are involved. The above expression would also be
2278/// legal to codegen as "icmp ne (i*4), 0" (assuming A is a pointer to i32).
2279/// This later form is less amenable to optimization though, and we are allowed
2280/// to generate the first by knowing that pointer arithmetic doesn't overflow.
2281///
2282/// If we can't emit an optimized form for this expression, this returns null.
2283///
2284static Value *EvaluateGEPOffsetExpression(User *GEP, Instruction &I,
2285 InstCombiner &IC) {
2286 TargetData &TD = *IC.getTargetData();
2287 gep_type_iterator GTI = gep_type_begin(GEP);
2288
2289 // Check to see if this gep only has a single variable index. If so, and if
2290 // any constant indices are a multiple of its scale, then we can compute this
2291 // in terms of the scale of the variable index. For example, if the GEP
2292 // implies an offset of "12 + i*4", then we can codegen this as "3 + i",
2293 // because the expression will cross zero at the same point.
2294 unsigned i, e = GEP->getNumOperands();
2295 int64_t Offset = 0;
2296 for (i = 1; i != e; ++i, ++GTI) {
2297 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
2298 // Compute the aggregate offset of constant indices.
2299 if (CI->isZero()) continue;
2300
2301 // Handle a struct index, which adds its field offset to the pointer.
2302 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
2303 Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
2304 } else {
2305 uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
2306 Offset += Size*CI->getSExtValue();
2307 }
2308 } else {
2309 // Found our variable index.
2310 break;
2311 }
2312 }
2313
2314 // If there are no variable indices, we must have a constant offset, just
2315 // evaluate it the general way.
2316 if (i == e) return 0;
2317
2318 Value *VariableIdx = GEP->getOperand(i);
2319 // Determine the scale factor of the variable element. For example, this is
2320 // 4 if the variable index is into an array of i32.
2321 uint64_t VariableScale = TD.getTypeAllocSize(GTI.getIndexedType());
2322
2323 // Verify that there are no other variable indices. If so, emit the hard way.
2324 for (++i, ++GTI; i != e; ++i, ++GTI) {
2325 ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i));
2326 if (!CI) return 0;
2327
2328 // Compute the aggregate offset of constant indices.
2329 if (CI->isZero()) continue;
2330
2331 // Handle a struct index, which adds its field offset to the pointer.
2332 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
2333 Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
2334 } else {
2335 uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
2336 Offset += Size*CI->getSExtValue();
2337 }
2338 }
2339
2340 // Okay, we know we have a single variable index, which must be a
2341 // pointer/array/vector index. If there is no offset, life is simple, return
2342 // the index.
2343 unsigned IntPtrWidth = TD.getPointerSizeInBits();
2344 if (Offset == 0) {
2345 // Cast to intptrty in case a truncation occurs. If an extension is needed,
2346 // we don't need to bother extending: the extension won't affect where the
2347 // computation crosses zero.
2348 if (VariableIdx->getType()->getPrimitiveSizeInBits() > IntPtrWidth)
2349 VariableIdx = new TruncInst(VariableIdx,
2350 TD.getIntPtrType(VariableIdx->getContext()),
2351 VariableIdx->getName(), &I);
2352 return VariableIdx;
2353 }
2354
2355 // Otherwise, there is an index. The computation we will do will be modulo
2356 // the pointer size, so get it.
2357 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
2358
2359 Offset &= PtrSizeMask;
2360 VariableScale &= PtrSizeMask;
2361
2362 // To do this transformation, any constant index must be a multiple of the
2363 // variable scale factor. For example, we can evaluate "12 + 4*i" as "3 + i",
2364 // but we can't evaluate "10 + 3*i" in terms of i. Check that the offset is a
2365 // multiple of the variable scale.
2366 int64_t NewOffs = Offset / (int64_t)VariableScale;
2367 if (Offset != NewOffs*(int64_t)VariableScale)
2368 return 0;
2369
2370 // Okay, we can do this evaluation. Start by converting the index to intptr.
2371 const Type *IntPtrTy = TD.getIntPtrType(VariableIdx->getContext());
2372 if (VariableIdx->getType() != IntPtrTy)
2373 VariableIdx = CastInst::CreateIntegerCast(VariableIdx, IntPtrTy,
2374 true /*SExt*/,
2375 VariableIdx->getName(), &I);
2376 Constant *OffsetVal = ConstantInt::get(IntPtrTy, NewOffs);
2377 return BinaryOperator::CreateAdd(VariableIdx, OffsetVal, "offset", &I);
2378}
2379
2380
2381/// Optimize pointer differences into the same array into a size. Consider:
2382/// &A[10] - &A[0]: we should compile this to "10". LHS/RHS are the pointer
2383/// operands to the ptrtoint instructions for the LHS/RHS of the subtract.
2384///
2385Value *InstCombiner::OptimizePointerDifference(Value *LHS, Value *RHS,
2386 const Type *Ty) {
2387 assert(TD && "Must have target data info for this");
2388
2389 // If LHS is a gep based on RHS or RHS is a gep based on LHS, we can optimize
2390 // this.
2391 bool Swapped;
Chris Lattner85c1c962010-01-01 22:42:29 +00002392 GetElementPtrInst *GEP = 0;
2393 ConstantExpr *CstGEP = 0;
Chris Lattner092543c2009-11-04 08:05:20 +00002394
Chris Lattner85c1c962010-01-01 22:42:29 +00002395 // TODO: Could also optimize &A[i] - &A[j] -> "i-j", and "&A.foo[i] - &A.foo".
2396 // For now we require one side to be the base pointer "A" or a constant
2397 // expression derived from it.
2398 if (GetElementPtrInst *LHSGEP = dyn_cast<GetElementPtrInst>(LHS)) {
2399 // (gep X, ...) - X
2400 if (LHSGEP->getOperand(0) == RHS) {
2401 GEP = LHSGEP;
2402 Swapped = false;
2403 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(RHS)) {
2404 // (gep X, ...) - (ce_gep X, ...)
2405 if (CE->getOpcode() == Instruction::GetElementPtr &&
2406 LHSGEP->getOperand(0) == CE->getOperand(0)) {
2407 CstGEP = CE;
2408 GEP = LHSGEP;
2409 Swapped = false;
2410 }
2411 }
2412 }
2413
2414 if (GetElementPtrInst *RHSGEP = dyn_cast<GetElementPtrInst>(RHS)) {
2415 // X - (gep X, ...)
2416 if (RHSGEP->getOperand(0) == LHS) {
2417 GEP = RHSGEP;
2418 Swapped = true;
2419 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(LHS)) {
2420 // (ce_gep X, ...) - (gep X, ...)
2421 if (CE->getOpcode() == Instruction::GetElementPtr &&
2422 RHSGEP->getOperand(0) == CE->getOperand(0)) {
2423 CstGEP = CE;
2424 GEP = RHSGEP;
2425 Swapped = true;
2426 }
2427 }
2428 }
2429
2430 if (GEP == 0)
Chris Lattner092543c2009-11-04 08:05:20 +00002431 return 0;
2432
Chris Lattner092543c2009-11-04 08:05:20 +00002433 // Emit the offset of the GEP and an intptr_t.
2434 Value *Result = EmitGEPOffset(GEP, *this);
Chris Lattner85c1c962010-01-01 22:42:29 +00002435
2436 // If we had a constant expression GEP on the other side offsetting the
2437 // pointer, subtract it from the offset we have.
2438 if (CstGEP) {
2439 Value *CstOffset = EmitGEPOffset(CstGEP, *this);
2440 Result = Builder->CreateSub(Result, CstOffset);
2441 }
2442
Chris Lattner092543c2009-11-04 08:05:20 +00002443
2444 // If we have p - gep(p, ...) then we have to negate the result.
2445 if (Swapped)
2446 Result = Builder->CreateNeg(Result, "diff.neg");
2447
2448 return Builder->CreateIntCast(Result, Ty, true);
2449}
2450
2451
Chris Lattner7e708292002-06-25 16:13:24 +00002452Instruction *InstCombiner::visitSub(BinaryOperator &I) {
Chris Lattner7e708292002-06-25 16:13:24 +00002453 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00002454
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002455 if (Op0 == Op1) // sub X, X -> 0
Owen Andersona7235ea2009-07-31 20:28:14 +00002456 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002457
Chris Lattner3bf68152009-12-21 04:04:05 +00002458 // If this is a 'B = x-(-A)', change to B = x+A. This preserves NSW/NUW.
2459 if (Value *V = dyn_castNegVal(Op1)) {
2460 BinaryOperator *Res = BinaryOperator::CreateAdd(Op0, V);
2461 Res->setHasNoSignedWrap(I.hasNoSignedWrap());
2462 Res->setHasNoUnsignedWrap(I.hasNoUnsignedWrap());
2463 return Res;
2464 }
Chris Lattnerb35dde12002-05-06 16:49:18 +00002465
Chris Lattnere87597f2004-10-16 18:11:37 +00002466 if (isa<UndefValue>(Op0))
2467 return ReplaceInstUsesWith(I, Op0); // undef - X -> undef
2468 if (isa<UndefValue>(Op1))
2469 return ReplaceInstUsesWith(I, Op1); // X - undef -> undef
Chris Lattner4de84762010-01-04 07:02:48 +00002470 if (I.getType() == Type::getInt1Ty(I.getContext()))
Chris Lattner092543c2009-11-04 08:05:20 +00002471 return BinaryOperator::CreateXor(Op0, Op1);
2472
Chris Lattnerd65460f2003-11-05 01:06:05 +00002473 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
Chris Lattner092543c2009-11-04 08:05:20 +00002474 // Replace (-1 - A) with (~A).
Chris Lattnera2881962003-02-18 19:28:33 +00002475 if (C->isAllOnesValue())
Dan Gohman4ae51262009-08-12 16:23:25 +00002476 return BinaryOperator::CreateNot(Op1);
Chris Lattner40371712002-05-09 01:29:19 +00002477
Chris Lattnerd65460f2003-11-05 01:06:05 +00002478 // C - ~X == X + (1+C)
Reid Spencer4b828e62005-06-18 17:37:34 +00002479 Value *X = 0;
Dan Gohman4ae51262009-08-12 16:23:25 +00002480 if (match(Op1, m_Not(m_Value(X))))
Dan Gohman186a6362009-08-12 16:04:34 +00002481 return BinaryOperator::CreateAdd(X, AddOne(C));
Reid Spencer7177c3a2007-03-25 05:33:51 +00002482
Chris Lattner76b7a062007-01-15 07:02:54 +00002483 // -(X >>u 31) -> (X >>s 31)
2484 // -(X >>s 31) -> (X >>u 31)
Zhou Sheng302748d2007-03-30 17:20:39 +00002485 if (C->isZero()) {
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00002486 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op1)) {
Reid Spencer3822ff52006-11-08 06:47:33 +00002487 if (SI->getOpcode() == Instruction::LShr) {
Reid Spencerb83eb642006-10-20 07:07:24 +00002488 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
Chris Lattner9c290672004-03-12 23:53:13 +00002489 // Check to see if we are shifting out everything but the sign bit.
Zhou Sheng302748d2007-03-30 17:20:39 +00002490 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
Reid Spencerb83eb642006-10-20 07:07:24 +00002491 SI->getType()->getPrimitiveSizeInBits()-1) {
Reid Spencer3822ff52006-11-08 06:47:33 +00002492 // Ok, the transformation is safe. Insert AShr.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002493 return BinaryOperator::Create(Instruction::AShr,
Reid Spencer832254e2007-02-02 02:16:23 +00002494 SI->getOperand(0), CU, SI->getName());
Chris Lattner9c290672004-03-12 23:53:13 +00002495 }
2496 }
Chris Lattner092543c2009-11-04 08:05:20 +00002497 } else if (SI->getOpcode() == Instruction::AShr) {
Reid Spencer3822ff52006-11-08 06:47:33 +00002498 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2499 // Check to see if we are shifting out everything but the sign bit.
Zhou Sheng302748d2007-03-30 17:20:39 +00002500 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
Reid Spencer3822ff52006-11-08 06:47:33 +00002501 SI->getType()->getPrimitiveSizeInBits()-1) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00002502 // Ok, the transformation is safe. Insert LShr.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002503 return BinaryOperator::CreateLShr(
Reid Spencer832254e2007-02-02 02:16:23 +00002504 SI->getOperand(0), CU, SI->getName());
Reid Spencer3822ff52006-11-08 06:47:33 +00002505 }
2506 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00002507 }
2508 }
Chris Lattnerbfe492b2004-03-13 00:11:49 +00002509 }
Chris Lattner2eefe512004-04-09 19:05:30 +00002510
2511 // Try to fold constant sub into select arguments.
2512 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002513 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00002514 return R;
Eli Friedman709b33d2009-07-13 22:27:52 +00002515
2516 // C - zext(bool) -> bool ? C - 1 : C
2517 if (ZExtInst *ZI = dyn_cast<ZExtInst>(Op1))
Chris Lattner4de84762010-01-04 07:02:48 +00002518 if (ZI->getSrcTy() == Type::getInt1Ty(I.getContext()))
Dan Gohman186a6362009-08-12 16:04:34 +00002519 return SelectInst::Create(ZI->getOperand(0), SubOne(C), C);
Chris Lattnerd65460f2003-11-05 01:06:05 +00002520 }
2521
Chris Lattner43d84d62005-04-07 16:15:25 +00002522 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002523 if (Op1I->getOpcode() == Instruction::Add) {
Chris Lattner08954a22005-04-07 16:28:01 +00002524 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
Dan Gohman4ae51262009-08-12 16:23:25 +00002525 return BinaryOperator::CreateNeg(Op1I->getOperand(1),
Owen Anderson0a5372e2009-07-13 04:09:18 +00002526 I.getName());
Chris Lattner08954a22005-04-07 16:28:01 +00002527 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
Dan Gohman4ae51262009-08-12 16:23:25 +00002528 return BinaryOperator::CreateNeg(Op1I->getOperand(0),
Owen Anderson0a5372e2009-07-13 04:09:18 +00002529 I.getName());
Chris Lattner08954a22005-04-07 16:28:01 +00002530 else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
2531 if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
2532 // C1-(X+C2) --> (C1-C2)-X
Owen Andersond672ecb2009-07-03 00:17:18 +00002533 return BinaryOperator::CreateSub(
Owen Andersonbaf3c402009-07-29 18:55:55 +00002534 ConstantExpr::getSub(CI1, CI2), Op1I->getOperand(0));
Chris Lattner08954a22005-04-07 16:28:01 +00002535 }
Chris Lattner43d84d62005-04-07 16:15:25 +00002536 }
2537
Chris Lattnerfd059242003-10-15 16:48:29 +00002538 if (Op1I->hasOneUse()) {
Chris Lattnera2881962003-02-18 19:28:33 +00002539 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
2540 // is not used by anyone else...
2541 //
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002542 if (Op1I->getOpcode() == Instruction::Sub) {
Chris Lattnera2881962003-02-18 19:28:33 +00002543 // Swap the two operands of the subexpr...
2544 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
2545 Op1I->setOperand(0, IIOp1);
2546 Op1I->setOperand(1, IIOp0);
Misha Brukmanfd939082005-04-21 23:48:37 +00002547
Chris Lattnera2881962003-02-18 19:28:33 +00002548 // Create the new top level add instruction...
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002549 return BinaryOperator::CreateAdd(Op0, Op1);
Chris Lattnera2881962003-02-18 19:28:33 +00002550 }
2551
2552 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
2553 //
2554 if (Op1I->getOpcode() == Instruction::And &&
2555 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
2556 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
2557
Chris Lattner74381062009-08-30 07:44:24 +00002558 Value *NewNot = Builder->CreateNot(OtherOp, "B.not");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002559 return BinaryOperator::CreateAnd(Op0, NewNot);
Chris Lattnera2881962003-02-18 19:28:33 +00002560 }
Chris Lattnerad3448c2003-02-18 19:57:07 +00002561
Reid Spencerac5209e2006-10-16 23:08:08 +00002562 // 0 - (X sdiv C) -> (X sdiv -C)
Reid Spencer1628cec2006-10-26 06:15:43 +00002563 if (Op1I->getOpcode() == Instruction::SDiv)
Reid Spencerb83eb642006-10-20 07:07:24 +00002564 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
Zhou Sheng843f07672007-04-19 05:39:12 +00002565 if (CSI->isZero())
Chris Lattner91ccc152004-10-06 15:08:25 +00002566 if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002567 return BinaryOperator::CreateSDiv(Op1I->getOperand(0),
Owen Andersonbaf3c402009-07-29 18:55:55 +00002568 ConstantExpr::getNeg(DivRHS));
Chris Lattner91ccc152004-10-06 15:08:25 +00002569
Chris Lattnerad3448c2003-02-18 19:57:07 +00002570 // X - X*C --> X * (1-C)
Reid Spencer4b828e62005-06-18 17:37:34 +00002571 ConstantInt *C2 = 0;
Dan Gohman186a6362009-08-12 16:04:34 +00002572 if (dyn_castFoldableMul(Op1I, C2) == Op0) {
Owen Andersond672ecb2009-07-03 00:17:18 +00002573 Constant *CP1 =
Owen Andersonbaf3c402009-07-29 18:55:55 +00002574 ConstantExpr::getSub(ConstantInt::get(I.getType(), 1),
Dan Gohman6de29f82009-06-15 22:12:54 +00002575 C2);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002576 return BinaryOperator::CreateMul(Op0, CP1);
Chris Lattnerad3448c2003-02-18 19:57:07 +00002577 }
Chris Lattner40371712002-05-09 01:29:19 +00002578 }
Chris Lattner43d84d62005-04-07 16:15:25 +00002579 }
Chris Lattnera2881962003-02-18 19:28:33 +00002580
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002581 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
2582 if (Op0I->getOpcode() == Instruction::Add) {
2583 if (Op0I->getOperand(0) == Op1) // (Y+X)-Y == X
2584 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2585 else if (Op0I->getOperand(1) == Op1) // (X+Y)-Y == X
2586 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
2587 } else if (Op0I->getOpcode() == Instruction::Sub) {
2588 if (Op0I->getOperand(0) == Op1) // (X-Y)-X == -Y
Dan Gohman4ae51262009-08-12 16:23:25 +00002589 return BinaryOperator::CreateNeg(Op0I->getOperand(1),
Owen Anderson0a5372e2009-07-13 04:09:18 +00002590 I.getName());
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00002591 }
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002592 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002593
Chris Lattner50af16a2004-11-13 19:50:12 +00002594 ConstantInt *C1;
Dan Gohman186a6362009-08-12 16:04:34 +00002595 if (Value *X = dyn_castFoldableMul(Op0, C1)) {
Reid Spencer7177c3a2007-03-25 05:33:51 +00002596 if (X == Op1) // X*C - X --> X * (C-1)
Dan Gohman186a6362009-08-12 16:04:34 +00002597 return BinaryOperator::CreateMul(Op1, SubOne(C1));
Chris Lattnerad3448c2003-02-18 19:57:07 +00002598
Chris Lattner50af16a2004-11-13 19:50:12 +00002599 ConstantInt *C2; // X*C1 - X*C2 -> X * (C1-C2)
Dan Gohman186a6362009-08-12 16:04:34 +00002600 if (X == dyn_castFoldableMul(Op1, C2))
Owen Andersonbaf3c402009-07-29 18:55:55 +00002601 return BinaryOperator::CreateMul(X, ConstantExpr::getSub(C1, C2));
Chris Lattner50af16a2004-11-13 19:50:12 +00002602 }
Chris Lattner092543c2009-11-04 08:05:20 +00002603
2604 // Optimize pointer differences into the same array into a size. Consider:
2605 // &A[10] - &A[0]: we should compile this to "10".
2606 if (TD) {
Chris Lattner33767182010-01-01 22:12:03 +00002607 Value *LHSOp, *RHSOp;
Chris Lattnerf2ebc682010-01-01 22:29:12 +00002608 if (match(Op0, m_PtrToInt(m_Value(LHSOp))) &&
2609 match(Op1, m_PtrToInt(m_Value(RHSOp))))
Chris Lattner33767182010-01-01 22:12:03 +00002610 if (Value *Res = OptimizePointerDifference(LHSOp, RHSOp, I.getType()))
2611 return ReplaceInstUsesWith(I, Res);
Chris Lattner092543c2009-11-04 08:05:20 +00002612
2613 // trunc(p)-trunc(q) -> trunc(p-q)
Chris Lattnerf2ebc682010-01-01 22:29:12 +00002614 if (match(Op0, m_Trunc(m_PtrToInt(m_Value(LHSOp)))) &&
2615 match(Op1, m_Trunc(m_PtrToInt(m_Value(RHSOp)))))
2616 if (Value *Res = OptimizePointerDifference(LHSOp, RHSOp, I.getType()))
2617 return ReplaceInstUsesWith(I, Res);
Chris Lattner092543c2009-11-04 08:05:20 +00002618 }
2619
Chris Lattner3f5b8772002-05-06 16:14:14 +00002620 return 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002621}
2622
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002623Instruction *InstCombiner::visitFSub(BinaryOperator &I) {
2624 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2625
2626 // If this is a 'B = x-(-A)', change to B = x+A...
Dan Gohman186a6362009-08-12 16:04:34 +00002627 if (Value *V = dyn_castFNegVal(Op1))
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002628 return BinaryOperator::CreateFAdd(Op0, V);
2629
2630 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2631 if (Op1I->getOpcode() == Instruction::FAdd) {
2632 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
Dan Gohman4ae51262009-08-12 16:23:25 +00002633 return BinaryOperator::CreateFNeg(Op1I->getOperand(1),
Owen Anderson0a5372e2009-07-13 04:09:18 +00002634 I.getName());
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002635 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
Dan Gohman4ae51262009-08-12 16:23:25 +00002636 return BinaryOperator::CreateFNeg(Op1I->getOperand(0),
Owen Anderson0a5372e2009-07-13 04:09:18 +00002637 I.getName());
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002638 }
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002639 }
2640
2641 return 0;
2642}
2643
Chris Lattnera0141b92007-07-15 20:42:37 +00002644/// isSignBitCheck - Given an exploded icmp instruction, return true if the
2645/// comparison only checks the sign bit. If it only checks the sign bit, set
2646/// TrueIfSigned if the result of the comparison is true when the input value is
2647/// signed.
2648static bool isSignBitCheck(ICmpInst::Predicate pred, ConstantInt *RHS,
2649 bool &TrueIfSigned) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00002650 switch (pred) {
Chris Lattnera0141b92007-07-15 20:42:37 +00002651 case ICmpInst::ICMP_SLT: // True if LHS s< 0
2652 TrueIfSigned = true;
2653 return RHS->isZero();
Chris Lattnercb7122b2007-07-16 04:15:34 +00002654 case ICmpInst::ICMP_SLE: // True if LHS s<= RHS and RHS == -1
2655 TrueIfSigned = true;
2656 return RHS->isAllOnesValue();
Chris Lattnera0141b92007-07-15 20:42:37 +00002657 case ICmpInst::ICMP_SGT: // True if LHS s> -1
2658 TrueIfSigned = false;
2659 return RHS->isAllOnesValue();
Chris Lattnercb7122b2007-07-16 04:15:34 +00002660 case ICmpInst::ICMP_UGT:
2661 // True if LHS u> RHS and RHS == high-bit-mask - 1
2662 TrueIfSigned = true;
2663 return RHS->getValue() ==
2664 APInt::getSignedMaxValue(RHS->getType()->getPrimitiveSizeInBits());
2665 case ICmpInst::ICMP_UGE:
2666 // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc)
2667 TrueIfSigned = true;
Chris Lattner833f25d2008-06-02 01:29:46 +00002668 return RHS->getValue().isSignBit();
Chris Lattnera0141b92007-07-15 20:42:37 +00002669 default:
2670 return false;
Chris Lattner4cb170c2004-02-23 06:38:22 +00002671 }
Chris Lattner4cb170c2004-02-23 06:38:22 +00002672}
2673
Chris Lattner7e708292002-06-25 16:13:24 +00002674Instruction *InstCombiner::visitMul(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00002675 bool Changed = SimplifyCommutative(I);
Chris Lattnera2498472009-10-11 21:36:10 +00002676 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002677
Chris Lattnera2498472009-10-11 21:36:10 +00002678 if (isa<UndefValue>(Op1)) // undef * X -> 0
Owen Andersona7235ea2009-07-31 20:28:14 +00002679 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00002680
Chris Lattner8af304a2009-10-11 07:53:15 +00002681 // Simplify mul instructions with a constant RHS.
Chris Lattnera2498472009-10-11 21:36:10 +00002682 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
2683 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1C)) {
Chris Lattnere92d2f42003-08-13 04:18:28 +00002684
2685 // ((X << C1)*C2) == (X * (C2 << C1))
Reid Spencer832254e2007-02-02 02:16:23 +00002686 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op0))
Chris Lattnere92d2f42003-08-13 04:18:28 +00002687 if (SI->getOpcode() == Instruction::Shl)
2688 if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002689 return BinaryOperator::CreateMul(SI->getOperand(0),
Owen Andersonbaf3c402009-07-29 18:55:55 +00002690 ConstantExpr::getShl(CI, ShOp));
Misha Brukmanfd939082005-04-21 23:48:37 +00002691
Zhou Sheng843f07672007-04-19 05:39:12 +00002692 if (CI->isZero())
Chris Lattnera2498472009-10-11 21:36:10 +00002693 return ReplaceInstUsesWith(I, Op1C); // X * 0 == 0
Chris Lattner515c97c2003-09-11 22:24:54 +00002694 if (CI->equalsInt(1)) // X * 1 == X
2695 return ReplaceInstUsesWith(I, Op0);
2696 if (CI->isAllOnesValue()) // X * -1 == 0 - X
Dan Gohman4ae51262009-08-12 16:23:25 +00002697 return BinaryOperator::CreateNeg(Op0, I.getName());
Chris Lattner6c1ce212002-04-29 22:24:47 +00002698
Zhou Sheng97b52c22007-03-29 01:57:21 +00002699 const APInt& Val = cast<ConstantInt>(CI)->getValue();
Reid Spencerbca0e382007-03-23 20:05:17 +00002700 if (Val.isPowerOf2()) { // Replace X*(2^C) with X << C
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002701 return BinaryOperator::CreateShl(Op0,
Owen Andersoneed707b2009-07-24 23:12:02 +00002702 ConstantInt::get(Op0->getType(), Val.logBase2()));
Chris Lattnerbcd7db52005-08-02 19:16:58 +00002703 }
Chris Lattnera2498472009-10-11 21:36:10 +00002704 } else if (isa<VectorType>(Op1C->getType())) {
2705 if (Op1C->isNullValue())
2706 return ReplaceInstUsesWith(I, Op1C);
Nick Lewycky895f0852008-11-27 20:21:08 +00002707
Chris Lattnera2498472009-10-11 21:36:10 +00002708 if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1C)) {
Nick Lewycky895f0852008-11-27 20:21:08 +00002709 if (Op1V->isAllOnesValue()) // X * -1 == 0 - X
Dan Gohman4ae51262009-08-12 16:23:25 +00002710 return BinaryOperator::CreateNeg(Op0, I.getName());
Nick Lewycky895f0852008-11-27 20:21:08 +00002711
2712 // As above, vector X*splat(1.0) -> X in all defined cases.
2713 if (Constant *Splat = Op1V->getSplatValue()) {
Nick Lewycky895f0852008-11-27 20:21:08 +00002714 if (ConstantInt *CI = dyn_cast<ConstantInt>(Splat))
2715 if (CI->equalsInt(1))
2716 return ReplaceInstUsesWith(I, Op0);
2717 }
2718 }
Chris Lattnera2881962003-02-18 19:28:33 +00002719 }
Chris Lattnerab51f3f2006-03-04 06:04:02 +00002720
2721 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2722 if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
Chris Lattnera2498472009-10-11 21:36:10 +00002723 isa<ConstantInt>(Op0I->getOperand(1)) && isa<ConstantInt>(Op1C)) {
Chris Lattnerab51f3f2006-03-04 06:04:02 +00002724 // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
Chris Lattnera2498472009-10-11 21:36:10 +00002725 Value *Add = Builder->CreateMul(Op0I->getOperand(0), Op1C, "tmp");
2726 Value *C1C2 = Builder->CreateMul(Op1C, Op0I->getOperand(1));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002727 return BinaryOperator::CreateAdd(Add, C1C2);
Chris Lattnerab51f3f2006-03-04 06:04:02 +00002728
2729 }
Chris Lattner2eefe512004-04-09 19:05:30 +00002730
2731 // Try to fold constant mul into select arguments.
2732 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002733 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00002734 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00002735
2736 if (isa<PHINode>(Op0))
2737 if (Instruction *NV = FoldOpIntoPhi(I))
2738 return NV;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002739 }
2740
Dan Gohman186a6362009-08-12 16:04:34 +00002741 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
Chris Lattnera2498472009-10-11 21:36:10 +00002742 if (Value *Op1v = dyn_castNegVal(Op1))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002743 return BinaryOperator::CreateMul(Op0v, Op1v);
Chris Lattnera4f445b2003-03-10 23:23:04 +00002744
Nick Lewycky0c730792008-11-21 07:33:58 +00002745 // (X / Y) * Y = X - (X % Y)
2746 // (X / Y) * -Y = (X % Y) - X
2747 {
Chris Lattnera2498472009-10-11 21:36:10 +00002748 Value *Op1C = Op1;
Nick Lewycky0c730792008-11-21 07:33:58 +00002749 BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0);
2750 if (!BO ||
2751 (BO->getOpcode() != Instruction::UDiv &&
2752 BO->getOpcode() != Instruction::SDiv)) {
Chris Lattnera2498472009-10-11 21:36:10 +00002753 Op1C = Op0;
2754 BO = dyn_cast<BinaryOperator>(Op1);
Nick Lewycky0c730792008-11-21 07:33:58 +00002755 }
Chris Lattnera2498472009-10-11 21:36:10 +00002756 Value *Neg = dyn_castNegVal(Op1C);
Nick Lewycky0c730792008-11-21 07:33:58 +00002757 if (BO && BO->hasOneUse() &&
Chris Lattnera2498472009-10-11 21:36:10 +00002758 (BO->getOperand(1) == Op1C || BO->getOperand(1) == Neg) &&
Nick Lewycky0c730792008-11-21 07:33:58 +00002759 (BO->getOpcode() == Instruction::UDiv ||
2760 BO->getOpcode() == Instruction::SDiv)) {
2761 Value *Op0BO = BO->getOperand(0), *Op1BO = BO->getOperand(1);
2762
Dan Gohmanfa94b942009-08-12 16:33:09 +00002763 // If the division is exact, X % Y is zero.
2764 if (SDivOperator *SDiv = dyn_cast<SDivOperator>(BO))
2765 if (SDiv->isExact()) {
Chris Lattnera2498472009-10-11 21:36:10 +00002766 if (Op1BO == Op1C)
Dan Gohmanfa94b942009-08-12 16:33:09 +00002767 return ReplaceInstUsesWith(I, Op0BO);
Chris Lattnera2498472009-10-11 21:36:10 +00002768 return BinaryOperator::CreateNeg(Op0BO);
Dan Gohmanfa94b942009-08-12 16:33:09 +00002769 }
2770
Chris Lattner74381062009-08-30 07:44:24 +00002771 Value *Rem;
Nick Lewycky0c730792008-11-21 07:33:58 +00002772 if (BO->getOpcode() == Instruction::UDiv)
Chris Lattner74381062009-08-30 07:44:24 +00002773 Rem = Builder->CreateURem(Op0BO, Op1BO);
Nick Lewycky0c730792008-11-21 07:33:58 +00002774 else
Chris Lattner74381062009-08-30 07:44:24 +00002775 Rem = Builder->CreateSRem(Op0BO, Op1BO);
Nick Lewycky0c730792008-11-21 07:33:58 +00002776 Rem->takeName(BO);
2777
Chris Lattnera2498472009-10-11 21:36:10 +00002778 if (Op1BO == Op1C)
Nick Lewycky0c730792008-11-21 07:33:58 +00002779 return BinaryOperator::CreateSub(Op0BO, Rem);
Chris Lattner74381062009-08-30 07:44:24 +00002780 return BinaryOperator::CreateSub(Rem, Op0BO);
Nick Lewycky0c730792008-11-21 07:33:58 +00002781 }
2782 }
2783
Chris Lattner8af304a2009-10-11 07:53:15 +00002784 /// i1 mul -> i1 and.
Chris Lattner4de84762010-01-04 07:02:48 +00002785 if (I.getType() == Type::getInt1Ty(I.getContext()))
Chris Lattnera2498472009-10-11 21:36:10 +00002786 return BinaryOperator::CreateAnd(Op0, Op1);
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002787
Chris Lattner8af304a2009-10-11 07:53:15 +00002788 // X*(1 << Y) --> X << Y
2789 // (1 << Y)*X --> X << Y
2790 {
2791 Value *Y;
2792 if (match(Op0, m_Shl(m_One(), m_Value(Y))))
Chris Lattnera2498472009-10-11 21:36:10 +00002793 return BinaryOperator::CreateShl(Op1, Y);
2794 if (match(Op1, m_Shl(m_One(), m_Value(Y))))
Chris Lattner8af304a2009-10-11 07:53:15 +00002795 return BinaryOperator::CreateShl(Op0, Y);
2796 }
2797
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002798 // If one of the operands of the multiply is a cast from a boolean value, then
2799 // we know the bool is either zero or one, so this is a 'masking' multiply.
Chris Lattnerd2c58362009-10-11 21:29:45 +00002800 // X * Y (where Y is 0 or 1) -> X & (0-Y)
2801 if (!isa<VectorType>(I.getType())) {
2802 // -2 is "-1 << 1" so it is all bits set except the low one.
Dale Johannesenc1deda52009-10-12 18:45:32 +00002803 APInt Negative2(I.getType()->getPrimitiveSizeInBits(), (uint64_t)-2, true);
Chris Lattner0036e3a2009-10-11 21:22:21 +00002804
Chris Lattnerd2c58362009-10-11 21:29:45 +00002805 Value *BoolCast = 0, *OtherOp = 0;
2806 if (MaskedValueIsZero(Op0, Negative2))
Chris Lattnera2498472009-10-11 21:36:10 +00002807 BoolCast = Op0, OtherOp = Op1;
2808 else if (MaskedValueIsZero(Op1, Negative2))
2809 BoolCast = Op1, OtherOp = Op0;
Chris Lattnerd2c58362009-10-11 21:29:45 +00002810
Chris Lattner0036e3a2009-10-11 21:22:21 +00002811 if (BoolCast) {
Chris Lattner0036e3a2009-10-11 21:22:21 +00002812 Value *V = Builder->CreateSub(Constant::getNullValue(I.getType()),
2813 BoolCast, "tmp");
2814 return BinaryOperator::CreateAnd(V, OtherOp);
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002815 }
2816 }
2817
Chris Lattner7e708292002-06-25 16:13:24 +00002818 return Changed ? &I : 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002819}
2820
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002821Instruction *InstCombiner::visitFMul(BinaryOperator &I) {
2822 bool Changed = SimplifyCommutative(I);
Chris Lattnera2498472009-10-11 21:36:10 +00002823 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002824
2825 // Simplify mul instructions with a constant RHS...
Chris Lattnera2498472009-10-11 21:36:10 +00002826 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
2827 if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1C)) {
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002828 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
2829 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
2830 if (Op1F->isExactlyValue(1.0))
2831 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0'
Chris Lattnera2498472009-10-11 21:36:10 +00002832 } else if (isa<VectorType>(Op1C->getType())) {
2833 if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1C)) {
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002834 // As above, vector X*splat(1.0) -> X in all defined cases.
2835 if (Constant *Splat = Op1V->getSplatValue()) {
2836 if (ConstantFP *F = dyn_cast<ConstantFP>(Splat))
2837 if (F->isExactlyValue(1.0))
2838 return ReplaceInstUsesWith(I, Op0);
2839 }
2840 }
2841 }
2842
2843 // Try to fold constant mul into select arguments.
2844 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2845 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2846 return R;
2847
2848 if (isa<PHINode>(Op0))
2849 if (Instruction *NV = FoldOpIntoPhi(I))
2850 return NV;
2851 }
2852
Dan Gohman186a6362009-08-12 16:04:34 +00002853 if (Value *Op0v = dyn_castFNegVal(Op0)) // -X * -Y = X*Y
Chris Lattnera2498472009-10-11 21:36:10 +00002854 if (Value *Op1v = dyn_castFNegVal(Op1))
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002855 return BinaryOperator::CreateFMul(Op0v, Op1v);
2856
2857 return Changed ? &I : 0;
2858}
2859
Chris Lattnerfdb19e52008-07-14 00:15:52 +00002860/// SimplifyDivRemOfSelect - Try to fold a divide or remainder of a select
2861/// instruction.
2862bool InstCombiner::SimplifyDivRemOfSelect(BinaryOperator &I) {
2863 SelectInst *SI = cast<SelectInst>(I.getOperand(1));
2864
2865 // div/rem X, (Cond ? 0 : Y) -> div/rem X, Y
2866 int NonNullOperand = -1;
2867 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2868 if (ST->isNullValue())
2869 NonNullOperand = 2;
2870 // div/rem X, (Cond ? Y : 0) -> div/rem X, Y
2871 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2872 if (ST->isNullValue())
2873 NonNullOperand = 1;
2874
2875 if (NonNullOperand == -1)
2876 return false;
2877
2878 Value *SelectCond = SI->getOperand(0);
2879
2880 // Change the div/rem to use 'Y' instead of the select.
2881 I.setOperand(1, SI->getOperand(NonNullOperand));
2882
2883 // Okay, we know we replace the operand of the div/rem with 'Y' with no
2884 // problem. However, the select, or the condition of the select may have
2885 // multiple uses. Based on our knowledge that the operand must be non-zero,
2886 // propagate the known value for the select into other uses of it, and
2887 // propagate a known value of the condition into its other users.
2888
2889 // If the select and condition only have a single use, don't bother with this,
2890 // early exit.
2891 if (SI->use_empty() && SelectCond->hasOneUse())
2892 return true;
2893
2894 // Scan the current block backward, looking for other uses of SI.
2895 BasicBlock::iterator BBI = &I, BBFront = I.getParent()->begin();
2896
2897 while (BBI != BBFront) {
2898 --BBI;
2899 // If we found a call to a function, we can't assume it will return, so
2900 // information from below it cannot be propagated above it.
2901 if (isa<CallInst>(BBI) && !isa<IntrinsicInst>(BBI))
2902 break;
2903
2904 // Replace uses of the select or its condition with the known values.
2905 for (Instruction::op_iterator I = BBI->op_begin(), E = BBI->op_end();
2906 I != E; ++I) {
2907 if (*I == SI) {
2908 *I = SI->getOperand(NonNullOperand);
Chris Lattner7a1e9242009-08-30 06:13:40 +00002909 Worklist.Add(BBI);
Chris Lattnerfdb19e52008-07-14 00:15:52 +00002910 } else if (*I == SelectCond) {
Chris Lattner4de84762010-01-04 07:02:48 +00002911 *I = NonNullOperand == 1 ? ConstantInt::getTrue(BBI->getContext()) :
2912 ConstantInt::getFalse(BBI->getContext());
Chris Lattner7a1e9242009-08-30 06:13:40 +00002913 Worklist.Add(BBI);
Chris Lattnerfdb19e52008-07-14 00:15:52 +00002914 }
2915 }
2916
2917 // If we past the instruction, quit looking for it.
2918 if (&*BBI == SI)
2919 SI = 0;
2920 if (&*BBI == SelectCond)
2921 SelectCond = 0;
2922
2923 // If we ran out of things to eliminate, break out of the loop.
2924 if (SelectCond == 0 && SI == 0)
2925 break;
2926
2927 }
2928 return true;
2929}
2930
2931
Reid Spencer1628cec2006-10-26 06:15:43 +00002932/// This function implements the transforms on div instructions that work
2933/// regardless of the kind of div instruction it is (udiv, sdiv, or fdiv). It is
2934/// used by the visitors to those instructions.
2935/// @brief Transforms common to all three div instructions
Reid Spencer3da59db2006-11-27 01:05:10 +00002936Instruction *InstCombiner::commonDivTransforms(BinaryOperator &I) {
Chris Lattner857e8cd2004-12-12 21:48:58 +00002937 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnere87597f2004-10-16 18:11:37 +00002938
Chris Lattner50b2ca42008-02-19 06:12:18 +00002939 // undef / X -> 0 for integer.
2940 // undef / X -> undef for FP (the undef could be a snan).
2941 if (isa<UndefValue>(Op0)) {
2942 if (Op0->getType()->isFPOrFPVector())
2943 return ReplaceInstUsesWith(I, Op0);
Owen Andersona7235ea2009-07-31 20:28:14 +00002944 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner50b2ca42008-02-19 06:12:18 +00002945 }
Reid Spencer1628cec2006-10-26 06:15:43 +00002946
2947 // X / undef -> undef
Chris Lattner857e8cd2004-12-12 21:48:58 +00002948 if (isa<UndefValue>(Op1))
Reid Spencer1628cec2006-10-26 06:15:43 +00002949 return ReplaceInstUsesWith(I, Op1);
Chris Lattner857e8cd2004-12-12 21:48:58 +00002950
Reid Spencer1628cec2006-10-26 06:15:43 +00002951 return 0;
2952}
Misha Brukmanfd939082005-04-21 23:48:37 +00002953
Reid Spencer1628cec2006-10-26 06:15:43 +00002954/// This function implements the transforms common to both integer division
2955/// instructions (udiv and sdiv). It is called by the visitors to those integer
2956/// division instructions.
2957/// @brief Common integer divide transforms
Reid Spencer3da59db2006-11-27 01:05:10 +00002958Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
Reid Spencer1628cec2006-10-26 06:15:43 +00002959 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2960
Chris Lattnerb2ae9e32008-05-16 02:59:42 +00002961 // (sdiv X, X) --> 1 (udiv X, X) --> 1
Nick Lewycky39ac3b52008-05-23 03:26:47 +00002962 if (Op0 == Op1) {
2963 if (const VectorType *Ty = dyn_cast<VectorType>(I.getType())) {
Owen Andersoneed707b2009-07-24 23:12:02 +00002964 Constant *CI = ConstantInt::get(Ty->getElementType(), 1);
Nick Lewycky39ac3b52008-05-23 03:26:47 +00002965 std::vector<Constant*> Elts(Ty->getNumElements(), CI);
Owen Andersonaf7ec972009-07-28 21:19:26 +00002966 return ReplaceInstUsesWith(I, ConstantVector::get(Elts));
Nick Lewycky39ac3b52008-05-23 03:26:47 +00002967 }
2968
Owen Andersoneed707b2009-07-24 23:12:02 +00002969 Constant *CI = ConstantInt::get(I.getType(), 1);
Nick Lewycky39ac3b52008-05-23 03:26:47 +00002970 return ReplaceInstUsesWith(I, CI);
2971 }
Chris Lattnerb2ae9e32008-05-16 02:59:42 +00002972
Reid Spencer1628cec2006-10-26 06:15:43 +00002973 if (Instruction *Common = commonDivTransforms(I))
2974 return Common;
Chris Lattnerfdb19e52008-07-14 00:15:52 +00002975
2976 // Handle cases involving: [su]div X, (select Cond, Y, Z)
2977 // This does not apply for fdiv.
2978 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
2979 return &I;
Reid Spencer1628cec2006-10-26 06:15:43 +00002980
2981 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2982 // div X, 1 == X
2983 if (RHS->equalsInt(1))
2984 return ReplaceInstUsesWith(I, Op0);
2985
2986 // (X / C1) / C2 -> X / (C1*C2)
2987 if (Instruction *LHS = dyn_cast<Instruction>(Op0))
2988 if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
2989 if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
Owen Andersond672ecb2009-07-03 00:17:18 +00002990 if (MultiplyOverflows(RHS, LHSRHS,
Dan Gohman186a6362009-08-12 16:04:34 +00002991 I.getOpcode()==Instruction::SDiv))
Owen Andersona7235ea2009-07-31 20:28:14 +00002992 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Nick Lewyckye0cfecf2008-02-18 22:48:05 +00002993 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002994 return BinaryOperator::Create(I.getOpcode(), LHS->getOperand(0),
Owen Andersonbaf3c402009-07-29 18:55:55 +00002995 ConstantExpr::getMul(RHS, LHSRHS));
Chris Lattnerbf70b832005-04-08 04:03:26 +00002996 }
Reid Spencer1628cec2006-10-26 06:15:43 +00002997
Reid Spencerbca0e382007-03-23 20:05:17 +00002998 if (!RHS->isZero()) { // avoid X udiv 0
Reid Spencer1628cec2006-10-26 06:15:43 +00002999 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
3000 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3001 return R;
3002 if (isa<PHINode>(Op0))
3003 if (Instruction *NV = FoldOpIntoPhi(I))
3004 return NV;
3005 }
Chris Lattner8e49e082006-09-09 20:26:32 +00003006 }
Misha Brukmanfd939082005-04-21 23:48:37 +00003007
Chris Lattnera2881962003-02-18 19:28:33 +00003008 // 0 / X == 0, we don't need to preserve faults!
Chris Lattner857e8cd2004-12-12 21:48:58 +00003009 if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
Chris Lattnera2881962003-02-18 19:28:33 +00003010 if (LHS->equalsInt(0))
Owen Andersona7235ea2009-07-31 20:28:14 +00003011 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00003012
Nick Lewycky9419ddb2008-05-31 17:59:52 +00003013 // It can't be division by zero, hence it must be division by one.
Chris Lattner4de84762010-01-04 07:02:48 +00003014 if (I.getType() == Type::getInt1Ty(I.getContext()))
Nick Lewycky9419ddb2008-05-31 17:59:52 +00003015 return ReplaceInstUsesWith(I, Op0);
3016
Nick Lewycky895f0852008-11-27 20:21:08 +00003017 if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
3018 if (ConstantInt *X = cast_or_null<ConstantInt>(Op1V->getSplatValue()))
3019 // div X, 1 == X
3020 if (X->isOne())
3021 return ReplaceInstUsesWith(I, Op0);
3022 }
3023
Reid Spencer1628cec2006-10-26 06:15:43 +00003024 return 0;
3025}
3026
3027Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
3028 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3029
3030 // Handle the integer div common cases
3031 if (Instruction *Common = commonIDivTransforms(I))
3032 return Common;
3033
Reid Spencer1628cec2006-10-26 06:15:43 +00003034 if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
Nick Lewycky8ca52482008-11-27 22:41:10 +00003035 // X udiv C^2 -> X >> C
3036 // Check to see if this is an unsigned division with an exact power of 2,
3037 // if so, convert to a right shift.
Reid Spencer6eb0d992007-03-26 23:58:26 +00003038 if (C->getValue().isPowerOf2()) // 0 not included in isPowerOf2
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003039 return BinaryOperator::CreateLShr(Op0,
Owen Andersoneed707b2009-07-24 23:12:02 +00003040 ConstantInt::get(Op0->getType(), C->getValue().logBase2()));
Nick Lewycky8ca52482008-11-27 22:41:10 +00003041
3042 // X udiv C, where C >= signbit
3043 if (C->getValue().isNegative()) {
Chris Lattner74381062009-08-30 07:44:24 +00003044 Value *IC = Builder->CreateICmpULT( Op0, C);
Owen Andersona7235ea2009-07-31 20:28:14 +00003045 return SelectInst::Create(IC, Constant::getNullValue(I.getType()),
Owen Andersoneed707b2009-07-24 23:12:02 +00003046 ConstantInt::get(I.getType(), 1));
Nick Lewycky8ca52482008-11-27 22:41:10 +00003047 }
Reid Spencer1628cec2006-10-26 06:15:43 +00003048 }
3049
3050 // X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2)
Reid Spencer832254e2007-02-02 02:16:23 +00003051 if (BinaryOperator *RHSI = dyn_cast<BinaryOperator>(I.getOperand(1))) {
Reid Spencer1628cec2006-10-26 06:15:43 +00003052 if (RHSI->getOpcode() == Instruction::Shl &&
3053 isa<ConstantInt>(RHSI->getOperand(0))) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003054 const APInt& C1 = cast<ConstantInt>(RHSI->getOperand(0))->getValue();
Reid Spencerbca0e382007-03-23 20:05:17 +00003055 if (C1.isPowerOf2()) {
Reid Spencer1628cec2006-10-26 06:15:43 +00003056 Value *N = RHSI->getOperand(1);
Reid Spencer3da59db2006-11-27 01:05:10 +00003057 const Type *NTy = N->getType();
Chris Lattner74381062009-08-30 07:44:24 +00003058 if (uint32_t C2 = C1.logBase2())
3059 N = Builder->CreateAdd(N, ConstantInt::get(NTy, C2), "tmp");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003060 return BinaryOperator::CreateLShr(Op0, N);
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003061 }
3062 }
Chris Lattnerc812e5d2005-11-05 07:40:31 +00003063 }
3064
Reid Spencer1628cec2006-10-26 06:15:43 +00003065 // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
3066 // where C1&C2 are powers of two.
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003067 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Reid Spencer1628cec2006-10-26 06:15:43 +00003068 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003069 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003070 const APInt &TVA = STO->getValue(), &FVA = SFO->getValue();
Reid Spencerbca0e382007-03-23 20:05:17 +00003071 if (TVA.isPowerOf2() && FVA.isPowerOf2()) {
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003072 // Compute the shift amounts
Reid Spencerbca0e382007-03-23 20:05:17 +00003073 uint32_t TSA = TVA.logBase2(), FSA = FVA.logBase2();
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003074 // Construct the "on true" case of the select
Owen Andersoneed707b2009-07-24 23:12:02 +00003075 Constant *TC = ConstantInt::get(Op0->getType(), TSA);
Chris Lattner74381062009-08-30 07:44:24 +00003076 Value *TSI = Builder->CreateLShr(Op0, TC, SI->getName()+".t");
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003077
3078 // Construct the "on false" case of the select
Owen Andersoneed707b2009-07-24 23:12:02 +00003079 Constant *FC = ConstantInt::get(Op0->getType(), FSA);
Chris Lattner74381062009-08-30 07:44:24 +00003080 Value *FSI = Builder->CreateLShr(Op0, FC, SI->getName()+".f");
Reid Spencer1628cec2006-10-26 06:15:43 +00003081
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003082 // construct the select instruction and return it.
Gabor Greif051a9502008-04-06 20:25:17 +00003083 return SelectInst::Create(SI->getOperand(0), TSI, FSI, SI->getName());
Reid Spencer1628cec2006-10-26 06:15:43 +00003084 }
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003085 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00003086 return 0;
3087}
3088
Reid Spencer1628cec2006-10-26 06:15:43 +00003089Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
3090 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3091
3092 // Handle the integer div common cases
3093 if (Instruction *Common = commonIDivTransforms(I))
3094 return Common;
3095
3096 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3097 // sdiv X, -1 == -X
3098 if (RHS->isAllOnesValue())
Dan Gohman4ae51262009-08-12 16:23:25 +00003099 return BinaryOperator::CreateNeg(Op0);
Dan Gohman1bdf5dc2009-08-11 20:47:47 +00003100
Dan Gohmanfa94b942009-08-12 16:33:09 +00003101 // sdiv X, C --> ashr X, log2(C)
Dan Gohman1bdf5dc2009-08-11 20:47:47 +00003102 if (cast<SDivOperator>(&I)->isExact() &&
3103 RHS->getValue().isNonNegative() &&
3104 RHS->getValue().isPowerOf2()) {
3105 Value *ShAmt = llvm::ConstantInt::get(RHS->getType(),
3106 RHS->getValue().exactLogBase2());
3107 return BinaryOperator::CreateAShr(Op0, ShAmt, I.getName());
3108 }
Dan Gohman9ca9daa2009-08-12 16:37:02 +00003109
3110 // -X/C --> X/-C provided the negation doesn't overflow.
3111 if (SubOperator *Sub = dyn_cast<SubOperator>(Op0))
3112 if (isa<Constant>(Sub->getOperand(0)) &&
3113 cast<Constant>(Sub->getOperand(0))->isNullValue() &&
Dan Gohman5078f842009-08-20 17:11:38 +00003114 Sub->hasNoSignedWrap())
Dan Gohman9ca9daa2009-08-12 16:37:02 +00003115 return BinaryOperator::CreateSDiv(Sub->getOperand(1),
3116 ConstantExpr::getNeg(RHS));
Reid Spencer1628cec2006-10-26 06:15:43 +00003117 }
3118
3119 // If the sign bits of both operands are zero (i.e. we can prove they are
3120 // unsigned inputs), turn this into a udiv.
Chris Lattner42a75512007-01-15 02:27:26 +00003121 if (I.getType()->isInteger()) {
Reid Spencerbca0e382007-03-23 20:05:17 +00003122 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
Eli Friedman8be17392009-07-18 09:53:21 +00003123 if (MaskedValueIsZero(Op0, Mask)) {
3124 if (MaskedValueIsZero(Op1, Mask)) {
3125 // X sdiv Y -> X udiv Y, iff X and Y don't have sign bit set
3126 return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
3127 }
3128 ConstantInt *ShiftedInt;
Dan Gohman4ae51262009-08-12 16:23:25 +00003129 if (match(Op1, m_Shl(m_ConstantInt(ShiftedInt), m_Value())) &&
Eli Friedman8be17392009-07-18 09:53:21 +00003130 ShiftedInt->getValue().isPowerOf2()) {
3131 // X sdiv (1 << Y) -> X udiv (1 << Y) ( -> X u>> Y)
3132 // Safe because the only negative value (1 << Y) can take on is
3133 // INT_MIN, and X sdiv INT_MIN == X udiv INT_MIN == 0 if X doesn't have
3134 // the sign bit set.
3135 return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
3136 }
Reid Spencer1628cec2006-10-26 06:15:43 +00003137 }
Eli Friedman8be17392009-07-18 09:53:21 +00003138 }
Reid Spencer1628cec2006-10-26 06:15:43 +00003139
3140 return 0;
3141}
3142
3143Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
3144 return commonDivTransforms(I);
3145}
Chris Lattner3f5b8772002-05-06 16:14:14 +00003146
Reid Spencer0a783f72006-11-02 01:53:59 +00003147/// This function implements the transforms on rem instructions that work
3148/// regardless of the kind of rem instruction it is (urem, srem, or frem). It
3149/// is used by the visitors to those instructions.
3150/// @brief Transforms common to all three rem instructions
3151Instruction *InstCombiner::commonRemTransforms(BinaryOperator &I) {
Chris Lattner857e8cd2004-12-12 21:48:58 +00003152 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Reid Spencer0a783f72006-11-02 01:53:59 +00003153
Chris Lattner50b2ca42008-02-19 06:12:18 +00003154 if (isa<UndefValue>(Op0)) { // undef % X -> 0
3155 if (I.getType()->isFPOrFPVector())
3156 return ReplaceInstUsesWith(I, Op0); // X % undef -> undef (could be SNaN)
Owen Andersona7235ea2009-07-31 20:28:14 +00003157 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner50b2ca42008-02-19 06:12:18 +00003158 }
Chris Lattner19ccd5c2006-02-28 05:30:45 +00003159 if (isa<UndefValue>(Op1))
3160 return ReplaceInstUsesWith(I, Op1); // X % undef -> undef
Reid Spencer0a783f72006-11-02 01:53:59 +00003161
3162 // Handle cases involving: rem X, (select Cond, Y, Z)
Chris Lattnerfdb19e52008-07-14 00:15:52 +00003163 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
3164 return &I;
Chris Lattner5b73c082004-07-06 07:01:22 +00003165
Reid Spencer0a783f72006-11-02 01:53:59 +00003166 return 0;
3167}
3168
3169/// This function implements the transforms common to both integer remainder
3170/// instructions (urem and srem). It is called by the visitors to those integer
3171/// remainder instructions.
3172/// @brief Common integer remainder transforms
3173Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
3174 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3175
3176 if (Instruction *common = commonRemTransforms(I))
3177 return common;
3178
Dale Johannesened6af242009-01-21 00:35:19 +00003179 // 0 % X == 0 for integer, we don't need to preserve faults!
3180 if (Constant *LHS = dyn_cast<Constant>(Op0))
3181 if (LHS->isNullValue())
Owen Andersona7235ea2009-07-31 20:28:14 +00003182 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Dale Johannesened6af242009-01-21 00:35:19 +00003183
Chris Lattner857e8cd2004-12-12 21:48:58 +00003184 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner19ccd5c2006-02-28 05:30:45 +00003185 // X % 0 == undef, we don't need to preserve faults!
3186 if (RHS->equalsInt(0))
Owen Anderson9e9a0d52009-07-30 23:03:37 +00003187 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
Chris Lattner19ccd5c2006-02-28 05:30:45 +00003188
Chris Lattnera2881962003-02-18 19:28:33 +00003189 if (RHS->equalsInt(1)) // X % 1 == 0
Owen Andersona7235ea2009-07-31 20:28:14 +00003190 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00003191
Chris Lattner97943922006-02-28 05:49:21 +00003192 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
3193 if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
3194 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3195 return R;
3196 } else if (isa<PHINode>(Op0I)) {
3197 if (Instruction *NV = FoldOpIntoPhi(I))
3198 return NV;
Chris Lattner97943922006-02-28 05:49:21 +00003199 }
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00003200
3201 // See if we can fold away this rem instruction.
Chris Lattner886ab6c2009-01-31 08:15:18 +00003202 if (SimplifyDemandedInstructionBits(I))
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00003203 return &I;
Chris Lattner97943922006-02-28 05:49:21 +00003204 }
Chris Lattnera2881962003-02-18 19:28:33 +00003205 }
3206
Reid Spencer0a783f72006-11-02 01:53:59 +00003207 return 0;
3208}
3209
3210Instruction *InstCombiner::visitURem(BinaryOperator &I) {
3211 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3212
3213 if (Instruction *common = commonIRemTransforms(I))
3214 return common;
3215
3216 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3217 // X urem C^2 -> X and C
3218 // Check to see if this is an unsigned remainder with an exact power of 2,
3219 // if so, convert to a bitwise and.
3220 if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
Reid Spencerbca0e382007-03-23 20:05:17 +00003221 if (C->getValue().isPowerOf2())
Dan Gohman186a6362009-08-12 16:04:34 +00003222 return BinaryOperator::CreateAnd(Op0, SubOne(C));
Reid Spencer0a783f72006-11-02 01:53:59 +00003223 }
3224
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003225 if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
Reid Spencer0a783f72006-11-02 01:53:59 +00003226 // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)
3227 if (RHSI->getOpcode() == Instruction::Shl &&
3228 isa<ConstantInt>(RHSI->getOperand(0))) {
Zhou Sheng0fc50952007-03-25 05:01:29 +00003229 if (cast<ConstantInt>(RHSI->getOperand(0))->getValue().isPowerOf2()) {
Owen Andersona7235ea2009-07-31 20:28:14 +00003230 Constant *N1 = Constant::getAllOnesValue(I.getType());
Chris Lattner74381062009-08-30 07:44:24 +00003231 Value *Add = Builder->CreateAdd(RHSI, N1, "tmp");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003232 return BinaryOperator::CreateAnd(Op0, Add);
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003233 }
3234 }
Reid Spencer0a783f72006-11-02 01:53:59 +00003235 }
Chris Lattner8e49e082006-09-09 20:26:32 +00003236
Reid Spencer0a783f72006-11-02 01:53:59 +00003237 // urem X, (select Cond, 2^C1, 2^C2) --> select Cond, (and X, C1), (and X, C2)
3238 // where C1&C2 are powers of two.
3239 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
3240 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
3241 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
3242 // STO == 0 and SFO == 0 handled above.
Reid Spencerbca0e382007-03-23 20:05:17 +00003243 if ((STO->getValue().isPowerOf2()) &&
3244 (SFO->getValue().isPowerOf2())) {
Chris Lattner74381062009-08-30 07:44:24 +00003245 Value *TrueAnd = Builder->CreateAnd(Op0, SubOne(STO),
3246 SI->getName()+".t");
3247 Value *FalseAnd = Builder->CreateAnd(Op0, SubOne(SFO),
3248 SI->getName()+".f");
Gabor Greif051a9502008-04-06 20:25:17 +00003249 return SelectInst::Create(SI->getOperand(0), TrueAnd, FalseAnd);
Reid Spencer0a783f72006-11-02 01:53:59 +00003250 }
3251 }
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003252 }
3253
Chris Lattner3f5b8772002-05-06 16:14:14 +00003254 return 0;
3255}
3256
Reid Spencer0a783f72006-11-02 01:53:59 +00003257Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
3258 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3259
Dan Gohmancff55092007-11-05 23:16:33 +00003260 // Handle the integer rem common cases
Chris Lattnere5ecdb52009-08-30 06:22:51 +00003261 if (Instruction *Common = commonIRemTransforms(I))
3262 return Common;
Reid Spencer0a783f72006-11-02 01:53:59 +00003263
Dan Gohman186a6362009-08-12 16:04:34 +00003264 if (Value *RHSNeg = dyn_castNegVal(Op1))
Nick Lewycky23c04302008-09-03 06:24:21 +00003265 if (!isa<Constant>(RHSNeg) ||
3266 (isa<ConstantInt>(RHSNeg) &&
3267 cast<ConstantInt>(RHSNeg)->getValue().isStrictlyPositive())) {
Reid Spencer0a783f72006-11-02 01:53:59 +00003268 // X % -Y -> X % Y
Chris Lattner3c4e38e2009-08-30 06:27:41 +00003269 Worklist.AddValue(I.getOperand(1));
Reid Spencer0a783f72006-11-02 01:53:59 +00003270 I.setOperand(1, RHSNeg);
3271 return &I;
3272 }
Nick Lewyckya06cf822008-09-30 06:08:34 +00003273
Dan Gohmancff55092007-11-05 23:16:33 +00003274 // If the sign bits of both operands are zero (i.e. we can prove they are
Reid Spencer0a783f72006-11-02 01:53:59 +00003275 // unsigned inputs), turn this into a urem.
Dan Gohmancff55092007-11-05 23:16:33 +00003276 if (I.getType()->isInteger()) {
3277 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
3278 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
3279 // X srem Y -> X urem Y, iff X and Y don't have sign bit set
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003280 return BinaryOperator::CreateURem(Op0, Op1, I.getName());
Dan Gohmancff55092007-11-05 23:16:33 +00003281 }
Reid Spencer0a783f72006-11-02 01:53:59 +00003282 }
3283
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003284 // If it's a constant vector, flip any negative values positive.
Nick Lewycky9dce8732008-12-20 16:48:00 +00003285 if (ConstantVector *RHSV = dyn_cast<ConstantVector>(Op1)) {
3286 unsigned VWidth = RHSV->getNumOperands();
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003287
Nick Lewycky9dce8732008-12-20 16:48:00 +00003288 bool hasNegative = false;
3289 for (unsigned i = 0; !hasNegative && i != VWidth; ++i)
3290 if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i)))
3291 if (RHS->getValue().isNegative())
3292 hasNegative = true;
3293
3294 if (hasNegative) {
3295 std::vector<Constant *> Elts(VWidth);
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003296 for (unsigned i = 0; i != VWidth; ++i) {
3297 if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i))) {
3298 if (RHS->getValue().isNegative())
Owen Andersonbaf3c402009-07-29 18:55:55 +00003299 Elts[i] = cast<ConstantInt>(ConstantExpr::getNeg(RHS));
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003300 else
3301 Elts[i] = RHS;
3302 }
3303 }
3304
Owen Andersonaf7ec972009-07-28 21:19:26 +00003305 Constant *NewRHSV = ConstantVector::get(Elts);
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003306 if (NewRHSV != RHSV) {
Chris Lattner3c4e38e2009-08-30 06:27:41 +00003307 Worklist.AddValue(I.getOperand(1));
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003308 I.setOperand(1, NewRHSV);
3309 return &I;
3310 }
3311 }
3312 }
3313
Reid Spencer0a783f72006-11-02 01:53:59 +00003314 return 0;
3315}
3316
3317Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
Reid Spencer0a783f72006-11-02 01:53:59 +00003318 return commonRemTransforms(I);
3319}
3320
Chris Lattner457dd822004-06-09 07:59:58 +00003321// isOneBitSet - Return true if there is exactly one bit set in the specified
3322// constant.
3323static bool isOneBitSet(const ConstantInt *CI) {
Reid Spencer5f6a8952007-03-20 00:16:52 +00003324 return CI->getValue().isPowerOf2();
Chris Lattner457dd822004-06-09 07:59:58 +00003325}
3326
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00003327// isHighOnes - Return true if the constant is of the form 1+0+.
3328// This is the same as lowones(~X).
3329static bool isHighOnes(const ConstantInt *CI) {
Zhou Sheng2cde46c2007-03-20 12:49:06 +00003330 return (~CI->getValue() + 1).isPowerOf2();
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00003331}
3332
Reid Spencere4d87aa2006-12-23 06:05:41 +00003333/// getICmpCode - Encode a icmp predicate into a three bit mask. These bits
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003334/// are carefully arranged to allow folding of expressions such as:
3335///
3336/// (A < B) | (A > B) --> (A != B)
3337///
Reid Spencere4d87aa2006-12-23 06:05:41 +00003338/// Note that this is only valid if the first and second predicates have the
3339/// same sign. Is illegal to do: (A u< B) | (A s> B)
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003340///
Reid Spencere4d87aa2006-12-23 06:05:41 +00003341/// Three bits are used to represent the condition, as follows:
3342/// 0 A > B
3343/// 1 A == B
3344/// 2 A < B
3345///
3346/// <=> Value Definition
3347/// 000 0 Always false
3348/// 001 1 A > B
3349/// 010 2 A == B
3350/// 011 3 A >= B
3351/// 100 4 A < B
3352/// 101 5 A != B
3353/// 110 6 A <= B
3354/// 111 7 Always true
3355///
3356static unsigned getICmpCode(const ICmpInst *ICI) {
3357 switch (ICI->getPredicate()) {
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003358 // False -> 0
Reid Spencere4d87aa2006-12-23 06:05:41 +00003359 case ICmpInst::ICMP_UGT: return 1; // 001
3360 case ICmpInst::ICMP_SGT: return 1; // 001
3361 case ICmpInst::ICMP_EQ: return 2; // 010
3362 case ICmpInst::ICMP_UGE: return 3; // 011
3363 case ICmpInst::ICMP_SGE: return 3; // 011
3364 case ICmpInst::ICMP_ULT: return 4; // 100
3365 case ICmpInst::ICMP_SLT: return 4; // 100
3366 case ICmpInst::ICMP_NE: return 5; // 101
3367 case ICmpInst::ICMP_ULE: return 6; // 110
3368 case ICmpInst::ICMP_SLE: return 6; // 110
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003369 // True -> 7
3370 default:
Torok Edwinc23197a2009-07-14 16:55:14 +00003371 llvm_unreachable("Invalid ICmp predicate!");
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003372 return 0;
3373 }
3374}
3375
Evan Cheng8db90722008-10-14 17:15:11 +00003376/// getFCmpCode - Similar to getICmpCode but for FCmpInst. This encodes a fcmp
3377/// predicate into a three bit mask. It also returns whether it is an ordered
3378/// predicate by reference.
3379static unsigned getFCmpCode(FCmpInst::Predicate CC, bool &isOrdered) {
3380 isOrdered = false;
3381 switch (CC) {
3382 case FCmpInst::FCMP_ORD: isOrdered = true; return 0; // 000
3383 case FCmpInst::FCMP_UNO: return 0; // 000
Evan Cheng4990b252008-10-14 18:13:38 +00003384 case FCmpInst::FCMP_OGT: isOrdered = true; return 1; // 001
3385 case FCmpInst::FCMP_UGT: return 1; // 001
3386 case FCmpInst::FCMP_OEQ: isOrdered = true; return 2; // 010
3387 case FCmpInst::FCMP_UEQ: return 2; // 010
Evan Cheng8db90722008-10-14 17:15:11 +00003388 case FCmpInst::FCMP_OGE: isOrdered = true; return 3; // 011
3389 case FCmpInst::FCMP_UGE: return 3; // 011
3390 case FCmpInst::FCMP_OLT: isOrdered = true; return 4; // 100
3391 case FCmpInst::FCMP_ULT: return 4; // 100
Evan Cheng4990b252008-10-14 18:13:38 +00003392 case FCmpInst::FCMP_ONE: isOrdered = true; return 5; // 101
3393 case FCmpInst::FCMP_UNE: return 5; // 101
Evan Cheng8db90722008-10-14 17:15:11 +00003394 case FCmpInst::FCMP_OLE: isOrdered = true; return 6; // 110
3395 case FCmpInst::FCMP_ULE: return 6; // 110
Evan Cheng40300622008-10-14 18:44:08 +00003396 // True -> 7
Evan Cheng8db90722008-10-14 17:15:11 +00003397 default:
3398 // Not expecting FCMP_FALSE and FCMP_TRUE;
Torok Edwinc23197a2009-07-14 16:55:14 +00003399 llvm_unreachable("Unexpected FCmp predicate!");
Evan Cheng8db90722008-10-14 17:15:11 +00003400 return 0;
3401 }
3402}
3403
Reid Spencere4d87aa2006-12-23 06:05:41 +00003404/// getICmpValue - This is the complement of getICmpCode, which turns an
3405/// opcode and two operands into either a constant true or false, or a brand
Dan Gohman5d066ff2007-09-17 17:31:57 +00003406/// new ICmp instruction. The sign is passed in to determine which kind
Evan Cheng8db90722008-10-14 17:15:11 +00003407/// of predicate to use in the new icmp instruction.
Chris Lattner4de84762010-01-04 07:02:48 +00003408static Value *getICmpValue(bool sign, unsigned code, Value *LHS, Value *RHS) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00003409 switch (code) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003410 default: llvm_unreachable("Illegal ICmp code!");
Chris Lattner4de84762010-01-04 07:02:48 +00003411 case 0: return ConstantInt::getFalse(LHS->getContext());
Reid Spencere4d87aa2006-12-23 06:05:41 +00003412 case 1:
3413 if (sign)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003414 return new ICmpInst(ICmpInst::ICMP_SGT, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003415 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003416 return new ICmpInst(ICmpInst::ICMP_UGT, LHS, RHS);
3417 case 2: return new ICmpInst(ICmpInst::ICMP_EQ, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003418 case 3:
3419 if (sign)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003420 return new ICmpInst(ICmpInst::ICMP_SGE, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003421 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003422 return new ICmpInst(ICmpInst::ICMP_UGE, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003423 case 4:
3424 if (sign)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003425 return new ICmpInst(ICmpInst::ICMP_SLT, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003426 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003427 return new ICmpInst(ICmpInst::ICMP_ULT, LHS, RHS);
3428 case 5: return new ICmpInst(ICmpInst::ICMP_NE, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003429 case 6:
3430 if (sign)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003431 return new ICmpInst(ICmpInst::ICMP_SLE, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003432 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003433 return new ICmpInst(ICmpInst::ICMP_ULE, LHS, RHS);
Chris Lattner4de84762010-01-04 07:02:48 +00003434 case 7: return ConstantInt::getTrue(LHS->getContext());
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003435 }
3436}
3437
Evan Cheng8db90722008-10-14 17:15:11 +00003438/// getFCmpValue - This is the complement of getFCmpCode, which turns an
3439/// opcode and two operands into either a FCmp instruction. isordered is passed
3440/// in to determine which kind of predicate to use in the new fcmp instruction.
3441static Value *getFCmpValue(bool isordered, unsigned code,
Chris Lattner4de84762010-01-04 07:02:48 +00003442 Value *LHS, Value *RHS) {
Evan Cheng8db90722008-10-14 17:15:11 +00003443 switch (code) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003444 default: llvm_unreachable("Illegal FCmp code!");
Evan Cheng8db90722008-10-14 17:15:11 +00003445 case 0:
3446 if (isordered)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003447 return new FCmpInst(FCmpInst::FCMP_ORD, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003448 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003449 return new FCmpInst(FCmpInst::FCMP_UNO, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003450 case 1:
3451 if (isordered)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003452 return new FCmpInst(FCmpInst::FCMP_OGT, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003453 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003454 return new FCmpInst(FCmpInst::FCMP_UGT, LHS, RHS);
Evan Cheng4990b252008-10-14 18:13:38 +00003455 case 2:
3456 if (isordered)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003457 return new FCmpInst(FCmpInst::FCMP_OEQ, LHS, RHS);
Evan Cheng4990b252008-10-14 18:13:38 +00003458 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003459 return new FCmpInst(FCmpInst::FCMP_UEQ, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003460 case 3:
3461 if (isordered)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003462 return new FCmpInst(FCmpInst::FCMP_OGE, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003463 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003464 return new FCmpInst(FCmpInst::FCMP_UGE, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003465 case 4:
3466 if (isordered)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003467 return new FCmpInst(FCmpInst::FCMP_OLT, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003468 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003469 return new FCmpInst(FCmpInst::FCMP_ULT, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003470 case 5:
3471 if (isordered)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003472 return new FCmpInst(FCmpInst::FCMP_ONE, LHS, RHS);
Evan Cheng4990b252008-10-14 18:13:38 +00003473 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003474 return new FCmpInst(FCmpInst::FCMP_UNE, LHS, RHS);
Evan Cheng4990b252008-10-14 18:13:38 +00003475 case 6:
3476 if (isordered)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003477 return new FCmpInst(FCmpInst::FCMP_OLE, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003478 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003479 return new FCmpInst(FCmpInst::FCMP_ULE, LHS, RHS);
Chris Lattner4de84762010-01-04 07:02:48 +00003480 case 7: return ConstantInt::getTrue(LHS->getContext());
Evan Cheng8db90722008-10-14 17:15:11 +00003481 }
3482}
3483
Chris Lattnerb9553d62008-11-16 04:55:20 +00003484/// PredicatesFoldable - Return true if both predicates match sign or if at
3485/// least one of them is an equality comparison (which is signless).
Reid Spencere4d87aa2006-12-23 06:05:41 +00003486static bool PredicatesFoldable(ICmpInst::Predicate p1, ICmpInst::Predicate p2) {
Nick Lewycky4a134af2009-10-25 05:20:17 +00003487 return (CmpInst::isSigned(p1) == CmpInst::isSigned(p2)) ||
3488 (CmpInst::isSigned(p1) && ICmpInst::isEquality(p2)) ||
3489 (CmpInst::isSigned(p2) && ICmpInst::isEquality(p1));
Reid Spencere4d87aa2006-12-23 06:05:41 +00003490}
3491
3492namespace {
3493// FoldICmpLogical - Implements (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3494struct FoldICmpLogical {
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003495 InstCombiner &IC;
3496 Value *LHS, *RHS;
Reid Spencere4d87aa2006-12-23 06:05:41 +00003497 ICmpInst::Predicate pred;
3498 FoldICmpLogical(InstCombiner &ic, ICmpInst *ICI)
3499 : IC(ic), LHS(ICI->getOperand(0)), RHS(ICI->getOperand(1)),
3500 pred(ICI->getPredicate()) {}
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003501 bool shouldApply(Value *V) const {
Reid Spencere4d87aa2006-12-23 06:05:41 +00003502 if (ICmpInst *ICI = dyn_cast<ICmpInst>(V))
3503 if (PredicatesFoldable(pred, ICI->getPredicate()))
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00003504 return ((ICI->getOperand(0) == LHS && ICI->getOperand(1) == RHS) ||
3505 (ICI->getOperand(0) == RHS && ICI->getOperand(1) == LHS));
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003506 return false;
3507 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00003508 Instruction *apply(Instruction &Log) const {
3509 ICmpInst *ICI = cast<ICmpInst>(Log.getOperand(0));
3510 if (ICI->getOperand(0) != LHS) {
3511 assert(ICI->getOperand(1) == LHS);
3512 ICI->swapOperands(); // Swap the LHS and RHS of the ICmp
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003513 }
3514
Chris Lattnerbc1dbfc2007-03-13 14:27:42 +00003515 ICmpInst *RHSICI = cast<ICmpInst>(Log.getOperand(1));
Reid Spencere4d87aa2006-12-23 06:05:41 +00003516 unsigned LHSCode = getICmpCode(ICI);
Chris Lattnerbc1dbfc2007-03-13 14:27:42 +00003517 unsigned RHSCode = getICmpCode(RHSICI);
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003518 unsigned Code;
3519 switch (Log.getOpcode()) {
3520 case Instruction::And: Code = LHSCode & RHSCode; break;
3521 case Instruction::Or: Code = LHSCode | RHSCode; break;
3522 case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
Torok Edwinc23197a2009-07-14 16:55:14 +00003523 default: llvm_unreachable("Illegal logical opcode!"); return 0;
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003524 }
3525
Nick Lewycky4a134af2009-10-25 05:20:17 +00003526 bool isSigned = RHSICI->isSigned() || ICI->isSigned();
Chris Lattner4de84762010-01-04 07:02:48 +00003527 Value *RV = getICmpValue(isSigned, Code, LHS, RHS);
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003528 if (Instruction *I = dyn_cast<Instruction>(RV))
3529 return I;
3530 // Otherwise, it's a constant boolean value...
3531 return IC.ReplaceInstUsesWith(Log, RV);
3532 }
3533};
Chris Lattnerd23b5ba2006-11-15 04:53:24 +00003534} // end anonymous namespace
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003535
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003536// OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
3537// the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
Reid Spencer832254e2007-02-02 02:16:23 +00003538// guaranteed to be a binary operator.
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003539Instruction *InstCombiner::OptAndOp(Instruction *Op,
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003540 ConstantInt *OpRHS,
3541 ConstantInt *AndRHS,
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003542 BinaryOperator &TheAnd) {
3543 Value *X = Op->getOperand(0);
Chris Lattner76f7fe22004-01-12 19:47:05 +00003544 Constant *Together = 0;
Reid Spencer832254e2007-02-02 02:16:23 +00003545 if (!Op->isShift())
Owen Andersonbaf3c402009-07-29 18:55:55 +00003546 Together = ConstantExpr::getAnd(AndRHS, OpRHS);
Chris Lattner7c4049c2004-01-12 19:35:11 +00003547
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003548 switch (Op->getOpcode()) {
3549 case Instruction::Xor:
Chris Lattner6e7ba452005-01-01 16:22:27 +00003550 if (Op->hasOneUse()) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003551 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
Chris Lattner74381062009-08-30 07:44:24 +00003552 Value *And = Builder->CreateAnd(X, AndRHS);
Chris Lattner6934a042007-02-11 01:23:03 +00003553 And->takeName(Op);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003554 return BinaryOperator::CreateXor(And, Together);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003555 }
3556 break;
3557 case Instruction::Or:
Chris Lattner6e7ba452005-01-01 16:22:27 +00003558 if (Together == AndRHS) // (X | C) & C --> C
3559 return ReplaceInstUsesWith(TheAnd, AndRHS);
Misha Brukmanfd939082005-04-21 23:48:37 +00003560
Chris Lattner6e7ba452005-01-01 16:22:27 +00003561 if (Op->hasOneUse() && Together != OpRHS) {
3562 // (X | C1) & C2 --> (X | (C1&C2)) & C2
Chris Lattner74381062009-08-30 07:44:24 +00003563 Value *Or = Builder->CreateOr(X, Together);
Chris Lattner6934a042007-02-11 01:23:03 +00003564 Or->takeName(Op);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003565 return BinaryOperator::CreateAnd(Or, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003566 }
3567 break;
3568 case Instruction::Add:
Chris Lattnerfd059242003-10-15 16:48:29 +00003569 if (Op->hasOneUse()) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003570 // Adding a one to a single bit bit-field should be turned into an XOR
3571 // of the bit. First thing to check is to see if this AND is with a
3572 // single bit constant.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003573 const APInt& AndRHSV = cast<ConstantInt>(AndRHS)->getValue();
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003574
3575 // If there is only one bit set...
Chris Lattner457dd822004-06-09 07:59:58 +00003576 if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003577 // Ok, at this point, we know that we are masking the result of the
3578 // ADD down to exactly one bit. If the constant we are adding has
3579 // no bits set below this bit, then we can eliminate the ADD.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003580 const APInt& AddRHS = cast<ConstantInt>(OpRHS)->getValue();
Misha Brukmanfd939082005-04-21 23:48:37 +00003581
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003582 // Check to see if any bits below the one bit set in AndRHSV are set.
3583 if ((AddRHS & (AndRHSV-1)) == 0) {
3584 // If not, the only thing that can effect the output of the AND is
3585 // the bit specified by AndRHSV. If that bit is set, the effect of
3586 // the XOR is to toggle the bit. If it is clear, then the ADD has
3587 // no effect.
3588 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
3589 TheAnd.setOperand(0, X);
3590 return &TheAnd;
3591 } else {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003592 // Pull the XOR out of the AND.
Chris Lattner74381062009-08-30 07:44:24 +00003593 Value *NewAnd = Builder->CreateAnd(X, AndRHS);
Chris Lattner6934a042007-02-11 01:23:03 +00003594 NewAnd->takeName(Op);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003595 return BinaryOperator::CreateXor(NewAnd, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003596 }
3597 }
3598 }
3599 }
3600 break;
Chris Lattner62a355c2003-09-19 19:05:02 +00003601
3602 case Instruction::Shl: {
3603 // We know that the AND will not produce any of the bits shifted in, so if
3604 // the anded constant includes them, clear them now!
3605 //
Zhou Sheng290bec52007-03-29 08:15:12 +00003606 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003607 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +00003608 APInt ShlMask(APInt::getHighBitsSet(BitWidth, BitWidth-OpRHSVal));
Chris Lattner4de84762010-01-04 07:02:48 +00003609 ConstantInt *CI = ConstantInt::get(AndRHS->getContext(),
3610 AndRHS->getValue() & ShlMask);
Misha Brukmanfd939082005-04-21 23:48:37 +00003611
Zhou Sheng290bec52007-03-29 08:15:12 +00003612 if (CI->getValue() == ShlMask) {
3613 // Masking out bits that the shift already masks
Chris Lattner0c967662004-09-24 15:21:34 +00003614 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
3615 } else if (CI != AndRHS) { // Reducing bits set in and.
Chris Lattner62a355c2003-09-19 19:05:02 +00003616 TheAnd.setOperand(1, CI);
3617 return &TheAnd;
3618 }
3619 break;
Misha Brukmanfd939082005-04-21 23:48:37 +00003620 }
Chris Lattner4de84762010-01-04 07:02:48 +00003621 case Instruction::LShr: {
Chris Lattner62a355c2003-09-19 19:05:02 +00003622 // We know that the AND will not produce any of the bits shifted in, so if
3623 // the anded constant includes them, clear them now! This only applies to
3624 // unsigned shifts, because a signed shr may bring in set bits!
3625 //
Zhou Sheng290bec52007-03-29 08:15:12 +00003626 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003627 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +00003628 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
Chris Lattner4de84762010-01-04 07:02:48 +00003629 ConstantInt *CI = ConstantInt::get(Op->getContext(),
3630 AndRHS->getValue() & ShrMask);
Chris Lattner0c967662004-09-24 15:21:34 +00003631
Zhou Sheng290bec52007-03-29 08:15:12 +00003632 if (CI->getValue() == ShrMask) {
3633 // Masking out bits that the shift already masks.
Reid Spencer3822ff52006-11-08 06:47:33 +00003634 return ReplaceInstUsesWith(TheAnd, Op);
3635 } else if (CI != AndRHS) {
3636 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
3637 return &TheAnd;
3638 }
3639 break;
3640 }
3641 case Instruction::AShr:
3642 // Signed shr.
3643 // See if this is shifting in some sign extension, then masking it out
3644 // with an and.
3645 if (Op->hasOneUse()) {
Zhou Sheng290bec52007-03-29 08:15:12 +00003646 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003647 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +00003648 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
Chris Lattner4de84762010-01-04 07:02:48 +00003649 Constant *C = ConstantInt::get(Op->getContext(),
3650 AndRHS->getValue() & ShrMask);
Reid Spencer7eb76382006-12-13 17:19:09 +00003651 if (C == AndRHS) { // Masking out bits shifted in.
Reid Spencer17212df2006-12-12 09:18:51 +00003652 // (Val ashr C1) & C2 -> (Val lshr C1) & C2
Reid Spencer3822ff52006-11-08 06:47:33 +00003653 // Make the argument unsigned.
3654 Value *ShVal = Op->getOperand(0);
Chris Lattner74381062009-08-30 07:44:24 +00003655 ShVal = Builder->CreateLShr(ShVal, OpRHS, Op->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003656 return BinaryOperator::CreateAnd(ShVal, AndRHS, TheAnd.getName());
Chris Lattner0c967662004-09-24 15:21:34 +00003657 }
Chris Lattner62a355c2003-09-19 19:05:02 +00003658 }
3659 break;
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003660 }
3661 return 0;
3662}
3663
Chris Lattner8b170942002-08-09 23:47:40 +00003664
Chris Lattnera96879a2004-09-29 17:40:11 +00003665/// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
3666/// true, otherwise (V < Lo || V >= Hi). In pratice, we emit the more efficient
Reid Spencere4d87aa2006-12-23 06:05:41 +00003667/// (V-Lo) <u Hi-Lo. This method expects that Lo <= Hi. isSigned indicates
3668/// whether to treat the V, Lo and HI as signed or not. IB is the location to
Chris Lattnera96879a2004-09-29 17:40:11 +00003669/// insert new instructions.
3670Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
Reid Spencere4d87aa2006-12-23 06:05:41 +00003671 bool isSigned, bool Inside,
3672 Instruction &IB) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00003673 assert(cast<ConstantInt>(ConstantExpr::getICmp((isSigned ?
Reid Spencer579dca12007-01-12 04:24:46 +00003674 ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
Chris Lattnera96879a2004-09-29 17:40:11 +00003675 "Lo is not <= Hi in range emission code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00003676
Chris Lattnera96879a2004-09-29 17:40:11 +00003677 if (Inside) {
3678 if (Lo == Hi) // Trivially false.
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003679 return new ICmpInst(ICmpInst::ICMP_NE, V, V);
Misha Brukmanfd939082005-04-21 23:48:37 +00003680
Reid Spencere4d87aa2006-12-23 06:05:41 +00003681 // V >= Min && V < Hi --> V < Hi
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003682 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
Reid Spencere4e40032007-03-21 23:19:50 +00003683 ICmpInst::Predicate pred = (isSigned ?
Reid Spencere4d87aa2006-12-23 06:05:41 +00003684 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003685 return new ICmpInst(pred, V, Hi);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003686 }
3687
3688 // Emit V-Lo <u Hi-Lo
Owen Andersonbaf3c402009-07-29 18:55:55 +00003689 Constant *NegLo = ConstantExpr::getNeg(Lo);
Chris Lattner74381062009-08-30 07:44:24 +00003690 Value *Add = Builder->CreateAdd(V, NegLo, V->getName()+".off");
Owen Andersonbaf3c402009-07-29 18:55:55 +00003691 Constant *UpperBound = ConstantExpr::getAdd(NegLo, Hi);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003692 return new ICmpInst(ICmpInst::ICMP_ULT, Add, UpperBound);
Chris Lattnera96879a2004-09-29 17:40:11 +00003693 }
3694
3695 if (Lo == Hi) // Trivially true.
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003696 return new ICmpInst(ICmpInst::ICMP_EQ, V, V);
Chris Lattnera96879a2004-09-29 17:40:11 +00003697
Reid Spencere4e40032007-03-21 23:19:50 +00003698 // V < Min || V >= Hi -> V > Hi-1
Dan Gohman186a6362009-08-12 16:04:34 +00003699 Hi = SubOne(cast<ConstantInt>(Hi));
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003700 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00003701 ICmpInst::Predicate pred = (isSigned ?
3702 ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003703 return new ICmpInst(pred, V, Hi);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003704 }
Reid Spencerb83eb642006-10-20 07:07:24 +00003705
Reid Spencere4e40032007-03-21 23:19:50 +00003706 // Emit V-Lo >u Hi-1-Lo
3707 // Note that Hi has already had one subtracted from it, above.
Owen Andersonbaf3c402009-07-29 18:55:55 +00003708 ConstantInt *NegLo = cast<ConstantInt>(ConstantExpr::getNeg(Lo));
Chris Lattner74381062009-08-30 07:44:24 +00003709 Value *Add = Builder->CreateAdd(V, NegLo, V->getName()+".off");
Owen Andersonbaf3c402009-07-29 18:55:55 +00003710 Constant *LowerBound = ConstantExpr::getAdd(NegLo, Hi);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003711 return new ICmpInst(ICmpInst::ICMP_UGT, Add, LowerBound);
Chris Lattnera96879a2004-09-29 17:40:11 +00003712}
3713
Chris Lattner7203e152005-09-18 07:22:02 +00003714// isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
3715// any number of 0s on either side. The 1s are allowed to wrap from LSB to
3716// MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs. 0x0F0F0000 is
3717// not, since all 1s are not contiguous.
Zhou Sheng4351c642007-04-02 08:20:41 +00003718static bool isRunOfOnes(ConstantInt *Val, uint32_t &MB, uint32_t &ME) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003719 const APInt& V = Val->getValue();
Reid Spencerf2442522007-03-24 00:42:08 +00003720 uint32_t BitWidth = Val->getType()->getBitWidth();
3721 if (!APIntOps::isShiftedMask(BitWidth, V)) return false;
Chris Lattner7203e152005-09-18 07:22:02 +00003722
3723 // look for the first zero bit after the run of ones
Reid Spencerf2442522007-03-24 00:42:08 +00003724 MB = BitWidth - ((V - 1) ^ V).countLeadingZeros();
Chris Lattner7203e152005-09-18 07:22:02 +00003725 // look for the first non-zero bit
Reid Spencerf2442522007-03-24 00:42:08 +00003726 ME = V.getActiveBits();
Chris Lattner7203e152005-09-18 07:22:02 +00003727 return true;
3728}
3729
Chris Lattner7203e152005-09-18 07:22:02 +00003730/// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
3731/// where isSub determines whether the operator is a sub. If we can fold one of
3732/// the following xforms:
Chris Lattnerc8e77562005-09-18 04:24:45 +00003733///
3734/// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
3735/// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3736/// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3737///
3738/// return (A +/- B).
3739///
3740Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003741 ConstantInt *Mask, bool isSub,
Chris Lattnerc8e77562005-09-18 04:24:45 +00003742 Instruction &I) {
3743 Instruction *LHSI = dyn_cast<Instruction>(LHS);
3744 if (!LHSI || LHSI->getNumOperands() != 2 ||
3745 !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
3746
3747 ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
3748
3749 switch (LHSI->getOpcode()) {
3750 default: return 0;
3751 case Instruction::And:
Owen Andersonbaf3c402009-07-29 18:55:55 +00003752 if (ConstantExpr::getAnd(N, Mask) == Mask) {
Chris Lattner7203e152005-09-18 07:22:02 +00003753 // If the AndRHS is a power of two minus one (0+1+), this is simple.
Zhou Sheng00f436c2007-03-24 15:34:37 +00003754 if ((Mask->getValue().countLeadingZeros() +
3755 Mask->getValue().countPopulation()) ==
3756 Mask->getValue().getBitWidth())
Chris Lattner7203e152005-09-18 07:22:02 +00003757 break;
3758
3759 // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
3760 // part, we don't need any explicit masks to take them out of A. If that
3761 // is all N is, ignore it.
Zhou Sheng4351c642007-04-02 08:20:41 +00003762 uint32_t MB = 0, ME = 0;
Chris Lattner7203e152005-09-18 07:22:02 +00003763 if (isRunOfOnes(Mask, MB, ME)) { // begin/end bit of run, inclusive
Reid Spencerb35ae032007-03-23 18:46:34 +00003764 uint32_t BitWidth = cast<IntegerType>(RHS->getType())->getBitWidth();
Zhou Sheng290bec52007-03-29 08:15:12 +00003765 APInt Mask(APInt::getLowBitsSet(BitWidth, MB-1));
Chris Lattner3bedbd92006-02-07 07:27:52 +00003766 if (MaskedValueIsZero(RHS, Mask))
Chris Lattner7203e152005-09-18 07:22:02 +00003767 break;
3768 }
3769 }
Chris Lattnerc8e77562005-09-18 04:24:45 +00003770 return 0;
3771 case Instruction::Or:
3772 case Instruction::Xor:
Chris Lattner7203e152005-09-18 07:22:02 +00003773 // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
Zhou Sheng00f436c2007-03-24 15:34:37 +00003774 if ((Mask->getValue().countLeadingZeros() +
3775 Mask->getValue().countPopulation()) == Mask->getValue().getBitWidth()
Owen Andersonbaf3c402009-07-29 18:55:55 +00003776 && ConstantExpr::getAnd(N, Mask)->isNullValue())
Chris Lattnerc8e77562005-09-18 04:24:45 +00003777 break;
3778 return 0;
3779 }
3780
Chris Lattnerc8e77562005-09-18 04:24:45 +00003781 if (isSub)
Chris Lattner74381062009-08-30 07:44:24 +00003782 return Builder->CreateSub(LHSI->getOperand(0), RHS, "fold");
3783 return Builder->CreateAdd(LHSI->getOperand(0), RHS, "fold");
Chris Lattnerc8e77562005-09-18 04:24:45 +00003784}
3785
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003786/// FoldAndOfICmps - Fold (icmp)&(icmp) if possible.
3787Instruction *InstCombiner::FoldAndOfICmps(Instruction &I,
3788 ICmpInst *LHS, ICmpInst *RHS) {
Chris Lattnerea065fb2008-11-16 05:10:52 +00003789 Value *Val, *Val2;
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003790 ConstantInt *LHSCst, *RHSCst;
3791 ICmpInst::Predicate LHSCC, RHSCC;
3792
Chris Lattnerea065fb2008-11-16 05:10:52 +00003793 // This only handles icmp of constants: (icmp1 A, C1) & (icmp2 B, C2).
Owen Andersonc7d2ce72009-07-10 17:35:01 +00003794 if (!match(LHS, m_ICmp(LHSCC, m_Value(Val),
Dan Gohman4ae51262009-08-12 16:23:25 +00003795 m_ConstantInt(LHSCst))) ||
Owen Andersonc7d2ce72009-07-10 17:35:01 +00003796 !match(RHS, m_ICmp(RHSCC, m_Value(Val2),
Dan Gohman4ae51262009-08-12 16:23:25 +00003797 m_ConstantInt(RHSCst))))
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003798 return 0;
Chris Lattnerea065fb2008-11-16 05:10:52 +00003799
Chris Lattner3f40e232009-11-29 00:51:17 +00003800 if (LHSCst == RHSCst && LHSCC == RHSCC) {
3801 // (icmp ult A, C) & (icmp ult B, C) --> (icmp ult (A|B), C)
3802 // where C is a power of 2
3803 if (LHSCC == ICmpInst::ICMP_ULT &&
3804 LHSCst->getValue().isPowerOf2()) {
3805 Value *NewOr = Builder->CreateOr(Val, Val2);
3806 return new ICmpInst(LHSCC, NewOr, LHSCst);
3807 }
3808
3809 // (icmp eq A, 0) & (icmp eq B, 0) --> (icmp eq (A|B), 0)
3810 if (LHSCC == ICmpInst::ICMP_EQ && LHSCst->isZero()) {
3811 Value *NewOr = Builder->CreateOr(Val, Val2);
3812 return new ICmpInst(LHSCC, NewOr, LHSCst);
3813 }
Chris Lattnerea065fb2008-11-16 05:10:52 +00003814 }
3815
3816 // From here on, we only handle:
3817 // (icmp1 A, C1) & (icmp2 A, C2) --> something simpler.
3818 if (Val != Val2) return 0;
3819
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003820 // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
3821 if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
3822 RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
3823 LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
3824 RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
3825 return 0;
3826
3827 // We can't fold (ugt x, C) & (sgt x, C2).
3828 if (!PredicatesFoldable(LHSCC, RHSCC))
3829 return 0;
3830
3831 // Ensure that the larger constant is on the RHS.
Chris Lattneraa3e1572008-11-16 05:14:43 +00003832 bool ShouldSwap;
Nick Lewycky4a134af2009-10-25 05:20:17 +00003833 if (CmpInst::isSigned(LHSCC) ||
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003834 (ICmpInst::isEquality(LHSCC) &&
Nick Lewycky4a134af2009-10-25 05:20:17 +00003835 CmpInst::isSigned(RHSCC)))
Chris Lattneraa3e1572008-11-16 05:14:43 +00003836 ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003837 else
Chris Lattneraa3e1572008-11-16 05:14:43 +00003838 ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
3839
3840 if (ShouldSwap) {
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003841 std::swap(LHS, RHS);
3842 std::swap(LHSCst, RHSCst);
3843 std::swap(LHSCC, RHSCC);
3844 }
3845
3846 // At this point, we know we have have two icmp instructions
3847 // comparing a value against two constants and and'ing the result
3848 // together. Because of the above check, we know that we only have
3849 // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know
3850 // (from the FoldICmpLogical check above), that the two constants
3851 // are not equal and that the larger constant is on the RHS
3852 assert(LHSCst != RHSCst && "Compares not folded above?");
3853
3854 switch (LHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003855 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003856 case ICmpInst::ICMP_EQ:
3857 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003858 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003859 case ICmpInst::ICMP_EQ: // (X == 13 & X == 15) -> false
3860 case ICmpInst::ICMP_UGT: // (X == 13 & X > 15) -> false
3861 case ICmpInst::ICMP_SGT: // (X == 13 & X > 15) -> false
Chris Lattner4de84762010-01-04 07:02:48 +00003862 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getContext()));
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003863 case ICmpInst::ICMP_NE: // (X == 13 & X != 15) -> X == 13
3864 case ICmpInst::ICMP_ULT: // (X == 13 & X < 15) -> X == 13
3865 case ICmpInst::ICMP_SLT: // (X == 13 & X < 15) -> X == 13
3866 return ReplaceInstUsesWith(I, LHS);
3867 }
3868 case ICmpInst::ICMP_NE:
3869 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003870 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003871 case ICmpInst::ICMP_ULT:
Dan Gohman186a6362009-08-12 16:04:34 +00003872 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X u< 14) -> X < 13
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003873 return new ICmpInst(ICmpInst::ICMP_ULT, Val, LHSCst);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003874 break; // (X != 13 & X u< 15) -> no change
3875 case ICmpInst::ICMP_SLT:
Dan Gohman186a6362009-08-12 16:04:34 +00003876 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X s< 14) -> X < 13
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003877 return new ICmpInst(ICmpInst::ICMP_SLT, Val, LHSCst);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003878 break; // (X != 13 & X s< 15) -> no change
3879 case ICmpInst::ICMP_EQ: // (X != 13 & X == 15) -> X == 15
3880 case ICmpInst::ICMP_UGT: // (X != 13 & X u> 15) -> X u> 15
3881 case ICmpInst::ICMP_SGT: // (X != 13 & X s> 15) -> X s> 15
3882 return ReplaceInstUsesWith(I, RHS);
3883 case ICmpInst::ICMP_NE:
Dan Gohman186a6362009-08-12 16:04:34 +00003884 if (LHSCst == SubOne(RHSCst)){// (X != 13 & X != 14) -> X-13 >u 1
Owen Andersonbaf3c402009-07-29 18:55:55 +00003885 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
Chris Lattner74381062009-08-30 07:44:24 +00003886 Value *Add = Builder->CreateAdd(Val, AddCST, Val->getName()+".off");
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003887 return new ICmpInst(ICmpInst::ICMP_UGT, Add,
Owen Andersoneed707b2009-07-24 23:12:02 +00003888 ConstantInt::get(Add->getType(), 1));
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003889 }
3890 break; // (X != 13 & X != 15) -> no change
3891 }
3892 break;
3893 case ICmpInst::ICMP_ULT:
3894 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003895 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003896 case ICmpInst::ICMP_EQ: // (X u< 13 & X == 15) -> false
3897 case ICmpInst::ICMP_UGT: // (X u< 13 & X u> 15) -> false
Chris Lattner4de84762010-01-04 07:02:48 +00003898 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getContext()));
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003899 case ICmpInst::ICMP_SGT: // (X u< 13 & X s> 15) -> no change
3900 break;
3901 case ICmpInst::ICMP_NE: // (X u< 13 & X != 15) -> X u< 13
3902 case ICmpInst::ICMP_ULT: // (X u< 13 & X u< 15) -> X u< 13
3903 return ReplaceInstUsesWith(I, LHS);
3904 case ICmpInst::ICMP_SLT: // (X u< 13 & X s< 15) -> no change
3905 break;
3906 }
3907 break;
3908 case ICmpInst::ICMP_SLT:
3909 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003910 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003911 case ICmpInst::ICMP_EQ: // (X s< 13 & X == 15) -> false
3912 case ICmpInst::ICMP_SGT: // (X s< 13 & X s> 15) -> false
Chris Lattner4de84762010-01-04 07:02:48 +00003913 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getContext()));
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003914 case ICmpInst::ICMP_UGT: // (X s< 13 & X u> 15) -> no change
3915 break;
3916 case ICmpInst::ICMP_NE: // (X s< 13 & X != 15) -> X < 13
3917 case ICmpInst::ICMP_SLT: // (X s< 13 & X s< 15) -> X < 13
3918 return ReplaceInstUsesWith(I, LHS);
3919 case ICmpInst::ICMP_ULT: // (X s< 13 & X u< 15) -> no change
3920 break;
3921 }
3922 break;
3923 case ICmpInst::ICMP_UGT:
3924 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003925 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003926 case ICmpInst::ICMP_EQ: // (X u> 13 & X == 15) -> X == 15
3927 case ICmpInst::ICMP_UGT: // (X u> 13 & X u> 15) -> X u> 15
3928 return ReplaceInstUsesWith(I, RHS);
3929 case ICmpInst::ICMP_SGT: // (X u> 13 & X s> 15) -> no change
3930 break;
3931 case ICmpInst::ICMP_NE:
Dan Gohman186a6362009-08-12 16:04:34 +00003932 if (RHSCst == AddOne(LHSCst)) // (X u> 13 & X != 14) -> X u> 14
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003933 return new ICmpInst(LHSCC, Val, RHSCst);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003934 break; // (X u> 13 & X != 15) -> no change
Chris Lattner69d4ced2008-11-16 05:20:07 +00003935 case ICmpInst::ICMP_ULT: // (X u> 13 & X u< 15) -> (X-14) <u 1
Dan Gohman186a6362009-08-12 16:04:34 +00003936 return InsertRangeTest(Val, AddOne(LHSCst),
Owen Andersond672ecb2009-07-03 00:17:18 +00003937 RHSCst, false, true, I);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003938 case ICmpInst::ICMP_SLT: // (X u> 13 & X s< 15) -> no change
3939 break;
3940 }
3941 break;
3942 case ICmpInst::ICMP_SGT:
3943 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003944 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003945 case ICmpInst::ICMP_EQ: // (X s> 13 & X == 15) -> X == 15
3946 case ICmpInst::ICMP_SGT: // (X s> 13 & X s> 15) -> X s> 15
3947 return ReplaceInstUsesWith(I, RHS);
3948 case ICmpInst::ICMP_UGT: // (X s> 13 & X u> 15) -> no change
3949 break;
3950 case ICmpInst::ICMP_NE:
Dan Gohman186a6362009-08-12 16:04:34 +00003951 if (RHSCst == AddOne(LHSCst)) // (X s> 13 & X != 14) -> X s> 14
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003952 return new ICmpInst(LHSCC, Val, RHSCst);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003953 break; // (X s> 13 & X != 15) -> no change
Chris Lattner69d4ced2008-11-16 05:20:07 +00003954 case ICmpInst::ICMP_SLT: // (X s> 13 & X s< 15) -> (X-14) s< 1
Dan Gohman186a6362009-08-12 16:04:34 +00003955 return InsertRangeTest(Val, AddOne(LHSCst),
Owen Andersond672ecb2009-07-03 00:17:18 +00003956 RHSCst, true, true, I);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003957 case ICmpInst::ICMP_ULT: // (X s> 13 & X u< 15) -> no change
3958 break;
3959 }
3960 break;
3961 }
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003962
3963 return 0;
3964}
3965
Chris Lattner42d1be02009-07-23 05:14:02 +00003966Instruction *InstCombiner::FoldAndOfFCmps(Instruction &I, FCmpInst *LHS,
3967 FCmpInst *RHS) {
3968
3969 if (LHS->getPredicate() == FCmpInst::FCMP_ORD &&
3970 RHS->getPredicate() == FCmpInst::FCMP_ORD) {
3971 // (fcmp ord x, c) & (fcmp ord y, c) -> (fcmp ord x, y)
3972 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
3973 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
3974 // If either of the constants are nans, then the whole thing returns
3975 // false.
3976 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Chris Lattner4de84762010-01-04 07:02:48 +00003977 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getContext()));
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003978 return new FCmpInst(FCmpInst::FCMP_ORD,
Chris Lattner42d1be02009-07-23 05:14:02 +00003979 LHS->getOperand(0), RHS->getOperand(0));
3980 }
Chris Lattnerf98d2532009-07-23 05:32:17 +00003981
3982 // Handle vector zeros. This occurs because the canonical form of
3983 // "fcmp ord x,x" is "fcmp ord x, 0".
3984 if (isa<ConstantAggregateZero>(LHS->getOperand(1)) &&
3985 isa<ConstantAggregateZero>(RHS->getOperand(1)))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003986 return new FCmpInst(FCmpInst::FCMP_ORD,
Chris Lattnerf98d2532009-07-23 05:32:17 +00003987 LHS->getOperand(0), RHS->getOperand(0));
Chris Lattner42d1be02009-07-23 05:14:02 +00003988 return 0;
3989 }
3990
3991 Value *Op0LHS = LHS->getOperand(0), *Op0RHS = LHS->getOperand(1);
3992 Value *Op1LHS = RHS->getOperand(0), *Op1RHS = RHS->getOperand(1);
3993 FCmpInst::Predicate Op0CC = LHS->getPredicate(), Op1CC = RHS->getPredicate();
3994
3995
3996 if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
3997 // Swap RHS operands to match LHS.
3998 Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
3999 std::swap(Op1LHS, Op1RHS);
4000 }
4001
4002 if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
4003 // Simplify (fcmp cc0 x, y) & (fcmp cc1 x, y).
4004 if (Op0CC == Op1CC)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00004005 return new FCmpInst((FCmpInst::Predicate)Op0CC, Op0LHS, Op0RHS);
Chris Lattner42d1be02009-07-23 05:14:02 +00004006
4007 if (Op0CC == FCmpInst::FCMP_FALSE || Op1CC == FCmpInst::FCMP_FALSE)
Chris Lattner4de84762010-01-04 07:02:48 +00004008 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getContext()));
Chris Lattner42d1be02009-07-23 05:14:02 +00004009 if (Op0CC == FCmpInst::FCMP_TRUE)
4010 return ReplaceInstUsesWith(I, RHS);
4011 if (Op1CC == FCmpInst::FCMP_TRUE)
4012 return ReplaceInstUsesWith(I, LHS);
4013
4014 bool Op0Ordered;
4015 bool Op1Ordered;
4016 unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
4017 unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
4018 if (Op1Pred == 0) {
4019 std::swap(LHS, RHS);
4020 std::swap(Op0Pred, Op1Pred);
4021 std::swap(Op0Ordered, Op1Ordered);
4022 }
4023 if (Op0Pred == 0) {
4024 // uno && ueq -> uno && (uno || eq) -> ueq
4025 // ord && olt -> ord && (ord && lt) -> olt
4026 if (Op0Ordered == Op1Ordered)
4027 return ReplaceInstUsesWith(I, RHS);
4028
4029 // uno && oeq -> uno && (ord && eq) -> false
4030 // uno && ord -> false
4031 if (!Op0Ordered)
Chris Lattner4de84762010-01-04 07:02:48 +00004032 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getContext()));
Chris Lattner42d1be02009-07-23 05:14:02 +00004033 // ord && ueq -> ord && (uno || eq) -> oeq
Chris Lattner4de84762010-01-04 07:02:48 +00004034 return cast<Instruction>(getFCmpValue(true, Op1Pred, Op0LHS, Op0RHS));
Chris Lattner42d1be02009-07-23 05:14:02 +00004035 }
4036 }
4037
4038 return 0;
4039}
4040
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004041
Chris Lattner7e708292002-06-25 16:13:24 +00004042Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00004043 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00004044 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00004045
Chris Lattnerd06094f2009-11-10 00:55:12 +00004046 if (Value *V = SimplifyAndInst(Op0, Op1, TD))
4047 return ReplaceInstUsesWith(I, V);
Chris Lattner3f5b8772002-05-06 16:14:14 +00004048
Chris Lattnerf8c36f52006-02-12 08:02:11 +00004049 // See if we can simplify any instructions used by the instruction whose sole
Chris Lattner9ca96412006-02-08 03:25:32 +00004050 // purpose is to compute bits we don't care about.
Dan Gohman6de29f82009-06-15 22:12:54 +00004051 if (SimplifyDemandedInstructionBits(I))
Nick Lewycky546d6312010-01-02 15:25:44 +00004052 return &I;
Dan Gohman6de29f82009-06-15 22:12:54 +00004053
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004054 if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner7acdf1d2009-10-11 22:00:32 +00004055 const APInt &AndRHSMask = AndRHS->getValue();
Zhou Sheng3a507fd2007-04-01 17:13:37 +00004056 APInt NotAndRHS(~AndRHSMask);
Chris Lattner6e7ba452005-01-01 16:22:27 +00004057
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00004058 // Optimize a variety of ((val OP C1) & C2) combinations...
Chris Lattner7acdf1d2009-10-11 22:00:32 +00004059 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Chris Lattner6e7ba452005-01-01 16:22:27 +00004060 Value *Op0LHS = Op0I->getOperand(0);
4061 Value *Op0RHS = Op0I->getOperand(1);
4062 switch (Op0I->getOpcode()) {
Chris Lattner7acdf1d2009-10-11 22:00:32 +00004063 default: break;
Chris Lattner6e7ba452005-01-01 16:22:27 +00004064 case Instruction::Xor:
4065 case Instruction::Or:
Chris Lattnerad1e3022005-01-23 20:26:55 +00004066 // If the mask is only needed on one incoming arm, push it up.
Chris Lattner7acdf1d2009-10-11 22:00:32 +00004067 if (!Op0I->hasOneUse()) break;
4068
4069 if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
4070 // Not masking anything out for the LHS, move to RHS.
4071 Value *NewRHS = Builder->CreateAnd(Op0RHS, AndRHS,
4072 Op0RHS->getName()+".masked");
4073 return BinaryOperator::Create(Op0I->getOpcode(), Op0LHS, NewRHS);
4074 }
4075 if (!isa<Constant>(Op0RHS) &&
4076 MaskedValueIsZero(Op0RHS, NotAndRHS)) {
4077 // Not masking anything out for the RHS, move to LHS.
4078 Value *NewLHS = Builder->CreateAnd(Op0LHS, AndRHS,
4079 Op0LHS->getName()+".masked");
4080 return BinaryOperator::Create(Op0I->getOpcode(), NewLHS, Op0RHS);
Chris Lattnerad1e3022005-01-23 20:26:55 +00004081 }
4082
Chris Lattner6e7ba452005-01-01 16:22:27 +00004083 break;
Chris Lattnerc8e77562005-09-18 04:24:45 +00004084 case Instruction::Add:
Chris Lattner7203e152005-09-18 07:22:02 +00004085 // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
4086 // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
4087 // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
4088 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004089 return BinaryOperator::CreateAnd(V, AndRHS);
Chris Lattner7203e152005-09-18 07:22:02 +00004090 if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004091 return BinaryOperator::CreateAnd(V, AndRHS); // Add commutes
Chris Lattnerc8e77562005-09-18 04:24:45 +00004092 break;
4093
4094 case Instruction::Sub:
Chris Lattner7203e152005-09-18 07:22:02 +00004095 // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
4096 // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
4097 // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
4098 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004099 return BinaryOperator::CreateAnd(V, AndRHS);
Nick Lewyckyb4d1bc92008-07-09 04:32:37 +00004100
Nick Lewycky5dcc41f2008-07-10 05:51:40 +00004101 // (A - N) & AndRHS -> -N & AndRHS iff A&AndRHS==0 and AndRHS
4102 // has 1's for all bits that the subtraction with A might affect.
4103 if (Op0I->hasOneUse()) {
4104 uint32_t BitWidth = AndRHSMask.getBitWidth();
4105 uint32_t Zeros = AndRHSMask.countLeadingZeros();
4106 APInt Mask = APInt::getLowBitsSet(BitWidth, BitWidth - Zeros);
4107
Nick Lewyckyb4d1bc92008-07-09 04:32:37 +00004108 ConstantInt *A = dyn_cast<ConstantInt>(Op0LHS);
Nick Lewycky5dcc41f2008-07-10 05:51:40 +00004109 if (!(A && A->isZero()) && // avoid infinite recursion.
4110 MaskedValueIsZero(Op0LHS, Mask)) {
Chris Lattner74381062009-08-30 07:44:24 +00004111 Value *NewNeg = Builder->CreateNeg(Op0RHS);
Nick Lewyckyb4d1bc92008-07-09 04:32:37 +00004112 return BinaryOperator::CreateAnd(NewNeg, AndRHS);
4113 }
4114 }
Chris Lattnerc8e77562005-09-18 04:24:45 +00004115 break;
Nick Lewyckyd1f77bf2008-07-09 05:20:13 +00004116
4117 case Instruction::Shl:
4118 case Instruction::LShr:
4119 // (1 << x) & 1 --> zext(x == 0)
4120 // (1 >> x) & 1 --> zext(x == 0)
Nick Lewyckyd8ad4922008-07-09 07:35:26 +00004121 if (AndRHSMask == 1 && Op0LHS == AndRHS) {
Chris Lattner74381062009-08-30 07:44:24 +00004122 Value *NewICmp =
4123 Builder->CreateICmpEQ(Op0RHS, Constant::getNullValue(I.getType()));
Nick Lewyckyd1f77bf2008-07-09 05:20:13 +00004124 return new ZExtInst(NewICmp, I.getType());
4125 }
4126 break;
Chris Lattner6e7ba452005-01-01 16:22:27 +00004127 }
4128
Chris Lattner58403262003-07-23 19:25:52 +00004129 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattner6e7ba452005-01-01 16:22:27 +00004130 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00004131 return Res;
Chris Lattner6e7ba452005-01-01 16:22:27 +00004132 } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
Chris Lattner2b83af22005-08-07 07:03:10 +00004133 // If this is an integer truncation or change from signed-to-unsigned, and
4134 // if the source is an and/or with immediate, transform it. This
4135 // frequently occurs for bitfield accesses.
4136 if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
Reid Spencer3da59db2006-11-27 01:05:10 +00004137 if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
Chris Lattner2b83af22005-08-07 07:03:10 +00004138 CastOp->getNumOperands() == 2)
Chris Lattner48b59ec2009-10-26 15:40:07 +00004139 if (ConstantInt *AndCI =dyn_cast<ConstantInt>(CastOp->getOperand(1))){
Chris Lattner2b83af22005-08-07 07:03:10 +00004140 if (CastOp->getOpcode() == Instruction::And) {
4141 // Change: and (cast (and X, C1) to T), C2
Reid Spencer3da59db2006-11-27 01:05:10 +00004142 // into : and (cast X to T), trunc_or_bitcast(C1)&C2
4143 // This will fold the two constants together, which may allow
4144 // other simplifications.
Chris Lattner74381062009-08-30 07:44:24 +00004145 Value *NewCast = Builder->CreateTruncOrBitCast(
Reid Spencerd977d862006-12-12 23:36:14 +00004146 CastOp->getOperand(0), I.getType(),
4147 CastOp->getName()+".shrunk");
Reid Spencer3da59db2006-11-27 01:05:10 +00004148 // trunc_or_bitcast(C1)&C2
Chris Lattner74381062009-08-30 07:44:24 +00004149 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
Owen Andersonbaf3c402009-07-29 18:55:55 +00004150 C3 = ConstantExpr::getAnd(C3, AndRHS);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004151 return BinaryOperator::CreateAnd(NewCast, C3);
Chris Lattner2b83af22005-08-07 07:03:10 +00004152 } else if (CastOp->getOpcode() == Instruction::Or) {
4153 // Change: and (cast (or X, C1) to T), C2
4154 // into : trunc(C1)&C2 iff trunc(C1)&C2 == C2
Chris Lattner74381062009-08-30 07:44:24 +00004155 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
Owen Andersonbaf3c402009-07-29 18:55:55 +00004156 if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS)
Owen Andersond672ecb2009-07-03 00:17:18 +00004157 // trunc(C1)&C2
Chris Lattner2b83af22005-08-07 07:03:10 +00004158 return ReplaceInstUsesWith(I, AndRHS);
4159 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00004160 }
Chris Lattner2b83af22005-08-07 07:03:10 +00004161 }
Chris Lattner06782f82003-07-23 19:36:21 +00004162 }
Chris Lattner2eefe512004-04-09 19:05:30 +00004163
4164 // Try to fold constant and into select arguments.
4165 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00004166 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00004167 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00004168 if (isa<PHINode>(Op0))
4169 if (Instruction *NV = FoldOpIntoPhi(I))
4170 return NV;
Chris Lattnerc6a8aff2003-07-23 17:57:01 +00004171 }
4172
Chris Lattner5b62aa72004-06-18 06:07:51 +00004173
Misha Brukmancb6267b2004-07-30 12:50:08 +00004174 // (~A & ~B) == (~(A | B)) - De Morgan's Law
Chris Lattnerd06094f2009-11-10 00:55:12 +00004175 if (Value *Op0NotVal = dyn_castNotVal(Op0))
4176 if (Value *Op1NotVal = dyn_castNotVal(Op1))
4177 if (Op0->hasOneUse() && Op1->hasOneUse()) {
4178 Value *Or = Builder->CreateOr(Op0NotVal, Op1NotVal,
4179 I.getName()+".demorgan");
4180 return BinaryOperator::CreateNot(Or);
4181 }
4182
Chris Lattner2082ad92006-02-13 23:07:23 +00004183 {
Chris Lattner003b6202007-06-15 05:58:24 +00004184 Value *A = 0, *B = 0, *C = 0, *D = 0;
Chris Lattnerd06094f2009-11-10 00:55:12 +00004185 // (A|B) & ~(A&B) -> A^B
4186 if (match(Op0, m_Or(m_Value(A), m_Value(B))) &&
4187 match(Op1, m_Not(m_And(m_Value(C), m_Value(D)))) &&
4188 ((A == C && B == D) || (A == D && B == C)))
4189 return BinaryOperator::CreateXor(A, B);
Chris Lattner003b6202007-06-15 05:58:24 +00004190
Chris Lattnerd06094f2009-11-10 00:55:12 +00004191 // ~(A&B) & (A|B) -> A^B
4192 if (match(Op1, m_Or(m_Value(A), m_Value(B))) &&
4193 match(Op0, m_Not(m_And(m_Value(C), m_Value(D)))) &&
4194 ((A == C && B == D) || (A == D && B == C)))
4195 return BinaryOperator::CreateXor(A, B);
Chris Lattner64daab52006-04-01 08:03:55 +00004196
4197 if (Op0->hasOneUse() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00004198 match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
Chris Lattner64daab52006-04-01 08:03:55 +00004199 if (A == Op1) { // (A^B)&A -> A&(A^B)
4200 I.swapOperands(); // Simplify below
4201 std::swap(Op0, Op1);
4202 } else if (B == Op1) { // (A^B)&B -> B&(B^A)
4203 cast<BinaryOperator>(Op0)->swapOperands();
4204 I.swapOperands(); // Simplify below
4205 std::swap(Op0, Op1);
4206 }
4207 }
Bill Wendling7f0ef6b2008-11-30 13:08:13 +00004208
Chris Lattner64daab52006-04-01 08:03:55 +00004209 if (Op1->hasOneUse() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00004210 match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
Chris Lattner64daab52006-04-01 08:03:55 +00004211 if (B == Op0) { // B&(A^B) -> B&(B^A)
4212 cast<BinaryOperator>(Op1)->swapOperands();
4213 std::swap(A, B);
4214 }
Chris Lattner74381062009-08-30 07:44:24 +00004215 if (A == Op0) // A&(A^B) -> A & ~B
4216 return BinaryOperator::CreateAnd(A, Builder->CreateNot(B, "tmp"));
Chris Lattner64daab52006-04-01 08:03:55 +00004217 }
Bill Wendling7f0ef6b2008-11-30 13:08:13 +00004218
4219 // (A&((~A)|B)) -> A&B
Dan Gohman4ae51262009-08-12 16:23:25 +00004220 if (match(Op0, m_Or(m_Not(m_Specific(Op1)), m_Value(A))) ||
4221 match(Op0, m_Or(m_Value(A), m_Not(m_Specific(Op1)))))
Chris Lattnerd8aafcb2008-12-01 05:16:26 +00004222 return BinaryOperator::CreateAnd(A, Op1);
Dan Gohman4ae51262009-08-12 16:23:25 +00004223 if (match(Op1, m_Or(m_Not(m_Specific(Op0)), m_Value(A))) ||
4224 match(Op1, m_Or(m_Value(A), m_Not(m_Specific(Op0)))))
Chris Lattnerd8aafcb2008-12-01 05:16:26 +00004225 return BinaryOperator::CreateAnd(A, Op0);
Chris Lattner2082ad92006-02-13 23:07:23 +00004226 }
4227
Reid Spencere4d87aa2006-12-23 06:05:41 +00004228 if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1)) {
4229 // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
Dan Gohman186a6362009-08-12 16:04:34 +00004230 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00004231 return R;
4232
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004233 if (ICmpInst *LHS = dyn_cast<ICmpInst>(Op0))
4234 if (Instruction *Res = FoldAndOfICmps(I, LHS, RHS))
4235 return Res;
Chris Lattner955f3312004-09-28 21:48:02 +00004236 }
4237
Chris Lattner6fc205f2006-05-05 06:39:07 +00004238 // fold (and (cast A), (cast B)) -> (cast (and A, B))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004239 if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
4240 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4241 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind ?
4242 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattnerf98d2532009-07-23 05:32:17 +00004243 if (SrcTy == Op1C->getOperand(0)->getType() &&
4244 SrcTy->isIntOrIntVector() &&
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004245 // Only do this if the casts both really cause code to be generated.
Reid Spencere4d87aa2006-12-23 06:05:41 +00004246 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4247 I.getType(), TD) &&
4248 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4249 I.getType(), TD)) {
Chris Lattner74381062009-08-30 07:44:24 +00004250 Value *NewOp = Builder->CreateAnd(Op0C->getOperand(0),
4251 Op1C->getOperand(0), I.getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004252 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004253 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004254 }
Chris Lattnere511b742006-11-14 07:46:50 +00004255
4256 // (X >> Z) & (Y >> Z) -> (X&Y) >> Z for all shifts.
Reid Spencer832254e2007-02-02 02:16:23 +00004257 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4258 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4259 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
Chris Lattnere511b742006-11-14 07:46:50 +00004260 SI0->getOperand(1) == SI1->getOperand(1) &&
4261 (SI0->hasOneUse() || SI1->hasOneUse())) {
Chris Lattner74381062009-08-30 07:44:24 +00004262 Value *NewOp =
4263 Builder->CreateAnd(SI0->getOperand(0), SI1->getOperand(0),
4264 SI0->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004265 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
Reid Spencer832254e2007-02-02 02:16:23 +00004266 SI1->getOperand(1));
Chris Lattnere511b742006-11-14 07:46:50 +00004267 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004268 }
4269
Evan Cheng8db90722008-10-14 17:15:11 +00004270 // If and'ing two fcmp, try combine them into one.
Chris Lattner99c65742007-10-24 05:38:08 +00004271 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
Chris Lattner42d1be02009-07-23 05:14:02 +00004272 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
4273 if (Instruction *Res = FoldAndOfFCmps(I, LHS, RHS))
4274 return Res;
Chris Lattner99c65742007-10-24 05:38:08 +00004275 }
Nick Lewyckyb4d1bc92008-07-09 04:32:37 +00004276
Chris Lattner7e708292002-06-25 16:13:24 +00004277 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00004278}
4279
Chris Lattner8c34cd22008-10-05 02:13:19 +00004280/// CollectBSwapParts - Analyze the specified subexpression and see if it is
4281/// capable of providing pieces of a bswap. The subexpression provides pieces
4282/// of a bswap if it is proven that each of the non-zero bytes in the output of
4283/// the expression came from the corresponding "byte swapped" byte in some other
4284/// value. For example, if the current subexpression is "(shl i32 %X, 24)" then
4285/// we know that the expression deposits the low byte of %X into the high byte
4286/// of the bswap result and that all other bytes are zero. This expression is
4287/// accepted, the high byte of ByteValues is set to X to indicate a correct
4288/// match.
4289///
4290/// This function returns true if the match was unsuccessful and false if so.
4291/// On entry to the function the "OverallLeftShift" is a signed integer value
4292/// indicating the number of bytes that the subexpression is later shifted. For
4293/// example, if the expression is later right shifted by 16 bits, the
4294/// OverallLeftShift value would be -2 on entry. This is used to specify which
4295/// byte of ByteValues is actually being set.
4296///
4297/// Similarly, ByteMask is a bitmask where a bit is clear if its corresponding
4298/// byte is masked to zero by a user. For example, in (X & 255), X will be
4299/// processed with a bytemask of 1. Because bytemask is 32-bits, this limits
4300/// this function to working on up to 32-byte (256 bit) values. ByteMask is
4301/// always in the local (OverallLeftShift) coordinate space.
4302///
4303static bool CollectBSwapParts(Value *V, int OverallLeftShift, uint32_t ByteMask,
4304 SmallVector<Value*, 8> &ByteValues) {
4305 if (Instruction *I = dyn_cast<Instruction>(V)) {
4306 // If this is an or instruction, it may be an inner node of the bswap.
4307 if (I->getOpcode() == Instruction::Or) {
4308 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4309 ByteValues) ||
4310 CollectBSwapParts(I->getOperand(1), OverallLeftShift, ByteMask,
4311 ByteValues);
Chris Lattnerafe91a52006-06-15 19:07:26 +00004312 }
Chris Lattner8c34cd22008-10-05 02:13:19 +00004313
4314 // If this is a logical shift by a constant multiple of 8, recurse with
4315 // OverallLeftShift and ByteMask adjusted.
4316 if (I->isLogicalShift() && isa<ConstantInt>(I->getOperand(1))) {
4317 unsigned ShAmt =
4318 cast<ConstantInt>(I->getOperand(1))->getLimitedValue(~0U);
4319 // Ensure the shift amount is defined and of a byte value.
4320 if ((ShAmt & 7) || (ShAmt > 8*ByteValues.size()))
4321 return true;
4322
4323 unsigned ByteShift = ShAmt >> 3;
4324 if (I->getOpcode() == Instruction::Shl) {
4325 // X << 2 -> collect(X, +2)
4326 OverallLeftShift += ByteShift;
4327 ByteMask >>= ByteShift;
4328 } else {
4329 // X >>u 2 -> collect(X, -2)
4330 OverallLeftShift -= ByteShift;
4331 ByteMask <<= ByteShift;
Chris Lattnerde17ddc2008-10-08 06:42:28 +00004332 ByteMask &= (~0U >> (32-ByteValues.size()));
Chris Lattner8c34cd22008-10-05 02:13:19 +00004333 }
4334
4335 if (OverallLeftShift >= (int)ByteValues.size()) return true;
4336 if (OverallLeftShift <= -(int)ByteValues.size()) return true;
4337
4338 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4339 ByteValues);
4340 }
4341
4342 // If this is a logical 'and' with a mask that clears bytes, clear the
4343 // corresponding bytes in ByteMask.
4344 if (I->getOpcode() == Instruction::And &&
4345 isa<ConstantInt>(I->getOperand(1))) {
4346 // Scan every byte of the and mask, seeing if the byte is either 0 or 255.
4347 unsigned NumBytes = ByteValues.size();
4348 APInt Byte(I->getType()->getPrimitiveSizeInBits(), 255);
4349 const APInt &AndMask = cast<ConstantInt>(I->getOperand(1))->getValue();
4350
4351 for (unsigned i = 0; i != NumBytes; ++i, Byte <<= 8) {
4352 // If this byte is masked out by a later operation, we don't care what
4353 // the and mask is.
4354 if ((ByteMask & (1 << i)) == 0)
4355 continue;
4356
4357 // If the AndMask is all zeros for this byte, clear the bit.
4358 APInt MaskB = AndMask & Byte;
4359 if (MaskB == 0) {
4360 ByteMask &= ~(1U << i);
4361 continue;
4362 }
4363
4364 // If the AndMask is not all ones for this byte, it's not a bytezap.
4365 if (MaskB != Byte)
4366 return true;
4367
4368 // Otherwise, this byte is kept.
4369 }
4370
4371 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4372 ByteValues);
4373 }
Chris Lattnerafe91a52006-06-15 19:07:26 +00004374 }
4375
Chris Lattner8c34cd22008-10-05 02:13:19 +00004376 // Okay, we got to something that isn't a shift, 'or' or 'and'. This must be
4377 // the input value to the bswap. Some observations: 1) if more than one byte
4378 // is demanded from this input, then it could not be successfully assembled
4379 // into a byteswap. At least one of the two bytes would not be aligned with
4380 // their ultimate destination.
4381 if (!isPowerOf2_32(ByteMask)) return true;
4382 unsigned InputByteNo = CountTrailingZeros_32(ByteMask);
Chris Lattnerafe91a52006-06-15 19:07:26 +00004383
Chris Lattner8c34cd22008-10-05 02:13:19 +00004384 // 2) The input and ultimate destinations must line up: if byte 3 of an i32
4385 // is demanded, it needs to go into byte 0 of the result. This means that the
4386 // byte needs to be shifted until it lands in the right byte bucket. The
4387 // shift amount depends on the position: if the byte is coming from the high
4388 // part of the value (e.g. byte 3) then it must be shifted right. If from the
4389 // low part, it must be shifted left.
4390 unsigned DestByteNo = InputByteNo + OverallLeftShift;
4391 if (InputByteNo < ByteValues.size()/2) {
4392 if (ByteValues.size()-1-DestByteNo != InputByteNo)
4393 return true;
4394 } else {
4395 if (ByteValues.size()-1-DestByteNo != InputByteNo)
4396 return true;
4397 }
Chris Lattnerafe91a52006-06-15 19:07:26 +00004398
4399 // If the destination byte value is already defined, the values are or'd
4400 // together, which isn't a bswap (unless it's an or of the same bits).
Chris Lattner8c34cd22008-10-05 02:13:19 +00004401 if (ByteValues[DestByteNo] && ByteValues[DestByteNo] != V)
Chris Lattnerafe91a52006-06-15 19:07:26 +00004402 return true;
Chris Lattner8c34cd22008-10-05 02:13:19 +00004403 ByteValues[DestByteNo] = V;
Chris Lattnerafe91a52006-06-15 19:07:26 +00004404 return false;
4405}
4406
4407/// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
4408/// If so, insert the new bswap intrinsic and return it.
4409Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
Chris Lattner55fc8c42007-04-01 20:57:36 +00004410 const IntegerType *ITy = dyn_cast<IntegerType>(I.getType());
Chris Lattner8c34cd22008-10-05 02:13:19 +00004411 if (!ITy || ITy->getBitWidth() % 16 ||
4412 // ByteMask only allows up to 32-byte values.
4413 ITy->getBitWidth() > 32*8)
Chris Lattner55fc8c42007-04-01 20:57:36 +00004414 return 0; // Can only bswap pairs of bytes. Can't do vectors.
Chris Lattnerafe91a52006-06-15 19:07:26 +00004415
4416 /// ByteValues - For each byte of the result, we keep track of which value
4417 /// defines each byte.
Chris Lattner535014f2007-02-15 22:52:10 +00004418 SmallVector<Value*, 8> ByteValues;
Chris Lattner55fc8c42007-04-01 20:57:36 +00004419 ByteValues.resize(ITy->getBitWidth()/8);
Chris Lattnerafe91a52006-06-15 19:07:26 +00004420
4421 // Try to find all the pieces corresponding to the bswap.
Chris Lattner8c34cd22008-10-05 02:13:19 +00004422 uint32_t ByteMask = ~0U >> (32-ByteValues.size());
4423 if (CollectBSwapParts(&I, 0, ByteMask, ByteValues))
Chris Lattnerafe91a52006-06-15 19:07:26 +00004424 return 0;
4425
4426 // Check to see if all of the bytes come from the same value.
4427 Value *V = ByteValues[0];
4428 if (V == 0) return 0; // Didn't find a byte? Must be zero.
4429
4430 // Check to make sure that all of the bytes come from the same value.
4431 for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
4432 if (ByteValues[i] != V)
4433 return 0;
Chandler Carruth69940402007-08-04 01:51:18 +00004434 const Type *Tys[] = { ITy };
Chris Lattnerafe91a52006-06-15 19:07:26 +00004435 Module *M = I.getParent()->getParent()->getParent();
Chandler Carruth69940402007-08-04 01:51:18 +00004436 Function *F = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 1);
Gabor Greif051a9502008-04-06 20:25:17 +00004437 return CallInst::Create(F, V);
Chris Lattnerafe91a52006-06-15 19:07:26 +00004438}
4439
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004440/// MatchSelectFromAndOr - We have an expression of the form (A&C)|(B&D). Check
4441/// If A is (cond?-1:0) and either B or D is ~(cond?-1,0) or (cond?0,-1), then
4442/// we can simplify this expression to "cond ? C : D or B".
4443static Instruction *MatchSelectFromAndOr(Value *A, Value *B,
Chris Lattner4de84762010-01-04 07:02:48 +00004444 Value *C, Value *D) {
Chris Lattnera6a474d2008-11-16 04:26:55 +00004445 // If A is not a select of -1/0, this cannot match.
Chris Lattner6046fb72008-11-16 04:46:19 +00004446 Value *Cond = 0;
Dan Gohman4ae51262009-08-12 16:23:25 +00004447 if (!match(A, m_SelectCst<-1, 0>(m_Value(Cond))))
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004448 return 0;
4449
Chris Lattnera6a474d2008-11-16 04:26:55 +00004450 // ((cond?-1:0)&C) | (B&(cond?0:-1)) -> cond ? C : B.
Dan Gohman4ae51262009-08-12 16:23:25 +00004451 if (match(D, m_SelectCst<0, -1>(m_Specific(Cond))))
Chris Lattnera6a474d2008-11-16 04:26:55 +00004452 return SelectInst::Create(Cond, C, B);
Dan Gohman4ae51262009-08-12 16:23:25 +00004453 if (match(D, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond)))))
Chris Lattnera6a474d2008-11-16 04:26:55 +00004454 return SelectInst::Create(Cond, C, B);
4455 // ((cond?-1:0)&C) | ((cond?0:-1)&D) -> cond ? C : D.
Dan Gohman4ae51262009-08-12 16:23:25 +00004456 if (match(B, m_SelectCst<0, -1>(m_Specific(Cond))))
Chris Lattnera6a474d2008-11-16 04:26:55 +00004457 return SelectInst::Create(Cond, C, D);
Dan Gohman4ae51262009-08-12 16:23:25 +00004458 if (match(B, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond)))))
Chris Lattnera6a474d2008-11-16 04:26:55 +00004459 return SelectInst::Create(Cond, C, D);
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004460 return 0;
4461}
Chris Lattnerafe91a52006-06-15 19:07:26 +00004462
Chris Lattner69d4ced2008-11-16 05:20:07 +00004463/// FoldOrOfICmps - Fold (icmp)|(icmp) if possible.
4464Instruction *InstCombiner::FoldOrOfICmps(Instruction &I,
4465 ICmpInst *LHS, ICmpInst *RHS) {
4466 Value *Val, *Val2;
4467 ConstantInt *LHSCst, *RHSCst;
4468 ICmpInst::Predicate LHSCC, RHSCC;
4469
4470 // This only handles icmp of constants: (icmp1 A, C1) | (icmp2 B, C2).
Chris Lattner3f40e232009-11-29 00:51:17 +00004471 if (!match(LHS, m_ICmp(LHSCC, m_Value(Val), m_ConstantInt(LHSCst))) ||
4472 !match(RHS, m_ICmp(RHSCC, m_Value(Val2), m_ConstantInt(RHSCst))))
Chris Lattner69d4ced2008-11-16 05:20:07 +00004473 return 0;
Chris Lattner3f40e232009-11-29 00:51:17 +00004474
4475
4476 // (icmp ne A, 0) | (icmp ne B, 0) --> (icmp ne (A|B), 0)
4477 if (LHSCst == RHSCst && LHSCC == RHSCC &&
4478 LHSCC == ICmpInst::ICMP_NE && LHSCst->isZero()) {
4479 Value *NewOr = Builder->CreateOr(Val, Val2);
4480 return new ICmpInst(LHSCC, NewOr, LHSCst);
4481 }
Chris Lattner69d4ced2008-11-16 05:20:07 +00004482
4483 // From here on, we only handle:
4484 // (icmp1 A, C1) | (icmp2 A, C2) --> something simpler.
4485 if (Val != Val2) return 0;
4486
4487 // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
4488 if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
4489 RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
4490 LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
4491 RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
4492 return 0;
4493
4494 // We can't fold (ugt x, C) | (sgt x, C2).
4495 if (!PredicatesFoldable(LHSCC, RHSCC))
4496 return 0;
4497
4498 // Ensure that the larger constant is on the RHS.
4499 bool ShouldSwap;
Nick Lewycky4a134af2009-10-25 05:20:17 +00004500 if (CmpInst::isSigned(LHSCC) ||
Chris Lattner69d4ced2008-11-16 05:20:07 +00004501 (ICmpInst::isEquality(LHSCC) &&
Nick Lewycky4a134af2009-10-25 05:20:17 +00004502 CmpInst::isSigned(RHSCC)))
Chris Lattner69d4ced2008-11-16 05:20:07 +00004503 ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
4504 else
4505 ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
4506
4507 if (ShouldSwap) {
4508 std::swap(LHS, RHS);
4509 std::swap(LHSCst, RHSCst);
4510 std::swap(LHSCC, RHSCC);
4511 }
4512
4513 // At this point, we know we have have two icmp instructions
4514 // comparing a value against two constants and or'ing the result
4515 // together. Because of the above check, we know that we only have
4516 // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
4517 // FoldICmpLogical check above), that the two constants are not
4518 // equal.
4519 assert(LHSCst != RHSCst && "Compares not folded above?");
4520
4521 switch (LHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004522 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00004523 case ICmpInst::ICMP_EQ:
4524 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004525 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00004526 case ICmpInst::ICMP_EQ:
Dan Gohman186a6362009-08-12 16:04:34 +00004527 if (LHSCst == SubOne(RHSCst)) {
Owen Andersond672ecb2009-07-03 00:17:18 +00004528 // (X == 13 | X == 14) -> X-13 <u 2
Owen Andersonbaf3c402009-07-29 18:55:55 +00004529 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
Chris Lattner74381062009-08-30 07:44:24 +00004530 Value *Add = Builder->CreateAdd(Val, AddCST, Val->getName()+".off");
Dan Gohman186a6362009-08-12 16:04:34 +00004531 AddCST = ConstantExpr::getSub(AddOne(RHSCst), LHSCst);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00004532 return new ICmpInst(ICmpInst::ICMP_ULT, Add, AddCST);
Chris Lattner69d4ced2008-11-16 05:20:07 +00004533 }
4534 break; // (X == 13 | X == 15) -> no change
4535 case ICmpInst::ICMP_UGT: // (X == 13 | X u> 14) -> no change
4536 case ICmpInst::ICMP_SGT: // (X == 13 | X s> 14) -> no change
4537 break;
4538 case ICmpInst::ICMP_NE: // (X == 13 | X != 15) -> X != 15
4539 case ICmpInst::ICMP_ULT: // (X == 13 | X u< 15) -> X u< 15
4540 case ICmpInst::ICMP_SLT: // (X == 13 | X s< 15) -> X s< 15
4541 return ReplaceInstUsesWith(I, RHS);
4542 }
4543 break;
4544 case ICmpInst::ICMP_NE:
4545 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004546 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00004547 case ICmpInst::ICMP_EQ: // (X != 13 | X == 15) -> X != 13
4548 case ICmpInst::ICMP_UGT: // (X != 13 | X u> 15) -> X != 13
4549 case ICmpInst::ICMP_SGT: // (X != 13 | X s> 15) -> X != 13
4550 return ReplaceInstUsesWith(I, LHS);
4551 case ICmpInst::ICMP_NE: // (X != 13 | X != 15) -> true
4552 case ICmpInst::ICMP_ULT: // (X != 13 | X u< 15) -> true
4553 case ICmpInst::ICMP_SLT: // (X != 13 | X s< 15) -> true
Chris Lattner4de84762010-01-04 07:02:48 +00004554 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getContext()));
Chris Lattner69d4ced2008-11-16 05:20:07 +00004555 }
4556 break;
4557 case ICmpInst::ICMP_ULT:
4558 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004559 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00004560 case ICmpInst::ICMP_EQ: // (X u< 13 | X == 14) -> no change
4561 break;
4562 case ICmpInst::ICMP_UGT: // (X u< 13 | X u> 15) -> (X-13) u> 2
4563 // If RHSCst is [us]MAXINT, it is always false. Not handling
4564 // this can cause overflow.
4565 if (RHSCst->isMaxValue(false))
4566 return ReplaceInstUsesWith(I, LHS);
Dan Gohman186a6362009-08-12 16:04:34 +00004567 return InsertRangeTest(Val, LHSCst, AddOne(RHSCst),
Owen Andersond672ecb2009-07-03 00:17:18 +00004568 false, false, I);
Chris Lattner69d4ced2008-11-16 05:20:07 +00004569 case ICmpInst::ICMP_SGT: // (X u< 13 | X s> 15) -> no change
4570 break;
4571 case ICmpInst::ICMP_NE: // (X u< 13 | X != 15) -> X != 15
4572 case ICmpInst::ICMP_ULT: // (X u< 13 | X u< 15) -> X u< 15
4573 return ReplaceInstUsesWith(I, RHS);
4574 case ICmpInst::ICMP_SLT: // (X u< 13 | X s< 15) -> no change
4575 break;
4576 }
4577 break;
4578 case ICmpInst::ICMP_SLT:
4579 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004580 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00004581 case ICmpInst::ICMP_EQ: // (X s< 13 | X == 14) -> no change
4582 break;
4583 case ICmpInst::ICMP_SGT: // (X s< 13 | X s> 15) -> (X-13) s> 2
4584 // If RHSCst is [us]MAXINT, it is always false. Not handling
4585 // this can cause overflow.
4586 if (RHSCst->isMaxValue(true))
4587 return ReplaceInstUsesWith(I, LHS);
Dan Gohman186a6362009-08-12 16:04:34 +00004588 return InsertRangeTest(Val, LHSCst, AddOne(RHSCst),
Owen Andersond672ecb2009-07-03 00:17:18 +00004589 true, false, I);
Chris Lattner69d4ced2008-11-16 05:20:07 +00004590 case ICmpInst::ICMP_UGT: // (X s< 13 | X u> 15) -> no change
4591 break;
4592 case ICmpInst::ICMP_NE: // (X s< 13 | X != 15) -> X != 15
4593 case ICmpInst::ICMP_SLT: // (X s< 13 | X s< 15) -> X s< 15
4594 return ReplaceInstUsesWith(I, RHS);
4595 case ICmpInst::ICMP_ULT: // (X s< 13 | X u< 15) -> no change
4596 break;
4597 }
4598 break;
4599 case ICmpInst::ICMP_UGT:
4600 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004601 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00004602 case ICmpInst::ICMP_EQ: // (X u> 13 | X == 15) -> X u> 13
4603 case ICmpInst::ICMP_UGT: // (X u> 13 | X u> 15) -> X u> 13
4604 return ReplaceInstUsesWith(I, LHS);
4605 case ICmpInst::ICMP_SGT: // (X u> 13 | X s> 15) -> no change
4606 break;
4607 case ICmpInst::ICMP_NE: // (X u> 13 | X != 15) -> true
4608 case ICmpInst::ICMP_ULT: // (X u> 13 | X u< 15) -> true
Chris Lattner4de84762010-01-04 07:02:48 +00004609 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getContext()));
Chris Lattner69d4ced2008-11-16 05:20:07 +00004610 case ICmpInst::ICMP_SLT: // (X u> 13 | X s< 15) -> no change
4611 break;
4612 }
4613 break;
4614 case ICmpInst::ICMP_SGT:
4615 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004616 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00004617 case ICmpInst::ICMP_EQ: // (X s> 13 | X == 15) -> X > 13
4618 case ICmpInst::ICMP_SGT: // (X s> 13 | X s> 15) -> X > 13
4619 return ReplaceInstUsesWith(I, LHS);
4620 case ICmpInst::ICMP_UGT: // (X s> 13 | X u> 15) -> no change
4621 break;
4622 case ICmpInst::ICMP_NE: // (X s> 13 | X != 15) -> true
4623 case ICmpInst::ICMP_SLT: // (X s> 13 | X s< 15) -> true
Chris Lattner4de84762010-01-04 07:02:48 +00004624 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getContext()));
Chris Lattner69d4ced2008-11-16 05:20:07 +00004625 case ICmpInst::ICMP_ULT: // (X s> 13 | X u< 15) -> no change
4626 break;
4627 }
4628 break;
4629 }
4630 return 0;
4631}
4632
Chris Lattner5414cc52009-07-23 05:46:22 +00004633Instruction *InstCombiner::FoldOrOfFCmps(Instruction &I, FCmpInst *LHS,
4634 FCmpInst *RHS) {
4635 if (LHS->getPredicate() == FCmpInst::FCMP_UNO &&
4636 RHS->getPredicate() == FCmpInst::FCMP_UNO &&
4637 LHS->getOperand(0)->getType() == RHS->getOperand(0)->getType()) {
4638 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4639 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4640 // If either of the constants are nans, then the whole thing returns
4641 // true.
4642 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Chris Lattner4de84762010-01-04 07:02:48 +00004643 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getContext()));
Chris Lattner5414cc52009-07-23 05:46:22 +00004644
4645 // Otherwise, no need to compare the two constants, compare the
4646 // rest.
Dan Gohman1c8a23c2009-08-25 23:17:54 +00004647 return new FCmpInst(FCmpInst::FCMP_UNO,
Chris Lattner5414cc52009-07-23 05:46:22 +00004648 LHS->getOperand(0), RHS->getOperand(0));
4649 }
4650
4651 // Handle vector zeros. This occurs because the canonical form of
4652 // "fcmp uno x,x" is "fcmp uno x, 0".
4653 if (isa<ConstantAggregateZero>(LHS->getOperand(1)) &&
4654 isa<ConstantAggregateZero>(RHS->getOperand(1)))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00004655 return new FCmpInst(FCmpInst::FCMP_UNO,
Chris Lattner5414cc52009-07-23 05:46:22 +00004656 LHS->getOperand(0), RHS->getOperand(0));
4657
4658 return 0;
4659 }
4660
4661 Value *Op0LHS = LHS->getOperand(0), *Op0RHS = LHS->getOperand(1);
4662 Value *Op1LHS = RHS->getOperand(0), *Op1RHS = RHS->getOperand(1);
4663 FCmpInst::Predicate Op0CC = LHS->getPredicate(), Op1CC = RHS->getPredicate();
4664
4665 if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
4666 // Swap RHS operands to match LHS.
4667 Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
4668 std::swap(Op1LHS, Op1RHS);
4669 }
4670 if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
4671 // Simplify (fcmp cc0 x, y) | (fcmp cc1 x, y).
4672 if (Op0CC == Op1CC)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00004673 return new FCmpInst((FCmpInst::Predicate)Op0CC,
Chris Lattner5414cc52009-07-23 05:46:22 +00004674 Op0LHS, Op0RHS);
4675 if (Op0CC == FCmpInst::FCMP_TRUE || Op1CC == FCmpInst::FCMP_TRUE)
Chris Lattner4de84762010-01-04 07:02:48 +00004676 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getContext()));
Chris Lattner5414cc52009-07-23 05:46:22 +00004677 if (Op0CC == FCmpInst::FCMP_FALSE)
4678 return ReplaceInstUsesWith(I, RHS);
4679 if (Op1CC == FCmpInst::FCMP_FALSE)
4680 return ReplaceInstUsesWith(I, LHS);
4681 bool Op0Ordered;
4682 bool Op1Ordered;
4683 unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
4684 unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
4685 if (Op0Ordered == Op1Ordered) {
4686 // If both are ordered or unordered, return a new fcmp with
4687 // or'ed predicates.
Chris Lattner4de84762010-01-04 07:02:48 +00004688 Value *RV = getFCmpValue(Op0Ordered, Op0Pred|Op1Pred, Op0LHS, Op0RHS);
Chris Lattner5414cc52009-07-23 05:46:22 +00004689 if (Instruction *I = dyn_cast<Instruction>(RV))
4690 return I;
4691 // Otherwise, it's a constant boolean value...
4692 return ReplaceInstUsesWith(I, RV);
4693 }
4694 }
4695 return 0;
4696}
4697
Bill Wendlinga698a472008-12-01 08:23:25 +00004698/// FoldOrWithConstants - This helper function folds:
4699///
Bill Wendlinga8bb13f2008-12-02 05:09:00 +00004700/// ((A | B) & C1) | (B & C2)
Bill Wendlinga698a472008-12-01 08:23:25 +00004701///
4702/// into:
4703///
Bill Wendlinga8bb13f2008-12-02 05:09:00 +00004704/// (A & C1) | B
Bill Wendlingd54d8602008-12-01 08:32:40 +00004705///
Bill Wendlinga8bb13f2008-12-02 05:09:00 +00004706/// when the XOR of the two constants is "all ones" (-1).
Bill Wendlingd54d8602008-12-01 08:32:40 +00004707Instruction *InstCombiner::FoldOrWithConstants(BinaryOperator &I, Value *Op,
Bill Wendlinga698a472008-12-01 08:23:25 +00004708 Value *A, Value *B, Value *C) {
Bill Wendlingdda74e02008-12-02 05:06:43 +00004709 ConstantInt *CI1 = dyn_cast<ConstantInt>(C);
4710 if (!CI1) return 0;
Bill Wendlinga698a472008-12-01 08:23:25 +00004711
Bill Wendling286a0542008-12-02 06:24:20 +00004712 Value *V1 = 0;
4713 ConstantInt *CI2 = 0;
Dan Gohman4ae51262009-08-12 16:23:25 +00004714 if (!match(Op, m_And(m_Value(V1), m_ConstantInt(CI2)))) return 0;
Bill Wendlinga698a472008-12-01 08:23:25 +00004715
Bill Wendling29976b92008-12-02 06:18:11 +00004716 APInt Xor = CI1->getValue() ^ CI2->getValue();
4717 if (!Xor.isAllOnesValue()) return 0;
4718
Bill Wendling286a0542008-12-02 06:24:20 +00004719 if (V1 == A || V1 == B) {
Chris Lattner74381062009-08-30 07:44:24 +00004720 Value *NewOp = Builder->CreateAnd((V1 == A) ? B : A, CI1);
Bill Wendlingd16c6e92008-12-02 06:22:04 +00004721 return BinaryOperator::CreateOr(NewOp, V1);
Bill Wendlinga698a472008-12-01 08:23:25 +00004722 }
4723
4724 return 0;
4725}
4726
Chris Lattner7e708292002-06-25 16:13:24 +00004727Instruction *InstCombiner::visitOr(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00004728 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00004729 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00004730
Chris Lattnerd06094f2009-11-10 00:55:12 +00004731 if (Value *V = SimplifyOrInst(Op0, Op1, TD))
4732 return ReplaceInstUsesWith(I, V);
4733
4734
Chris Lattnerf8c36f52006-02-12 08:02:11 +00004735 // See if we can simplify any instructions used by the instruction whose sole
4736 // purpose is to compute bits we don't care about.
Dan Gohman6de29f82009-06-15 22:12:54 +00004737 if (SimplifyDemandedInstructionBits(I))
4738 return &I;
Chris Lattner041a6c92007-06-15 05:26:55 +00004739
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004740 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner4f637d42006-01-06 17:59:59 +00004741 ConstantInt *C1 = 0; Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004742 // (X & C1) | C2 --> (X | C2) & (C1|C2)
Dan Gohman4ae51262009-08-12 16:23:25 +00004743 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004744 isOnlyUse(Op0)) {
Chris Lattner74381062009-08-30 07:44:24 +00004745 Value *Or = Builder->CreateOr(X, RHS);
Chris Lattner6934a042007-02-11 01:23:03 +00004746 Or->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004747 return BinaryOperator::CreateAnd(Or,
Chris Lattner4de84762010-01-04 07:02:48 +00004748 ConstantInt::get(I.getContext(),
4749 RHS->getValue() | C1->getValue()));
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004750 }
Chris Lattnerad44ebf2003-07-23 18:29:44 +00004751
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004752 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
Dan Gohman4ae51262009-08-12 16:23:25 +00004753 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004754 isOnlyUse(Op0)) {
Chris Lattner74381062009-08-30 07:44:24 +00004755 Value *Or = Builder->CreateOr(X, RHS);
Chris Lattner6934a042007-02-11 01:23:03 +00004756 Or->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004757 return BinaryOperator::CreateXor(Or,
Chris Lattner4de84762010-01-04 07:02:48 +00004758 ConstantInt::get(I.getContext(),
4759 C1->getValue() & ~RHS->getValue()));
Chris Lattnerad44ebf2003-07-23 18:29:44 +00004760 }
Chris Lattner2eefe512004-04-09 19:05:30 +00004761
4762 // Try to fold constant and into select arguments.
4763 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00004764 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00004765 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00004766 if (isa<PHINode>(Op0))
4767 if (Instruction *NV = FoldOpIntoPhi(I))
4768 return NV;
Chris Lattnerad44ebf2003-07-23 18:29:44 +00004769 }
4770
Chris Lattner4f637d42006-01-06 17:59:59 +00004771 Value *A = 0, *B = 0;
4772 ConstantInt *C1 = 0, *C2 = 0;
Chris Lattnerf4d4c872005-05-07 23:49:08 +00004773
Chris Lattner6423d4c2006-07-10 20:25:24 +00004774 // (A | B) | C and A | (B | C) -> bswap if possible.
4775 // (A >> B) | (C << D) and (A << B) | (B >> C) -> bswap if possible.
Dan Gohman4ae51262009-08-12 16:23:25 +00004776 if (match(Op0, m_Or(m_Value(), m_Value())) ||
4777 match(Op1, m_Or(m_Value(), m_Value())) ||
4778 (match(Op0, m_Shift(m_Value(), m_Value())) &&
4779 match(Op1, m_Shift(m_Value(), m_Value())))) {
Chris Lattnerafe91a52006-06-15 19:07:26 +00004780 if (Instruction *BSwap = MatchBSwap(I))
4781 return BSwap;
4782 }
4783
Chris Lattner6e4c6492005-05-09 04:58:36 +00004784 // (X^C)|Y -> (X|Y)^C iff Y&C == 0
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004785 if (Op0->hasOneUse() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00004786 match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Reid Spencera03d45f2007-03-22 22:19:58 +00004787 MaskedValueIsZero(Op1, C1->getValue())) {
Chris Lattner74381062009-08-30 07:44:24 +00004788 Value *NOr = Builder->CreateOr(A, Op1);
Chris Lattner6934a042007-02-11 01:23:03 +00004789 NOr->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004790 return BinaryOperator::CreateXor(NOr, C1);
Chris Lattner6e4c6492005-05-09 04:58:36 +00004791 }
4792
4793 // Y|(X^C) -> (X|Y)^C iff Y&C == 0
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004794 if (Op1->hasOneUse() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00004795 match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Reid Spencera03d45f2007-03-22 22:19:58 +00004796 MaskedValueIsZero(Op0, C1->getValue())) {
Chris Lattner74381062009-08-30 07:44:24 +00004797 Value *NOr = Builder->CreateOr(A, Op0);
Chris Lattner6934a042007-02-11 01:23:03 +00004798 NOr->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004799 return BinaryOperator::CreateXor(NOr, C1);
Chris Lattner6e4c6492005-05-09 04:58:36 +00004800 }
4801
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004802 // (A & C)|(B & D)
Chris Lattner2384d7b2007-06-19 05:43:49 +00004803 Value *C = 0, *D = 0;
Dan Gohman4ae51262009-08-12 16:23:25 +00004804 if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
4805 match(Op1, m_And(m_Value(B), m_Value(D)))) {
Chris Lattner6cae0e02007-04-08 07:55:22 +00004806 Value *V1 = 0, *V2 = 0, *V3 = 0;
4807 C1 = dyn_cast<ConstantInt>(C);
4808 C2 = dyn_cast<ConstantInt>(D);
4809 if (C1 && C2) { // (A & C1)|(B & C2)
4810 // If we have: ((V + N) & C1) | (V & C2)
4811 // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
4812 // replace with V+N.
4813 if (C1->getValue() == ~C2->getValue()) {
4814 if ((C2->getValue() & (C2->getValue()+1)) == 0 && // C2 == 0+1+
Dan Gohman4ae51262009-08-12 16:23:25 +00004815 match(A, m_Add(m_Value(V1), m_Value(V2)))) {
Chris Lattner6cae0e02007-04-08 07:55:22 +00004816 // Add commutes, try both ways.
4817 if (V1 == B && MaskedValueIsZero(V2, C2->getValue()))
4818 return ReplaceInstUsesWith(I, A);
4819 if (V2 == B && MaskedValueIsZero(V1, C2->getValue()))
4820 return ReplaceInstUsesWith(I, A);
4821 }
4822 // Or commutes, try both ways.
4823 if ((C1->getValue() & (C1->getValue()+1)) == 0 &&
Dan Gohman4ae51262009-08-12 16:23:25 +00004824 match(B, m_Add(m_Value(V1), m_Value(V2)))) {
Chris Lattner6cae0e02007-04-08 07:55:22 +00004825 // Add commutes, try both ways.
4826 if (V1 == A && MaskedValueIsZero(V2, C1->getValue()))
4827 return ReplaceInstUsesWith(I, B);
4828 if (V2 == A && MaskedValueIsZero(V1, C1->getValue()))
4829 return ReplaceInstUsesWith(I, B);
4830 }
4831 }
Chris Lattnere4412c12010-01-04 06:03:59 +00004832
4833 // ((V | N) & C1) | (V & C2) --> (V|N) & (C1|C2)
4834 // iff (C1&C2) == 0 and (N&~C1) == 0
4835 if ((C1->getValue() & C2->getValue()) == 0) {
4836 if (match(A, m_Or(m_Value(V1), m_Value(V2))) &&
4837 ((V1 == B && MaskedValueIsZero(V2, ~C1->getValue())) || // (V|N)
4838 (V2 == B && MaskedValueIsZero(V1, ~C1->getValue())))) // (N|V)
4839 return BinaryOperator::CreateAnd(A,
4840 ConstantInt::get(A->getContext(),
4841 C1->getValue()|C2->getValue()));
4842 // Or commutes, try both ways.
4843 if (match(B, m_Or(m_Value(V1), m_Value(V2))) &&
4844 ((V1 == A && MaskedValueIsZero(V2, ~C2->getValue())) || // (V|N)
4845 (V2 == A && MaskedValueIsZero(V1, ~C2->getValue())))) // (N|V)
4846 return BinaryOperator::CreateAnd(B,
4847 ConstantInt::get(B->getContext(),
4848 C1->getValue()|C2->getValue()));
4849 }
Chris Lattner6cae0e02007-04-08 07:55:22 +00004850 }
4851
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004852 // Check to see if we have any common things being and'ed. If so, find the
4853 // terms for V1 & (V2|V3).
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004854 if (isOnlyUse(Op0) || isOnlyUse(Op1)) {
Chris Lattnere4412c12010-01-04 06:03:59 +00004855 V1 = 0;
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004856 if (A == B) // (A & C)|(A & D) == A & (C|D)
4857 V1 = A, V2 = C, V3 = D;
4858 else if (A == D) // (A & C)|(B & A) == A & (B|C)
4859 V1 = A, V2 = B, V3 = C;
4860 else if (C == B) // (A & C)|(C & D) == C & (A|D)
4861 V1 = C, V2 = A, V3 = D;
4862 else if (C == D) // (A & C)|(B & C) == C & (A|B)
4863 V1 = C, V2 = A, V3 = B;
4864
4865 if (V1) {
Chris Lattner74381062009-08-30 07:44:24 +00004866 Value *Or = Builder->CreateOr(V2, V3, "tmp");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004867 return BinaryOperator::CreateAnd(V1, Or);
Chris Lattner0b7c0bf2005-09-18 06:02:59 +00004868 }
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004869 }
Dan Gohmanb493b272008-10-28 22:38:57 +00004870
Dan Gohman1975d032008-10-30 20:40:10 +00004871 // (A & (C0?-1:0)) | (B & ~(C0?-1:0)) -> C0 ? A : B, and commuted variants
Chris Lattner4de84762010-01-04 07:02:48 +00004872 if (Instruction *Match = MatchSelectFromAndOr(A, B, C, D))
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004873 return Match;
Chris Lattner4de84762010-01-04 07:02:48 +00004874 if (Instruction *Match = MatchSelectFromAndOr(B, A, D, C))
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004875 return Match;
Chris Lattner4de84762010-01-04 07:02:48 +00004876 if (Instruction *Match = MatchSelectFromAndOr(C, B, A, D))
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004877 return Match;
Chris Lattner4de84762010-01-04 07:02:48 +00004878 if (Instruction *Match = MatchSelectFromAndOr(D, A, B, C))
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004879 return Match;
Bill Wendlingb01865c2008-11-30 13:52:49 +00004880
Bill Wendlingb01865c2008-11-30 13:52:49 +00004881 // ((A&~B)|(~A&B)) -> A^B
Dan Gohman4ae51262009-08-12 16:23:25 +00004882 if ((match(C, m_Not(m_Specific(D))) &&
4883 match(B, m_Not(m_Specific(A)))))
Bill Wendling03aae5f2008-12-01 08:09:47 +00004884 return BinaryOperator::CreateXor(A, D);
Bill Wendlingb01865c2008-11-30 13:52:49 +00004885 // ((~B&A)|(~A&B)) -> A^B
Dan Gohman4ae51262009-08-12 16:23:25 +00004886 if ((match(A, m_Not(m_Specific(D))) &&
4887 match(B, m_Not(m_Specific(C)))))
Bill Wendling03aae5f2008-12-01 08:09:47 +00004888 return BinaryOperator::CreateXor(C, D);
Bill Wendlingb01865c2008-11-30 13:52:49 +00004889 // ((A&~B)|(B&~A)) -> A^B
Dan Gohman4ae51262009-08-12 16:23:25 +00004890 if ((match(C, m_Not(m_Specific(B))) &&
4891 match(D, m_Not(m_Specific(A)))))
Bill Wendling03aae5f2008-12-01 08:09:47 +00004892 return BinaryOperator::CreateXor(A, B);
Bill Wendlingb01865c2008-11-30 13:52:49 +00004893 // ((~B&A)|(B&~A)) -> A^B
Dan Gohman4ae51262009-08-12 16:23:25 +00004894 if ((match(A, m_Not(m_Specific(B))) &&
4895 match(D, m_Not(m_Specific(C)))))
Bill Wendling03aae5f2008-12-01 08:09:47 +00004896 return BinaryOperator::CreateXor(C, B);
Chris Lattnere9bed7d2005-09-18 03:42:07 +00004897 }
Chris Lattnere511b742006-11-14 07:46:50 +00004898
4899 // (X >> Z) | (Y >> Z) -> (X|Y) >> Z for all shifts.
Reid Spencer832254e2007-02-02 02:16:23 +00004900 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4901 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4902 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
Chris Lattnere511b742006-11-14 07:46:50 +00004903 SI0->getOperand(1) == SI1->getOperand(1) &&
4904 (SI0->hasOneUse() || SI1->hasOneUse())) {
Chris Lattner74381062009-08-30 07:44:24 +00004905 Value *NewOp = Builder->CreateOr(SI0->getOperand(0), SI1->getOperand(0),
4906 SI0->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004907 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
Reid Spencer832254e2007-02-02 02:16:23 +00004908 SI1->getOperand(1));
Chris Lattnere511b742006-11-14 07:46:50 +00004909 }
4910 }
Chris Lattner67ca7682003-08-12 19:11:07 +00004911
Bill Wendlingb3833d12008-12-01 01:07:11 +00004912 // ((A|B)&1)|(B&-2) -> (A&1) | B
Dan Gohman4ae51262009-08-12 16:23:25 +00004913 if (match(Op0, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C))) ||
4914 match(Op0, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))))) {
Bill Wendlingd54d8602008-12-01 08:32:40 +00004915 Instruction *Ret = FoldOrWithConstants(I, Op1, A, B, C);
Bill Wendlinga698a472008-12-01 08:23:25 +00004916 if (Ret) return Ret;
Bill Wendlingb3833d12008-12-01 01:07:11 +00004917 }
4918 // (B&-2)|((A|B)&1) -> (A&1) | B
Dan Gohman4ae51262009-08-12 16:23:25 +00004919 if (match(Op1, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C))) ||
4920 match(Op1, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))))) {
Bill Wendlingd54d8602008-12-01 08:32:40 +00004921 Instruction *Ret = FoldOrWithConstants(I, Op0, A, B, C);
Bill Wendlinga698a472008-12-01 08:23:25 +00004922 if (Ret) return Ret;
Bill Wendlingb3833d12008-12-01 01:07:11 +00004923 }
4924
Chris Lattnerd06094f2009-11-10 00:55:12 +00004925 // (~A | ~B) == (~(A & B)) - De Morgan's Law
4926 if (Value *Op0NotVal = dyn_castNotVal(Op0))
4927 if (Value *Op1NotVal = dyn_castNotVal(Op1))
4928 if (Op0->hasOneUse() && Op1->hasOneUse()) {
4929 Value *And = Builder->CreateAnd(Op0NotVal, Op1NotVal,
4930 I.getName()+".demorgan");
4931 return BinaryOperator::CreateNot(And);
4932 }
Chris Lattnera2881962003-02-18 19:28:33 +00004933
Reid Spencere4d87aa2006-12-23 06:05:41 +00004934 // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
4935 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1))) {
Dan Gohman186a6362009-08-12 16:04:34 +00004936 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00004937 return R;
4938
Chris Lattner69d4ced2008-11-16 05:20:07 +00004939 if (ICmpInst *LHS = dyn_cast<ICmpInst>(I.getOperand(0)))
4940 if (Instruction *Res = FoldOrOfICmps(I, LHS, RHS))
4941 return Res;
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004942 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004943
4944 // fold (or (cast A), (cast B)) -> (cast (or A, B))
Chris Lattner99c65742007-10-24 05:38:08 +00004945 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Chris Lattner6fc205f2006-05-05 06:39:07 +00004946 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004947 if (Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
Evan Chengb98a10e2008-03-24 00:21:34 +00004948 if (!isa<ICmpInst>(Op0C->getOperand(0)) ||
4949 !isa<ICmpInst>(Op1C->getOperand(0))) {
4950 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattnerf98d2532009-07-23 05:32:17 +00004951 if (SrcTy == Op1C->getOperand(0)->getType() &&
4952 SrcTy->isIntOrIntVector() &&
Evan Chengb98a10e2008-03-24 00:21:34 +00004953 // Only do this if the casts both really cause code to be
4954 // generated.
4955 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4956 I.getType(), TD) &&
4957 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4958 I.getType(), TD)) {
Chris Lattner74381062009-08-30 07:44:24 +00004959 Value *NewOp = Builder->CreateOr(Op0C->getOperand(0),
4960 Op1C->getOperand(0), I.getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004961 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Evan Chengb98a10e2008-03-24 00:21:34 +00004962 }
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004963 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004964 }
Chris Lattner99c65742007-10-24 05:38:08 +00004965 }
4966
4967
4968 // (fcmp uno x, c) | (fcmp uno y, c) -> (fcmp uno x, y)
4969 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
Chris Lattner5414cc52009-07-23 05:46:22 +00004970 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
4971 if (Instruction *Res = FoldOrOfFCmps(I, LHS, RHS))
4972 return Res;
Chris Lattner99c65742007-10-24 05:38:08 +00004973 }
Chris Lattnere9bed7d2005-09-18 03:42:07 +00004974
Chris Lattner7e708292002-06-25 16:13:24 +00004975 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00004976}
4977
Dan Gohman844731a2008-05-13 00:00:25 +00004978namespace {
4979
Chris Lattnerc317d392004-02-16 01:20:27 +00004980// XorSelf - Implements: X ^ X --> 0
4981struct XorSelf {
4982 Value *RHS;
4983 XorSelf(Value *rhs) : RHS(rhs) {}
4984 bool shouldApply(Value *LHS) const { return LHS == RHS; }
4985 Instruction *apply(BinaryOperator &Xor) const {
4986 return &Xor;
4987 }
4988};
Chris Lattner3f5b8772002-05-06 16:14:14 +00004989
Dan Gohman844731a2008-05-13 00:00:25 +00004990}
Chris Lattner3f5b8772002-05-06 16:14:14 +00004991
Chris Lattner7e708292002-06-25 16:13:24 +00004992Instruction *InstCombiner::visitXor(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00004993 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00004994 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00004995
Evan Chengd34af782008-03-25 20:07:13 +00004996 if (isa<UndefValue>(Op1)) {
4997 if (isa<UndefValue>(Op0))
4998 // Handle undef ^ undef -> 0 special case. This is a common
4999 // idiom (misuse).
Owen Andersona7235ea2009-07-31 20:28:14 +00005000 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00005001 return ReplaceInstUsesWith(I, Op1); // X ^ undef -> undef
Evan Chengd34af782008-03-25 20:07:13 +00005002 }
Chris Lattnere87597f2004-10-16 18:11:37 +00005003
Chris Lattnerc317d392004-02-16 01:20:27 +00005004 // xor X, X = 0, even if X is nested in a sequence of Xor's.
Dan Gohman186a6362009-08-12 16:04:34 +00005005 if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
Chris Lattnera9ff5eb2007-08-05 08:47:58 +00005006 assert(Result == &I && "AssociativeOpt didn't work?"); Result=Result;
Owen Andersona7235ea2009-07-31 20:28:14 +00005007 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerc317d392004-02-16 01:20:27 +00005008 }
Chris Lattnerf8c36f52006-02-12 08:02:11 +00005009
5010 // See if we can simplify any instructions used by the instruction whose sole
5011 // purpose is to compute bits we don't care about.
Dan Gohman6de29f82009-06-15 22:12:54 +00005012 if (SimplifyDemandedInstructionBits(I))
5013 return &I;
5014 if (isa<VectorType>(I.getType()))
5015 if (isa<ConstantAggregateZero>(Op1))
5016 return ReplaceInstUsesWith(I, Op0); // X ^ <0,0> -> X
Chris Lattner3f5b8772002-05-06 16:14:14 +00005017
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00005018 // Is this a ~ operation?
Dan Gohman186a6362009-08-12 16:04:34 +00005019 if (Value *NotOp = dyn_castNotVal(&I)) {
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00005020 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(NotOp)) {
5021 if (Op0I->getOpcode() == Instruction::And ||
5022 Op0I->getOpcode() == Instruction::Or) {
Chris Lattner48b59ec2009-10-26 15:40:07 +00005023 // ~(~X & Y) --> (X | ~Y) - De Morgan's Law
5024 // ~(~X | Y) === (X & ~Y) - De Morgan's Law
5025 if (dyn_castNotVal(Op0I->getOperand(1)))
5026 Op0I->swapOperands();
Dan Gohman186a6362009-08-12 16:04:34 +00005027 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
Chris Lattner74381062009-08-30 07:44:24 +00005028 Value *NotY =
5029 Builder->CreateNot(Op0I->getOperand(1),
5030 Op0I->getOperand(1)->getName()+".not");
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00005031 if (Op0I->getOpcode() == Instruction::And)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005032 return BinaryOperator::CreateOr(Op0NotVal, NotY);
Chris Lattner74381062009-08-30 07:44:24 +00005033 return BinaryOperator::CreateAnd(Op0NotVal, NotY);
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00005034 }
Chris Lattner48b59ec2009-10-26 15:40:07 +00005035
5036 // ~(X & Y) --> (~X | ~Y) - De Morgan's Law
5037 // ~(X | Y) === (~X & ~Y) - De Morgan's Law
5038 if (isFreeToInvert(Op0I->getOperand(0)) &&
5039 isFreeToInvert(Op0I->getOperand(1))) {
5040 Value *NotX =
5041 Builder->CreateNot(Op0I->getOperand(0), "notlhs");
5042 Value *NotY =
5043 Builder->CreateNot(Op0I->getOperand(1), "notrhs");
5044 if (Op0I->getOpcode() == Instruction::And)
5045 return BinaryOperator::CreateOr(NotX, NotY);
5046 return BinaryOperator::CreateAnd(NotX, NotY);
5047 }
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00005048 }
5049 }
5050 }
5051
5052
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005053 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner7acdf1d2009-10-11 22:00:32 +00005054 if (RHS->isOne() && Op0->hasOneUse()) {
Bill Wendling3479be92009-01-01 01:18:23 +00005055 // xor (cmp A, B), true = not (cmp A, B) = !cmp A, B
Nick Lewyckyf947b3e2007-08-06 20:04:16 +00005056 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Op0))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00005057 return new ICmpInst(ICI->getInversePredicate(),
Reid Spencere4d87aa2006-12-23 06:05:41 +00005058 ICI->getOperand(0), ICI->getOperand(1));
Chris Lattnerad5b4fb2003-11-04 23:50:51 +00005059
Nick Lewyckyf947b3e2007-08-06 20:04:16 +00005060 if (FCmpInst *FCI = dyn_cast<FCmpInst>(Op0))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00005061 return new FCmpInst(FCI->getInversePredicate(),
Nick Lewyckyf947b3e2007-08-06 20:04:16 +00005062 FCI->getOperand(0), FCI->getOperand(1));
5063 }
5064
Nick Lewycky517e1f52008-05-31 19:01:33 +00005065 // fold (xor(zext(cmp)), 1) and (xor(sext(cmp)), -1) to ext(!cmp).
5066 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
5067 if (CmpInst *CI = dyn_cast<CmpInst>(Op0C->getOperand(0))) {
5068 if (CI->hasOneUse() && Op0C->hasOneUse()) {
5069 Instruction::CastOps Opcode = Op0C->getOpcode();
Chris Lattner74381062009-08-30 07:44:24 +00005070 if ((Opcode == Instruction::ZExt || Opcode == Instruction::SExt) &&
5071 (RHS == ConstantExpr::getCast(Opcode,
Chris Lattner4de84762010-01-04 07:02:48 +00005072 ConstantInt::getTrue(I.getContext()),
Chris Lattner74381062009-08-30 07:44:24 +00005073 Op0C->getDestTy()))) {
5074 CI->setPredicate(CI->getInversePredicate());
5075 return CastInst::Create(Opcode, CI, Op0C->getType());
Nick Lewycky517e1f52008-05-31 19:01:33 +00005076 }
5077 }
5078 }
5079 }
5080
Reid Spencere4d87aa2006-12-23 06:05:41 +00005081 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Chris Lattnerd65460f2003-11-05 01:06:05 +00005082 // ~(c-X) == X-c-1 == X+(-c-1)
Chris Lattner7c4049c2004-01-12 19:35:11 +00005083 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
5084 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00005085 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
5086 Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
Owen Andersoneed707b2009-07-24 23:12:02 +00005087 ConstantInt::get(I.getType(), 1));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005088 return BinaryOperator::CreateAdd(Op0I->getOperand(1), ConstantRHS);
Chris Lattner7c4049c2004-01-12 19:35:11 +00005089 }
Chris Lattner5c6e2db2007-04-02 05:36:22 +00005090
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00005091 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
Chris Lattnerf8c36f52006-02-12 08:02:11 +00005092 if (Op0I->getOpcode() == Instruction::Add) {
Chris Lattner689d24b2003-11-04 23:37:10 +00005093 // ~(X-c) --> (-c-1)-X
Chris Lattner7c4049c2004-01-12 19:35:11 +00005094 if (RHS->isAllOnesValue()) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00005095 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005096 return BinaryOperator::CreateSub(
Owen Andersonbaf3c402009-07-29 18:55:55 +00005097 ConstantExpr::getSub(NegOp0CI,
Owen Andersoneed707b2009-07-24 23:12:02 +00005098 ConstantInt::get(I.getType(), 1)),
Owen Andersond672ecb2009-07-03 00:17:18 +00005099 Op0I->getOperand(0));
Chris Lattneracf4e072007-04-02 05:42:22 +00005100 } else if (RHS->getValue().isSignBit()) {
Chris Lattner5c6e2db2007-04-02 05:36:22 +00005101 // (X + C) ^ signbit -> (X + C + signbit)
Chris Lattner4de84762010-01-04 07:02:48 +00005102 Constant *C = ConstantInt::get(I.getContext(),
Owen Andersoneed707b2009-07-24 23:12:02 +00005103 RHS->getValue() + Op0CI->getValue());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005104 return BinaryOperator::CreateAdd(Op0I->getOperand(0), C);
Chris Lattnercd1d6d52007-04-02 05:48:58 +00005105
Chris Lattner7c4049c2004-01-12 19:35:11 +00005106 }
Chris Lattner02bd1b32006-02-26 19:57:54 +00005107 } else if (Op0I->getOpcode() == Instruction::Or) {
5108 // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
Reid Spencera03d45f2007-03-22 22:19:58 +00005109 if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue())) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00005110 Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
Chris Lattner02bd1b32006-02-26 19:57:54 +00005111 // Anything in both C1 and C2 is known to be zero, remove it from
5112 // NewRHS.
Owen Andersonbaf3c402009-07-29 18:55:55 +00005113 Constant *CommonBits = ConstantExpr::getAnd(Op0CI, RHS);
5114 NewRHS = ConstantExpr::getAnd(NewRHS,
5115 ConstantExpr::getNot(CommonBits));
Chris Lattner7a1e9242009-08-30 06:13:40 +00005116 Worklist.Add(Op0I);
Chris Lattner02bd1b32006-02-26 19:57:54 +00005117 I.setOperand(0, Op0I->getOperand(0));
5118 I.setOperand(1, NewRHS);
5119 return &I;
5120 }
Chris Lattnereca0c5c2003-07-23 21:37:07 +00005121 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00005122 }
Chris Lattner05bd1b22002-08-20 18:24:26 +00005123 }
Chris Lattner2eefe512004-04-09 19:05:30 +00005124
5125 // Try to fold constant and into select arguments.
5126 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00005127 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00005128 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00005129 if (isa<PHINode>(Op0))
5130 if (Instruction *NV = FoldOpIntoPhi(I))
5131 return NV;
Chris Lattner3f5b8772002-05-06 16:14:14 +00005132 }
5133
Dan Gohman186a6362009-08-12 16:04:34 +00005134 if (Value *X = dyn_castNotVal(Op0)) // ~A ^ A == -1
Chris Lattnera2881962003-02-18 19:28:33 +00005135 if (X == Op1)
Owen Andersona7235ea2009-07-31 20:28:14 +00005136 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00005137
Dan Gohman186a6362009-08-12 16:04:34 +00005138 if (Value *X = dyn_castNotVal(Op1)) // A ^ ~A == -1
Chris Lattnera2881962003-02-18 19:28:33 +00005139 if (X == Op0)
Owen Andersona7235ea2009-07-31 20:28:14 +00005140 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00005141
Chris Lattner318bf792007-03-18 22:51:34 +00005142
5143 BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1);
5144 if (Op1I) {
5145 Value *A, *B;
Dan Gohman4ae51262009-08-12 16:23:25 +00005146 if (match(Op1I, m_Or(m_Value(A), m_Value(B)))) {
Chris Lattner318bf792007-03-18 22:51:34 +00005147 if (A == Op0) { // B^(B|A) == (A|B)^B
Chris Lattner64daab52006-04-01 08:03:55 +00005148 Op1I->swapOperands();
Chris Lattnercb40a372003-03-10 18:24:17 +00005149 I.swapOperands();
5150 std::swap(Op0, Op1);
Chris Lattner318bf792007-03-18 22:51:34 +00005151 } else if (B == Op0) { // B^(A|B) == (A|B)^B
Chris Lattner64daab52006-04-01 08:03:55 +00005152 I.swapOperands(); // Simplified below.
Chris Lattnercb40a372003-03-10 18:24:17 +00005153 std::swap(Op0, Op1);
Misha Brukmanfd939082005-04-21 23:48:37 +00005154 }
Dan Gohman4ae51262009-08-12 16:23:25 +00005155 } else if (match(Op1I, m_Xor(m_Specific(Op0), m_Value(B)))) {
Chris Lattnercb504b92008-11-16 05:38:51 +00005156 return ReplaceInstUsesWith(I, B); // A^(A^B) == B
Dan Gohman4ae51262009-08-12 16:23:25 +00005157 } else if (match(Op1I, m_Xor(m_Value(A), m_Specific(Op0)))) {
Chris Lattnercb504b92008-11-16 05:38:51 +00005158 return ReplaceInstUsesWith(I, A); // A^(B^A) == B
Dan Gohman4ae51262009-08-12 16:23:25 +00005159 } else if (match(Op1I, m_And(m_Value(A), m_Value(B))) &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005160 Op1I->hasOneUse()){
Chris Lattner6abbdf92007-04-01 05:36:37 +00005161 if (A == Op0) { // A^(A&B) -> A^(B&A)
Chris Lattner64daab52006-04-01 08:03:55 +00005162 Op1I->swapOperands();
Chris Lattner6abbdf92007-04-01 05:36:37 +00005163 std::swap(A, B);
5164 }
Chris Lattner318bf792007-03-18 22:51:34 +00005165 if (B == Op0) { // A^(B&A) -> (B&A)^A
Chris Lattner64daab52006-04-01 08:03:55 +00005166 I.swapOperands(); // Simplified below.
5167 std::swap(Op0, Op1);
5168 }
Chris Lattner26ca7e12004-02-16 03:54:20 +00005169 }
Chris Lattner318bf792007-03-18 22:51:34 +00005170 }
5171
5172 BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0);
5173 if (Op0I) {
5174 Value *A, *B;
Dan Gohman4ae51262009-08-12 16:23:25 +00005175 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005176 Op0I->hasOneUse()) {
Chris Lattner318bf792007-03-18 22:51:34 +00005177 if (A == Op1) // (B|A)^B == (A|B)^B
5178 std::swap(A, B);
Chris Lattner74381062009-08-30 07:44:24 +00005179 if (B == Op1) // (A|B)^B == A & ~B
5180 return BinaryOperator::CreateAnd(A, Builder->CreateNot(Op1, "tmp"));
Dan Gohman4ae51262009-08-12 16:23:25 +00005181 } else if (match(Op0I, m_Xor(m_Specific(Op1), m_Value(B)))) {
Chris Lattnercb504b92008-11-16 05:38:51 +00005182 return ReplaceInstUsesWith(I, B); // (A^B)^A == B
Dan Gohman4ae51262009-08-12 16:23:25 +00005183 } else if (match(Op0I, m_Xor(m_Value(A), m_Specific(Op1)))) {
Chris Lattnercb504b92008-11-16 05:38:51 +00005184 return ReplaceInstUsesWith(I, A); // (B^A)^A == B
Dan Gohman4ae51262009-08-12 16:23:25 +00005185 } else if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005186 Op0I->hasOneUse()){
Chris Lattner318bf792007-03-18 22:51:34 +00005187 if (A == Op1) // (A&B)^A -> (B&A)^A
5188 std::swap(A, B);
5189 if (B == Op1 && // (B&A)^A == ~B & A
Chris Lattnerae1ab392006-04-01 22:05:01 +00005190 !isa<ConstantInt>(Op1)) { // Canonical form is (B&C)^C
Chris Lattner74381062009-08-30 07:44:24 +00005191 return BinaryOperator::CreateAnd(Builder->CreateNot(A, "tmp"), Op1);
Chris Lattner64daab52006-04-01 08:03:55 +00005192 }
Chris Lattnercb40a372003-03-10 18:24:17 +00005193 }
Chris Lattner318bf792007-03-18 22:51:34 +00005194 }
5195
5196 // (X >> Z) ^ (Y >> Z) -> (X^Y) >> Z for all shifts.
5197 if (Op0I && Op1I && Op0I->isShift() &&
5198 Op0I->getOpcode() == Op1I->getOpcode() &&
5199 Op0I->getOperand(1) == Op1I->getOperand(1) &&
5200 (Op1I->hasOneUse() || Op1I->hasOneUse())) {
Chris Lattner74381062009-08-30 07:44:24 +00005201 Value *NewOp =
5202 Builder->CreateXor(Op0I->getOperand(0), Op1I->getOperand(0),
5203 Op0I->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005204 return BinaryOperator::Create(Op1I->getOpcode(), NewOp,
Chris Lattner318bf792007-03-18 22:51:34 +00005205 Op1I->getOperand(1));
5206 }
5207
5208 if (Op0I && Op1I) {
5209 Value *A, *B, *C, *D;
5210 // (A & B)^(A | B) -> A ^ B
Dan Gohman4ae51262009-08-12 16:23:25 +00005211 if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
5212 match(Op1I, m_Or(m_Value(C), m_Value(D)))) {
Chris Lattner318bf792007-03-18 22:51:34 +00005213 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005214 return BinaryOperator::CreateXor(A, B);
Chris Lattner318bf792007-03-18 22:51:34 +00005215 }
5216 // (A | B)^(A & B) -> A ^ B
Dan Gohman4ae51262009-08-12 16:23:25 +00005217 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
5218 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
Chris Lattner318bf792007-03-18 22:51:34 +00005219 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005220 return BinaryOperator::CreateXor(A, B);
Chris Lattner318bf792007-03-18 22:51:34 +00005221 }
5222
5223 // (A & B)^(C & D)
5224 if ((Op0I->hasOneUse() || Op1I->hasOneUse()) &&
Dan Gohman4ae51262009-08-12 16:23:25 +00005225 match(Op0I, m_And(m_Value(A), m_Value(B))) &&
5226 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
Chris Lattner318bf792007-03-18 22:51:34 +00005227 // (X & Y)^(X & Y) -> (Y^Z) & X
5228 Value *X = 0, *Y = 0, *Z = 0;
5229 if (A == C)
5230 X = A, Y = B, Z = D;
5231 else if (A == D)
5232 X = A, Y = B, Z = C;
5233 else if (B == C)
5234 X = B, Y = A, Z = D;
5235 else if (B == D)
5236 X = B, Y = A, Z = C;
5237
5238 if (X) {
Chris Lattner74381062009-08-30 07:44:24 +00005239 Value *NewOp = Builder->CreateXor(Y, Z, Op0->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005240 return BinaryOperator::CreateAnd(NewOp, X);
Chris Lattner318bf792007-03-18 22:51:34 +00005241 }
5242 }
5243 }
5244
Reid Spencere4d87aa2006-12-23 06:05:41 +00005245 // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
5246 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
Dan Gohman186a6362009-08-12 16:04:34 +00005247 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00005248 return R;
5249
Chris Lattner6fc205f2006-05-05 06:39:07 +00005250 // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
Chris Lattner99c65742007-10-24 05:38:08 +00005251 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Chris Lattner6fc205f2006-05-05 06:39:07 +00005252 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00005253 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
5254 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner42a75512007-01-15 02:27:26 +00005255 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00005256 // Only do this if the casts both really cause code to be generated.
Reid Spencere4d87aa2006-12-23 06:05:41 +00005257 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
5258 I.getType(), TD) &&
5259 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
5260 I.getType(), TD)) {
Chris Lattner74381062009-08-30 07:44:24 +00005261 Value *NewOp = Builder->CreateXor(Op0C->getOperand(0),
5262 Op1C->getOperand(0), I.getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005263 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00005264 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00005265 }
Chris Lattner99c65742007-10-24 05:38:08 +00005266 }
Nick Lewycky517e1f52008-05-31 19:01:33 +00005267
Chris Lattner7e708292002-06-25 16:13:24 +00005268 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00005269}
5270
Chris Lattner4de84762010-01-04 07:02:48 +00005271static ConstantInt *ExtractElement(Constant *V, Constant *Idx) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00005272 return cast<ConstantInt>(ConstantExpr::getExtractElement(V, Idx));
Dan Gohman6de29f82009-06-15 22:12:54 +00005273}
Chris Lattnera96879a2004-09-29 17:40:11 +00005274
Dan Gohman6de29f82009-06-15 22:12:54 +00005275static bool HasAddOverflow(ConstantInt *Result,
5276 ConstantInt *In1, ConstantInt *In2,
5277 bool IsSigned) {
Reid Spencere4e40032007-03-21 23:19:50 +00005278 if (IsSigned)
5279 if (In2->getValue().isNegative())
5280 return Result->getValue().sgt(In1->getValue());
5281 else
5282 return Result->getValue().slt(In1->getValue());
5283 else
5284 return Result->getValue().ult(In1->getValue());
Chris Lattnera96879a2004-09-29 17:40:11 +00005285}
5286
Dan Gohman6de29f82009-06-15 22:12:54 +00005287/// AddWithOverflow - Compute Result = In1+In2, returning true if the result
Dan Gohman1df3fd62008-09-10 23:30:57 +00005288/// overflowed for this type.
Dan Gohman6de29f82009-06-15 22:12:54 +00005289static bool AddWithOverflow(Constant *&Result, Constant *In1,
Chris Lattner4de84762010-01-04 07:02:48 +00005290 Constant *In2, bool IsSigned = false) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00005291 Result = ConstantExpr::getAdd(In1, In2);
Dan Gohman1df3fd62008-09-10 23:30:57 +00005292
Dan Gohman6de29f82009-06-15 22:12:54 +00005293 if (const VectorType *VTy = dyn_cast<VectorType>(In1->getType())) {
5294 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
Chris Lattner4de84762010-01-04 07:02:48 +00005295 Constant *Idx = ConstantInt::get(Type::getInt32Ty(In1->getContext()), i);
5296 if (HasAddOverflow(ExtractElement(Result, Idx),
5297 ExtractElement(In1, Idx),
5298 ExtractElement(In2, Idx),
Dan Gohman6de29f82009-06-15 22:12:54 +00005299 IsSigned))
5300 return true;
5301 }
5302 return false;
5303 }
5304
5305 return HasAddOverflow(cast<ConstantInt>(Result),
5306 cast<ConstantInt>(In1), cast<ConstantInt>(In2),
5307 IsSigned);
5308}
5309
5310static bool HasSubOverflow(ConstantInt *Result,
5311 ConstantInt *In1, ConstantInt *In2,
5312 bool IsSigned) {
Dan Gohman1df3fd62008-09-10 23:30:57 +00005313 if (IsSigned)
5314 if (In2->getValue().isNegative())
5315 return Result->getValue().slt(In1->getValue());
5316 else
5317 return Result->getValue().sgt(In1->getValue());
5318 else
5319 return Result->getValue().ugt(In1->getValue());
5320}
5321
Dan Gohman6de29f82009-06-15 22:12:54 +00005322/// SubWithOverflow - Compute Result = In1-In2, returning true if the result
5323/// overflowed for this type.
5324static bool SubWithOverflow(Constant *&Result, Constant *In1,
Chris Lattner4de84762010-01-04 07:02:48 +00005325 Constant *In2, bool IsSigned = false) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00005326 Result = ConstantExpr::getSub(In1, In2);
Dan Gohman6de29f82009-06-15 22:12:54 +00005327
5328 if (const VectorType *VTy = dyn_cast<VectorType>(In1->getType())) {
5329 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
Chris Lattner4de84762010-01-04 07:02:48 +00005330 Constant *Idx = ConstantInt::get(Type::getInt32Ty(In1->getContext()), i);
5331 if (HasSubOverflow(ExtractElement(Result, Idx),
5332 ExtractElement(In1, Idx),
5333 ExtractElement(In2, Idx),
Dan Gohman6de29f82009-06-15 22:12:54 +00005334 IsSigned))
5335 return true;
5336 }
5337 return false;
5338 }
5339
5340 return HasSubOverflow(cast<ConstantInt>(Result),
5341 cast<ConstantInt>(In1), cast<ConstantInt>(In2),
5342 IsSigned);
5343}
5344
Chris Lattner10c0d912008-04-22 02:53:33 +00005345
Reid Spencere4d87aa2006-12-23 06:05:41 +00005346/// FoldGEPICmp - Fold comparisons between a GEP instruction and something
Chris Lattner574da9b2005-01-13 20:14:25 +00005347/// else. At this point we know that the GEP is on the LHS of the comparison.
Dan Gohmand6aa02d2009-07-28 01:40:03 +00005348Instruction *InstCombiner::FoldGEPICmp(GEPOperator *GEPLHS, Value *RHS,
Reid Spencere4d87aa2006-12-23 06:05:41 +00005349 ICmpInst::Predicate Cond,
5350 Instruction &I) {
Chris Lattner10c0d912008-04-22 02:53:33 +00005351 // Look through bitcasts.
5352 if (BitCastInst *BCI = dyn_cast<BitCastInst>(RHS))
5353 RHS = BCI->getOperand(0);
Chris Lattnere9d782b2005-01-13 22:25:21 +00005354
Chris Lattner574da9b2005-01-13 20:14:25 +00005355 Value *PtrBase = GEPLHS->getOperand(0);
Dan Gohmand6aa02d2009-07-28 01:40:03 +00005356 if (TD && PtrBase == RHS && GEPLHS->isInBounds()) {
Chris Lattner7c95deb2008-02-05 04:45:32 +00005357 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0).
Chris Lattner10c0d912008-04-22 02:53:33 +00005358 // This transformation (ignoring the base and scales) is valid because we
Dan Gohmand6aa02d2009-07-28 01:40:03 +00005359 // know pointers can't overflow since the gep is inbounds. See if we can
5360 // output an optimized form.
Chris Lattner10c0d912008-04-22 02:53:33 +00005361 Value *Offset = EvaluateGEPOffsetExpression(GEPLHS, I, *this);
5362
5363 // If not, synthesize the offset the hard way.
5364 if (Offset == 0)
Chris Lattner092543c2009-11-04 08:05:20 +00005365 Offset = EmitGEPOffset(GEPLHS, *this);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00005366 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Offset,
Owen Andersona7235ea2009-07-31 20:28:14 +00005367 Constant::getNullValue(Offset->getType()));
Dan Gohmand6aa02d2009-07-28 01:40:03 +00005368 } else if (GEPOperator *GEPRHS = dyn_cast<GEPOperator>(RHS)) {
Chris Lattnera70b66d2005-04-25 20:17:30 +00005369 // If the base pointers are different, but the indices are the same, just
5370 // compare the base pointer.
5371 if (PtrBase != GEPRHS->getOperand(0)) {
5372 bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
Jeff Cohen00b168892005-07-27 06:12:32 +00005373 IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
Chris Lattner93b94a62005-04-26 14:40:41 +00005374 GEPRHS->getOperand(0)->getType();
Chris Lattnera70b66d2005-04-25 20:17:30 +00005375 if (IndicesTheSame)
5376 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5377 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
5378 IndicesTheSame = false;
5379 break;
5380 }
5381
5382 // If all indices are the same, just compare the base pointers.
5383 if (IndicesTheSame)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00005384 return new ICmpInst(ICmpInst::getSignedPredicate(Cond),
Reid Spencere4d87aa2006-12-23 06:05:41 +00005385 GEPLHS->getOperand(0), GEPRHS->getOperand(0));
Chris Lattnera70b66d2005-04-25 20:17:30 +00005386
5387 // Otherwise, the base pointers are different and the indices are
5388 // different, bail out.
Chris Lattner574da9b2005-01-13 20:14:25 +00005389 return 0;
Chris Lattnera70b66d2005-04-25 20:17:30 +00005390 }
Chris Lattner574da9b2005-01-13 20:14:25 +00005391
Chris Lattnere9d782b2005-01-13 22:25:21 +00005392 // If one of the GEPs has all zero indices, recurse.
5393 bool AllZeros = true;
5394 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5395 if (!isa<Constant>(GEPLHS->getOperand(i)) ||
5396 !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
5397 AllZeros = false;
5398 break;
5399 }
5400 if (AllZeros)
Reid Spencere4d87aa2006-12-23 06:05:41 +00005401 return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
5402 ICmpInst::getSwappedPredicate(Cond), I);
Chris Lattner4401c9c2005-01-14 00:20:05 +00005403
5404 // If the other GEP has all zero indices, recurse.
Chris Lattnere9d782b2005-01-13 22:25:21 +00005405 AllZeros = true;
5406 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5407 if (!isa<Constant>(GEPRHS->getOperand(i)) ||
5408 !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
5409 AllZeros = false;
5410 break;
5411 }
5412 if (AllZeros)
Reid Spencere4d87aa2006-12-23 06:05:41 +00005413 return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
Chris Lattnere9d782b2005-01-13 22:25:21 +00005414
Chris Lattner4401c9c2005-01-14 00:20:05 +00005415 if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
5416 // If the GEPs only differ by one index, compare it.
5417 unsigned NumDifferences = 0; // Keep track of # differences.
5418 unsigned DiffOperand = 0; // The operand that differs.
5419 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5420 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
Chris Lattner484d3cf2005-04-24 06:59:08 +00005421 if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
5422 GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
Chris Lattner45f57b82005-01-21 23:06:49 +00005423 // Irreconcilable differences.
Chris Lattner4401c9c2005-01-14 00:20:05 +00005424 NumDifferences = 2;
5425 break;
5426 } else {
5427 if (NumDifferences++) break;
5428 DiffOperand = i;
5429 }
5430 }
5431
5432 if (NumDifferences == 0) // SAME GEP?
5433 return ReplaceInstUsesWith(I, // No comparison is needed here.
Chris Lattner4de84762010-01-04 07:02:48 +00005434 ConstantInt::get(Type::getInt1Ty(I.getContext()),
Nick Lewyckyfc1efbb2008-05-17 07:33:39 +00005435 ICmpInst::isTrueWhenEqual(Cond)));
Nick Lewycky455e1762007-09-06 02:40:25 +00005436
Chris Lattner4401c9c2005-01-14 00:20:05 +00005437 else if (NumDifferences == 1) {
Chris Lattner45f57b82005-01-21 23:06:49 +00005438 Value *LHSV = GEPLHS->getOperand(DiffOperand);
5439 Value *RHSV = GEPRHS->getOperand(DiffOperand);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005440 // Make sure we do a signed comparison here.
Dan Gohman1c8a23c2009-08-25 23:17:54 +00005441 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
Chris Lattner4401c9c2005-01-14 00:20:05 +00005442 }
5443 }
5444
Reid Spencere4d87aa2006-12-23 06:05:41 +00005445 // Only lower this if the icmp is the only user of the GEP or if we expect
Chris Lattner574da9b2005-01-13 20:14:25 +00005446 // the result to fold to a constant!
Dan Gohmance9fe9f2009-07-21 23:21:54 +00005447 if (TD &&
5448 (isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
Chris Lattner574da9b2005-01-13 20:14:25 +00005449 (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
5450 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2)
Chris Lattner092543c2009-11-04 08:05:20 +00005451 Value *L = EmitGEPOffset(GEPLHS, *this);
5452 Value *R = EmitGEPOffset(GEPRHS, *this);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00005453 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), L, R);
Chris Lattner574da9b2005-01-13 20:14:25 +00005454 }
5455 }
5456 return 0;
5457}
5458
Chris Lattnera5406232008-05-19 20:18:56 +00005459/// FoldFCmp_IntToFP_Cst - Fold fcmp ([us]itofp x, cst) if possible.
5460///
5461Instruction *InstCombiner::FoldFCmp_IntToFP_Cst(FCmpInst &I,
5462 Instruction *LHSI,
5463 Constant *RHSC) {
5464 if (!isa<ConstantFP>(RHSC)) return 0;
5465 const APFloat &RHS = cast<ConstantFP>(RHSC)->getValueAPF();
5466
5467 // Get the width of the mantissa. We don't want to hack on conversions that
5468 // might lose information from the integer, e.g. "i64 -> float"
Chris Lattner7be1c452008-05-19 21:17:23 +00005469 int MantissaWidth = LHSI->getType()->getFPMantissaWidth();
Chris Lattnera5406232008-05-19 20:18:56 +00005470 if (MantissaWidth == -1) return 0; // Unknown.
5471
5472 // Check to see that the input is converted from an integer type that is small
5473 // enough that preserves all bits. TODO: check here for "known" sign bits.
5474 // This would allow us to handle (fptosi (x >>s 62) to float) if x is i64 f.e.
Dan Gohman6de29f82009-06-15 22:12:54 +00005475 unsigned InputSize = LHSI->getOperand(0)->getType()->getScalarSizeInBits();
Chris Lattnera5406232008-05-19 20:18:56 +00005476
5477 // If this is a uitofp instruction, we need an extra bit to hold the sign.
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005478 bool LHSUnsigned = isa<UIToFPInst>(LHSI);
5479 if (LHSUnsigned)
Chris Lattnera5406232008-05-19 20:18:56 +00005480 ++InputSize;
5481
5482 // If the conversion would lose info, don't hack on this.
5483 if ((int)InputSize > MantissaWidth)
5484 return 0;
5485
5486 // Otherwise, we can potentially simplify the comparison. We know that it
5487 // will always come through as an integer value and we know the constant is
5488 // not a NAN (it would have been previously simplified).
5489 assert(!RHS.isNaN() && "NaN comparison not already folded!");
5490
5491 ICmpInst::Predicate Pred;
5492 switch (I.getPredicate()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00005493 default: llvm_unreachable("Unexpected predicate!");
Chris Lattnera5406232008-05-19 20:18:56 +00005494 case FCmpInst::FCMP_UEQ:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005495 case FCmpInst::FCMP_OEQ:
5496 Pred = ICmpInst::ICMP_EQ;
5497 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005498 case FCmpInst::FCMP_UGT:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005499 case FCmpInst::FCMP_OGT:
5500 Pred = LHSUnsigned ? ICmpInst::ICMP_UGT : ICmpInst::ICMP_SGT;
5501 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005502 case FCmpInst::FCMP_UGE:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005503 case FCmpInst::FCMP_OGE:
5504 Pred = LHSUnsigned ? ICmpInst::ICMP_UGE : ICmpInst::ICMP_SGE;
5505 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005506 case FCmpInst::FCMP_ULT:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005507 case FCmpInst::FCMP_OLT:
5508 Pred = LHSUnsigned ? ICmpInst::ICMP_ULT : ICmpInst::ICMP_SLT;
5509 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005510 case FCmpInst::FCMP_ULE:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005511 case FCmpInst::FCMP_OLE:
5512 Pred = LHSUnsigned ? ICmpInst::ICMP_ULE : ICmpInst::ICMP_SLE;
5513 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005514 case FCmpInst::FCMP_UNE:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005515 case FCmpInst::FCMP_ONE:
5516 Pred = ICmpInst::ICMP_NE;
5517 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005518 case FCmpInst::FCMP_ORD:
Chris Lattner4de84762010-01-04 07:02:48 +00005519 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getContext()));
Chris Lattnera5406232008-05-19 20:18:56 +00005520 case FCmpInst::FCMP_UNO:
Chris Lattner4de84762010-01-04 07:02:48 +00005521 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getContext()));
Chris Lattnera5406232008-05-19 20:18:56 +00005522 }
5523
5524 const IntegerType *IntTy = cast<IntegerType>(LHSI->getOperand(0)->getType());
5525
5526 // Now we know that the APFloat is a normal number, zero or inf.
5527
Chris Lattner85162782008-05-20 03:50:52 +00005528 // See if the FP constant is too large for the integer. For example,
Chris Lattnera5406232008-05-19 20:18:56 +00005529 // comparing an i8 to 300.0.
Dan Gohman6de29f82009-06-15 22:12:54 +00005530 unsigned IntWidth = IntTy->getScalarSizeInBits();
Chris Lattnera5406232008-05-19 20:18:56 +00005531
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005532 if (!LHSUnsigned) {
5533 // If the RHS value is > SignedMax, fold the comparison. This handles +INF
5534 // and large values.
5535 APFloat SMax(RHS.getSemantics(), APFloat::fcZero, false);
5536 SMax.convertFromAPInt(APInt::getSignedMaxValue(IntWidth), true,
5537 APFloat::rmNearestTiesToEven);
5538 if (SMax.compare(RHS) == APFloat::cmpLessThan) { // smax < 13123.0
5539 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SLT ||
5540 Pred == ICmpInst::ICMP_SLE)
Chris Lattner4de84762010-01-04 07:02:48 +00005541 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getContext()));
5542 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getContext()));
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005543 }
5544 } else {
5545 // If the RHS value is > UnsignedMax, fold the comparison. This handles
5546 // +INF and large values.
5547 APFloat UMax(RHS.getSemantics(), APFloat::fcZero, false);
5548 UMax.convertFromAPInt(APInt::getMaxValue(IntWidth), false,
5549 APFloat::rmNearestTiesToEven);
5550 if (UMax.compare(RHS) == APFloat::cmpLessThan) { // umax < 13123.0
5551 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_ULT ||
5552 Pred == ICmpInst::ICMP_ULE)
Chris Lattner4de84762010-01-04 07:02:48 +00005553 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getContext()));
5554 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getContext()));
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005555 }
Chris Lattnera5406232008-05-19 20:18:56 +00005556 }
5557
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005558 if (!LHSUnsigned) {
5559 // See if the RHS value is < SignedMin.
5560 APFloat SMin(RHS.getSemantics(), APFloat::fcZero, false);
5561 SMin.convertFromAPInt(APInt::getSignedMinValue(IntWidth), true,
5562 APFloat::rmNearestTiesToEven);
5563 if (SMin.compare(RHS) == APFloat::cmpGreaterThan) { // smin > 12312.0
5564 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SGT ||
5565 Pred == ICmpInst::ICMP_SGE)
Chris Lattner4de84762010-01-04 07:02:48 +00005566 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getContext()));
5567 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getContext()));
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005568 }
Chris Lattnera5406232008-05-19 20:18:56 +00005569 }
5570
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005571 // Okay, now we know that the FP constant fits in the range [SMIN, SMAX] or
5572 // [0, UMAX], but it may still be fractional. See if it is fractional by
5573 // casting the FP value to the integer value and back, checking for equality.
5574 // Don't do this for zero, because -0.0 is not fractional.
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005575 Constant *RHSInt = LHSUnsigned
Owen Andersonbaf3c402009-07-29 18:55:55 +00005576 ? ConstantExpr::getFPToUI(RHSC, IntTy)
5577 : ConstantExpr::getFPToSI(RHSC, IntTy);
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005578 if (!RHS.isZero()) {
5579 bool Equal = LHSUnsigned
Owen Andersonbaf3c402009-07-29 18:55:55 +00005580 ? ConstantExpr::getUIToFP(RHSInt, RHSC->getType()) == RHSC
5581 : ConstantExpr::getSIToFP(RHSInt, RHSC->getType()) == RHSC;
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005582 if (!Equal) {
5583 // If we had a comparison against a fractional value, we have to adjust
5584 // the compare predicate and sometimes the value. RHSC is rounded towards
5585 // zero at this point.
5586 switch (Pred) {
Torok Edwinc23197a2009-07-14 16:55:14 +00005587 default: llvm_unreachable("Unexpected integer comparison!");
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005588 case ICmpInst::ICMP_NE: // (float)int != 4.4 --> true
Chris Lattner4de84762010-01-04 07:02:48 +00005589 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getContext()));
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005590 case ICmpInst::ICMP_EQ: // (float)int == 4.4 --> false
Chris Lattner4de84762010-01-04 07:02:48 +00005591 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getContext()));
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005592 case ICmpInst::ICMP_ULE:
5593 // (float)int <= 4.4 --> int <= 4
5594 // (float)int <= -4.4 --> false
5595 if (RHS.isNegative())
Chris Lattner4de84762010-01-04 07:02:48 +00005596 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getContext()));
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005597 break;
5598 case ICmpInst::ICMP_SLE:
5599 // (float)int <= 4.4 --> int <= 4
5600 // (float)int <= -4.4 --> int < -4
5601 if (RHS.isNegative())
5602 Pred = ICmpInst::ICMP_SLT;
5603 break;
5604 case ICmpInst::ICMP_ULT:
5605 // (float)int < -4.4 --> false
5606 // (float)int < 4.4 --> int <= 4
5607 if (RHS.isNegative())
Chris Lattner4de84762010-01-04 07:02:48 +00005608 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getContext()));
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005609 Pred = ICmpInst::ICMP_ULE;
5610 break;
5611 case ICmpInst::ICMP_SLT:
5612 // (float)int < -4.4 --> int < -4
5613 // (float)int < 4.4 --> int <= 4
5614 if (!RHS.isNegative())
5615 Pred = ICmpInst::ICMP_SLE;
5616 break;
5617 case ICmpInst::ICMP_UGT:
5618 // (float)int > 4.4 --> int > 4
5619 // (float)int > -4.4 --> true
5620 if (RHS.isNegative())
Chris Lattner4de84762010-01-04 07:02:48 +00005621 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getContext()));
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005622 break;
5623 case ICmpInst::ICMP_SGT:
5624 // (float)int > 4.4 --> int > 4
5625 // (float)int > -4.4 --> int >= -4
5626 if (RHS.isNegative())
5627 Pred = ICmpInst::ICMP_SGE;
5628 break;
5629 case ICmpInst::ICMP_UGE:
5630 // (float)int >= -4.4 --> true
5631 // (float)int >= 4.4 --> int > 4
5632 if (!RHS.isNegative())
Chris Lattner4de84762010-01-04 07:02:48 +00005633 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getContext()));
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005634 Pred = ICmpInst::ICMP_UGT;
5635 break;
5636 case ICmpInst::ICMP_SGE:
5637 // (float)int >= -4.4 --> int >= -4
5638 // (float)int >= 4.4 --> int > 4
5639 if (!RHS.isNegative())
5640 Pred = ICmpInst::ICMP_SGT;
5641 break;
5642 }
Chris Lattnera5406232008-05-19 20:18:56 +00005643 }
5644 }
5645
5646 // Lower this FP comparison into an appropriate integer version of the
5647 // comparison.
Dan Gohman1c8a23c2009-08-25 23:17:54 +00005648 return new ICmpInst(Pred, LHSI->getOperand(0), RHSInt);
Chris Lattnera5406232008-05-19 20:18:56 +00005649}
5650
Chris Lattner1f12e442010-01-02 08:12:04 +00005651/// FoldCmpLoadFromIndexedGlobal - Called we see this pattern:
5652/// cmp pred (load (gep GV, ...)), cmpcst
5653/// where GV is a global variable with a constant initializer. Try to simplify
Chris Lattner82602bc2010-01-02 20:20:33 +00005654/// this into some simple computation that does not need the load. For example
5655/// we can optimize "icmp eq (load (gep "foo", 0, i)), 0" into "icmp eq i, 3".
Chris Lattnerdf3d63b2010-01-02 22:08:28 +00005656///
5657/// If AndCst is non-null, then the loaded value is masked with that constant
5658/// before doing the comparison. This handles cases like "A[i]&4 == 0".
Chris Lattner1f12e442010-01-02 08:12:04 +00005659Instruction *InstCombiner::
5660FoldCmpLoadFromIndexedGlobal(GetElementPtrInst *GEP, GlobalVariable *GV,
Chris Lattnerdf3d63b2010-01-02 22:08:28 +00005661 CmpInst &ICI, ConstantInt *AndCst) {
Chris Lattner56ba7a72010-01-03 03:03:27 +00005662 ConstantArray *Init = dyn_cast<ConstantArray>(GV->getInitializer());
5663 if (Init == 0 || Init->getNumOperands() > 1024) return 0;
Chris Lattner1f12e442010-01-02 08:12:04 +00005664
5665 // There are many forms of this optimization we can handle, for now, just do
5666 // the simple index into a single-dimensional array.
5667 //
Chris Lattner56ba7a72010-01-03 03:03:27 +00005668 // Require: GEP GV, 0, i {{, constant indices}}
5669 if (GEP->getNumOperands() < 3 ||
Chris Lattner1f12e442010-01-02 08:12:04 +00005670 !isa<ConstantInt>(GEP->getOperand(1)) ||
Chris Lattner56ba7a72010-01-03 03:03:27 +00005671 !cast<ConstantInt>(GEP->getOperand(1))->isZero() ||
5672 isa<Constant>(GEP->getOperand(2)))
Chris Lattner1f12e442010-01-02 08:12:04 +00005673 return 0;
Chris Lattner56ba7a72010-01-03 03:03:27 +00005674
5675 // Check that indices after the variable are constants and in-range for the
5676 // type they index. Collect the indices. This is typically for arrays of
5677 // structs.
5678 SmallVector<unsigned, 4> LaterIndices;
Chris Lattner1f12e442010-01-02 08:12:04 +00005679
Chris Lattner56ba7a72010-01-03 03:03:27 +00005680 const Type *EltTy = cast<ArrayType>(Init->getType())->getElementType();
5681 for (unsigned i = 3, e = GEP->getNumOperands(); i != e; ++i) {
5682 ConstantInt *Idx = dyn_cast<ConstantInt>(GEP->getOperand(i));
5683 if (Idx == 0) return 0; // Variable index.
5684
5685 uint64_t IdxVal = Idx->getZExtValue();
5686 if ((unsigned)IdxVal != IdxVal) return 0; // Too large array index.
5687
5688 if (const StructType *STy = dyn_cast<StructType>(EltTy))
5689 EltTy = STy->getElementType(IdxVal);
5690 else if (const ArrayType *ATy = dyn_cast<ArrayType>(EltTy)) {
5691 if (IdxVal >= ATy->getNumElements()) return 0;
5692 EltTy = ATy->getElementType();
5693 } else {
5694 return 0; // Unknown type.
5695 }
5696
5697 LaterIndices.push_back(IdxVal);
5698 }
Chris Lattner1f12e442010-01-02 08:12:04 +00005699
Chris Lattner82602bc2010-01-02 20:20:33 +00005700 enum { Overdefined = -3, Undefined = -2 };
5701
Chris Lattner1f12e442010-01-02 08:12:04 +00005702 // Variables for our state machines.
5703
Chris Lattnerbef37372010-01-02 09:35:17 +00005704 // FirstTrueElement/SecondTrueElement - Used to emit a comparison of the form
5705 // "i == 47 | i == 87", where 47 is the first index the condition is true for,
Chris Lattner82602bc2010-01-02 20:20:33 +00005706 // and 87 is the second (and last) index. FirstTrueElement is -2 when
Chris Lattnerbef37372010-01-02 09:35:17 +00005707 // undefined, otherwise set to the first true element. SecondTrueElement is
Chris Lattner82602bc2010-01-02 20:20:33 +00005708 // -2 when undefined, -3 when overdefined and >= 0 when that index is true.
5709 int FirstTrueElement = Undefined, SecondTrueElement = Undefined;
Chris Lattner1f12e442010-01-02 08:12:04 +00005710
Chris Lattnerbef37372010-01-02 09:35:17 +00005711 // FirstFalseElement/SecondFalseElement - Used to emit a comparison of the
5712 // form "i != 47 & i != 87". Same state transitions as for true elements.
Chris Lattner82602bc2010-01-02 20:20:33 +00005713 int FirstFalseElement = Undefined, SecondFalseElement = Undefined;
Chris Lattner1f12e442010-01-02 08:12:04 +00005714
Chris Lattnerb4f82b42010-01-02 21:50:18 +00005715 /// TrueRangeEnd/FalseRangeEnd - In conjunction with First*Element, these
5716 /// define a state machine that triggers for ranges of values that the index
5717 /// is true or false for. This triggers on things like "abbbbc"[i] == 'b'.
5718 /// This is -2 when undefined, -3 when overdefined, and otherwise the last
5719 /// index in the range (inclusive). We use -2 for undefined here because we
5720 /// use relative comparisons and don't want 0-1 to match -1.
5721 int TrueRangeEnd = Undefined, FalseRangeEnd = Undefined;
5722
Chris Lattner10d514e2010-01-02 08:56:52 +00005723 // MagicBitvector - This is a magic bitvector where we set a bit if the
5724 // comparison is true for element 'i'. If there are 64 elements or less in
5725 // the array, this will fully represent all the comparison results.
5726 uint64_t MagicBitvector = 0;
5727
5728
Chris Lattner1f12e442010-01-02 08:12:04 +00005729 // Scan the array and see if one of our patterns matches.
5730 Constant *CompareRHS = cast<Constant>(ICI.getOperand(1));
5731 for (unsigned i = 0, e = Init->getNumOperands(); i != e; ++i) {
Chris Lattnerdf3d63b2010-01-02 22:08:28 +00005732 Constant *Elt = Init->getOperand(i);
5733
Chris Lattner56ba7a72010-01-03 03:03:27 +00005734 // If this is indexing an array of structures, get the structure element.
5735 if (!LaterIndices.empty())
5736 Elt = ConstantExpr::getExtractValue(Elt, LaterIndices.data(),
5737 LaterIndices.size());
5738
Chris Lattnerdf3d63b2010-01-02 22:08:28 +00005739 // If the element is masked, handle it.
5740 if (AndCst) Elt = ConstantExpr::getAnd(Elt, AndCst);
5741
Chris Lattner1f12e442010-01-02 08:12:04 +00005742 // Find out if the comparison would be true or false for the i'th element.
Chris Lattnerdf3d63b2010-01-02 22:08:28 +00005743 Constant *C = ConstantFoldCompareInstOperands(ICI.getPredicate(), Elt,
Chris Lattner1f12e442010-01-02 08:12:04 +00005744 CompareRHS, TD);
5745 // If the result is undef for this element, ignore it.
Chris Lattnerb4f82b42010-01-02 21:50:18 +00005746 if (isa<UndefValue>(C)) {
5747 // Extend range state machines to cover this element in case there is an
5748 // undef in the middle of the range.
5749 if (TrueRangeEnd == (int)i-1)
5750 TrueRangeEnd = i;
5751 if (FalseRangeEnd == (int)i-1)
5752 FalseRangeEnd = i;
5753 continue;
5754 }
Chris Lattner1f12e442010-01-02 08:12:04 +00005755
5756 // If we can't compute the result for any of the elements, we have to give
5757 // up evaluating the entire conditional.
5758 if (!isa<ConstantInt>(C)) return 0;
5759
5760 // Otherwise, we know if the comparison is true or false for this element,
5761 // update our state machines.
5762 bool IsTrueForElt = !cast<ConstantInt>(C)->isZero();
5763
Chris Lattnerb4f82b42010-01-02 21:50:18 +00005764 // State machine for single/double/range index comparison.
Chris Lattner1f12e442010-01-02 08:12:04 +00005765 if (IsTrueForElt) {
Chris Lattnerbef37372010-01-02 09:35:17 +00005766 // Update the TrueElement state machine.
Chris Lattner82602bc2010-01-02 20:20:33 +00005767 if (FirstTrueElement == Undefined)
Chris Lattnerb4f82b42010-01-02 21:50:18 +00005768 FirstTrueElement = TrueRangeEnd = i; // First true element.
5769 else {
5770 // Update double-compare state machine.
5771 if (SecondTrueElement == Undefined)
5772 SecondTrueElement = i;
5773 else
5774 SecondTrueElement = Overdefined;
5775
5776 // Update range state machine.
5777 if (TrueRangeEnd == (int)i-1)
5778 TrueRangeEnd = i;
5779 else
5780 TrueRangeEnd = Overdefined;
5781 }
Chris Lattner1f12e442010-01-02 08:12:04 +00005782 } else {
Chris Lattnerbef37372010-01-02 09:35:17 +00005783 // Update the FalseElement state machine.
Chris Lattner82602bc2010-01-02 20:20:33 +00005784 if (FirstFalseElement == Undefined)
Chris Lattnerb4f82b42010-01-02 21:50:18 +00005785 FirstFalseElement = FalseRangeEnd = i; // First false element.
5786 else {
5787 // Update double-compare state machine.
5788 if (SecondFalseElement == Undefined)
5789 SecondFalseElement = i;
5790 else
5791 SecondFalseElement = Overdefined;
5792
5793 // Update range state machine.
5794 if (FalseRangeEnd == (int)i-1)
5795 FalseRangeEnd = i;
5796 else
5797 FalseRangeEnd = Overdefined;
5798 }
Chris Lattner1f12e442010-01-02 08:12:04 +00005799 }
5800
Chris Lattnerb4f82b42010-01-02 21:50:18 +00005801
Chris Lattner10d514e2010-01-02 08:56:52 +00005802 // If this element is in range, update our magic bitvector.
5803 if (i < 64 && IsTrueForElt)
Chris Lattner33a1ec72010-01-02 09:22:13 +00005804 MagicBitvector |= 1ULL << i;
Chris Lattner10d514e2010-01-02 08:56:52 +00005805
Chris Lattnerb4f82b42010-01-02 21:50:18 +00005806 // If all of our states become overdefined, bail out early. Since the
5807 // predicate is expensive, only check it every 8 elements. This is only
5808 // really useful for really huge arrays.
5809 if ((i & 8) == 0 && i >= 64 && SecondTrueElement == Overdefined &&
5810 SecondFalseElement == Overdefined && TrueRangeEnd == Overdefined &&
5811 FalseRangeEnd == Overdefined)
Chris Lattner1f12e442010-01-02 08:12:04 +00005812 return 0;
5813 }
5814
5815 // Now that we've scanned the entire array, emit our new comparison(s). We
5816 // order the state machines in complexity of the generated code.
Chris Lattnerbef37372010-01-02 09:35:17 +00005817 Value *Idx = GEP->getOperand(2);
5818
Chris Lattnerb4f82b42010-01-02 21:50:18 +00005819
Chris Lattnerbef37372010-01-02 09:35:17 +00005820 // If the comparison is only true for one or two elements, emit direct
5821 // comparisons.
Chris Lattner82602bc2010-01-02 20:20:33 +00005822 if (SecondTrueElement != Overdefined) {
Chris Lattner1f12e442010-01-02 08:12:04 +00005823 // None true -> false.
Chris Lattner82602bc2010-01-02 20:20:33 +00005824 if (FirstTrueElement == Undefined)
Chris Lattner4de84762010-01-04 07:02:48 +00005825 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(GEP->getContext()));
Chris Lattner1f12e442010-01-02 08:12:04 +00005826
Chris Lattnerbef37372010-01-02 09:35:17 +00005827 Value *FirstTrueIdx = ConstantInt::get(Idx->getType(), FirstTrueElement);
5828
Chris Lattner1f12e442010-01-02 08:12:04 +00005829 // True for one element -> 'i == 47'.
Chris Lattner82602bc2010-01-02 20:20:33 +00005830 if (SecondTrueElement == Undefined)
Chris Lattnerbef37372010-01-02 09:35:17 +00005831 return new ICmpInst(ICmpInst::ICMP_EQ, Idx, FirstTrueIdx);
5832
5833 // True for two elements -> 'i == 47 | i == 72'.
5834 Value *C1 = Builder->CreateICmpEQ(Idx, FirstTrueIdx);
5835 Value *SecondTrueIdx = ConstantInt::get(Idx->getType(), SecondTrueElement);
5836 Value *C2 = Builder->CreateICmpEQ(Idx, SecondTrueIdx);
5837 return BinaryOperator::CreateOr(C1, C2);
Chris Lattner1f12e442010-01-02 08:12:04 +00005838 }
5839
Chris Lattnerbef37372010-01-02 09:35:17 +00005840 // If the comparison is only false for one or two elements, emit direct
5841 // comparisons.
Chris Lattner82602bc2010-01-02 20:20:33 +00005842 if (SecondFalseElement != Overdefined) {
Chris Lattner1f12e442010-01-02 08:12:04 +00005843 // None false -> true.
Chris Lattner82602bc2010-01-02 20:20:33 +00005844 if (FirstFalseElement == Undefined)
Chris Lattner4de84762010-01-04 07:02:48 +00005845 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(GEP->getContext()));
Chris Lattner1f12e442010-01-02 08:12:04 +00005846
Chris Lattnerbef37372010-01-02 09:35:17 +00005847 Value *FirstFalseIdx = ConstantInt::get(Idx->getType(), FirstFalseElement);
5848
5849 // False for one element -> 'i != 47'.
Chris Lattner82602bc2010-01-02 20:20:33 +00005850 if (SecondFalseElement == Undefined)
Chris Lattnerbef37372010-01-02 09:35:17 +00005851 return new ICmpInst(ICmpInst::ICMP_NE, Idx, FirstFalseIdx);
5852
5853 // False for two elements -> 'i != 47 & i != 72'.
5854 Value *C1 = Builder->CreateICmpNE(Idx, FirstFalseIdx);
5855 Value *SecondFalseIdx = ConstantInt::get(Idx->getType(),SecondFalseElement);
5856 Value *C2 = Builder->CreateICmpNE(Idx, SecondFalseIdx);
5857 return BinaryOperator::CreateAnd(C1, C2);
Chris Lattner1f12e442010-01-02 08:12:04 +00005858 }
5859
Chris Lattnerb4f82b42010-01-02 21:50:18 +00005860 // If the comparison can be replaced with a range comparison for the elements
5861 // where it is true, emit the range check.
5862 if (TrueRangeEnd != Overdefined) {
5863 assert(TrueRangeEnd != FirstTrueElement && "Should emit single compare");
5864
5865 // Generate (i-FirstTrue) <u (TrueRangeEnd-FirstTrue+1).
5866 if (FirstTrueElement) {
5867 Value *Offs = ConstantInt::get(Idx->getType(), -FirstTrueElement);
5868 Idx = Builder->CreateAdd(Idx, Offs);
5869 }
5870
5871 Value *End = ConstantInt::get(Idx->getType(),
5872 TrueRangeEnd-FirstTrueElement+1);
5873 return new ICmpInst(ICmpInst::ICMP_ULT, Idx, End);
5874 }
5875
5876 // False range check.
5877 if (FalseRangeEnd != Overdefined) {
5878 assert(FalseRangeEnd != FirstFalseElement && "Should emit single compare");
5879 // Generate (i-FirstFalse) >u (FalseRangeEnd-FirstFalse).
5880 if (FirstFalseElement) {
5881 Value *Offs = ConstantInt::get(Idx->getType(), -FirstFalseElement);
5882 Idx = Builder->CreateAdd(Idx, Offs);
5883 }
5884
5885 Value *End = ConstantInt::get(Idx->getType(),
5886 FalseRangeEnd-FirstFalseElement);
5887 return new ICmpInst(ICmpInst::ICMP_UGT, Idx, End);
5888 }
5889
5890
Chris Lattner10d514e2010-01-02 08:56:52 +00005891 // If a 32-bit or 64-bit magic bitvector captures the entire comparison state
5892 // of this load, replace it with computation that does:
5893 // ((magic_cst >> i) & 1) != 0
5894 if (Init->getNumOperands() <= 32 ||
5895 (TD && Init->getNumOperands() <= 64 && TD->isLegalInteger(64))) {
5896 const Type *Ty;
5897 if (Init->getNumOperands() <= 32)
5898 Ty = Type::getInt32Ty(Init->getContext());
5899 else
5900 Ty = Type::getInt64Ty(Init->getContext());
Chris Lattnerbef37372010-01-02 09:35:17 +00005901 Value *V = Builder->CreateIntCast(Idx, Ty, false);
Chris Lattner10d514e2010-01-02 08:56:52 +00005902 V = Builder->CreateLShr(ConstantInt::get(Ty, MagicBitvector), V);
5903 V = Builder->CreateAnd(ConstantInt::get(Ty, 1), V);
5904 return new ICmpInst(ICmpInst::ICMP_NE, V, ConstantInt::get(Ty, 0));
5905 }
Chris Lattner1f12e442010-01-02 08:12:04 +00005906
Chris Lattner1f12e442010-01-02 08:12:04 +00005907 return 0;
5908}
5909
5910
Reid Spencere4d87aa2006-12-23 06:05:41 +00005911Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
Chris Lattnerb0bdac02009-11-09 23:31:49 +00005912 bool Changed = false;
5913
5914 /// Orders the operands of the compare so that they are listed from most
5915 /// complex to least complex. This puts constants before unary operators,
5916 /// before binary operators.
5917 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1))) {
5918 I.swapOperands();
5919 Changed = true;
5920 }
5921
Chris Lattner8b170942002-08-09 23:47:40 +00005922 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner58e97462007-01-14 19:42:17 +00005923
Chris Lattner210c5d42009-11-09 23:55:12 +00005924 if (Value *V = SimplifyFCmpInst(I.getPredicate(), Op0, Op1, TD))
5925 return ReplaceInstUsesWith(I, V);
5926
Chris Lattner58e97462007-01-14 19:42:17 +00005927 // Simplify 'fcmp pred X, X'
5928 if (Op0 == Op1) {
5929 switch (I.getPredicate()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00005930 default: llvm_unreachable("Unknown predicate!");
Chris Lattner58e97462007-01-14 19:42:17 +00005931 case FCmpInst::FCMP_UNO: // True if unordered: isnan(X) | isnan(Y)
5932 case FCmpInst::FCMP_ULT: // True if unordered or less than
5933 case FCmpInst::FCMP_UGT: // True if unordered or greater than
5934 case FCmpInst::FCMP_UNE: // True if unordered or not equal
5935 // Canonicalize these to be 'fcmp uno %X, 0.0'.
5936 I.setPredicate(FCmpInst::FCMP_UNO);
Owen Andersona7235ea2009-07-31 20:28:14 +00005937 I.setOperand(1, Constant::getNullValue(Op0->getType()));
Chris Lattner58e97462007-01-14 19:42:17 +00005938 return &I;
5939
5940 case FCmpInst::FCMP_ORD: // True if ordered (no nans)
5941 case FCmpInst::FCMP_OEQ: // True if ordered and equal
5942 case FCmpInst::FCMP_OGE: // True if ordered and greater than or equal
5943 case FCmpInst::FCMP_OLE: // True if ordered and less than or equal
5944 // Canonicalize these to be 'fcmp ord %X, 0.0'.
5945 I.setPredicate(FCmpInst::FCMP_ORD);
Owen Andersona7235ea2009-07-31 20:28:14 +00005946 I.setOperand(1, Constant::getNullValue(Op0->getType()));
Chris Lattner58e97462007-01-14 19:42:17 +00005947 return &I;
5948 }
5949 }
5950
Reid Spencere4d87aa2006-12-23 06:05:41 +00005951 // Handle fcmp with constant RHS
5952 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
5953 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5954 switch (LHSI->getOpcode()) {
5955 case Instruction::PHI:
Chris Lattner7d8ab4e2008-06-08 20:52:11 +00005956 // Only fold fcmp into the PHI if the phi and fcmp are in the same
5957 // block. If in the same block, we're encouraging jump threading. If
5958 // not, we are just pessimizing the code by making an i1 phi.
5959 if (LHSI->getParent() == I.getParent())
Chris Lattner213cd612009-09-27 20:46:36 +00005960 if (Instruction *NV = FoldOpIntoPhi(I, true))
Chris Lattner7d8ab4e2008-06-08 20:52:11 +00005961 return NV;
Reid Spencere4d87aa2006-12-23 06:05:41 +00005962 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005963 case Instruction::SIToFP:
5964 case Instruction::UIToFP:
5965 if (Instruction *NV = FoldFCmp_IntToFP_Cst(I, LHSI, RHSC))
5966 return NV;
5967 break;
Chris Lattner34e0c762010-01-02 08:20:51 +00005968 case Instruction::Select: {
Reid Spencere4d87aa2006-12-23 06:05:41 +00005969 // If either operand of the select is a constant, we can fold the
5970 // comparison into the select arms, which will cause one to be
5971 // constant folded and the select turned into a bitwise or.
5972 Value *Op1 = 0, *Op2 = 0;
5973 if (LHSI->hasOneUse()) {
5974 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5975 // Fold the known value into the constant operand.
Owen Andersonbaf3c402009-07-29 18:55:55 +00005976 Op1 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005977 // Insert a new FCmp of the other select operand.
Chris Lattner74381062009-08-30 07:44:24 +00005978 Op2 = Builder->CreateFCmp(I.getPredicate(),
5979 LHSI->getOperand(2), RHSC, I.getName());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005980 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5981 // Fold the known value into the constant operand.
Owen Andersonbaf3c402009-07-29 18:55:55 +00005982 Op2 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005983 // Insert a new FCmp of the other select operand.
Chris Lattner74381062009-08-30 07:44:24 +00005984 Op1 = Builder->CreateFCmp(I.getPredicate(), LHSI->getOperand(1),
5985 RHSC, I.getName());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005986 }
5987 }
5988
5989 if (Op1)
Gabor Greif051a9502008-04-06 20:25:17 +00005990 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005991 break;
5992 }
Chris Lattner34e0c762010-01-02 08:20:51 +00005993 case Instruction::Load:
5994 if (GetElementPtrInst *GEP =
5995 dyn_cast<GetElementPtrInst>(LHSI->getOperand(0))) {
5996 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0)))
5997 if (GV->isConstant() && GV->hasDefinitiveInitializer() &&
Chris Lattnera0085af2010-01-03 06:58:48 +00005998 !cast<LoadInst>(LHSI)->isVolatile())
Chris Lattner34e0c762010-01-02 08:20:51 +00005999 if (Instruction *Res = FoldCmpLoadFromIndexedGlobal(GEP, GV, I))
6000 return Res;
Chris Lattner34e0c762010-01-02 08:20:51 +00006001 }
6002 break;
6003 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00006004 }
6005
6006 return Changed ? &I : 0;
6007}
6008
6009Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
Chris Lattnerb0bdac02009-11-09 23:31:49 +00006010 bool Changed = false;
6011
6012 /// Orders the operands of the compare so that they are listed from most
6013 /// complex to least complex. This puts constants before unary operators,
6014 /// before binary operators.
6015 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1))) {
6016 I.swapOperands();
6017 Changed = true;
6018 }
6019
Reid Spencere4d87aa2006-12-23 06:05:41 +00006020 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Christopher Lamb7a0678c2007-12-18 21:32:20 +00006021
Chris Lattner210c5d42009-11-09 23:55:12 +00006022 if (Value *V = SimplifyICmpInst(I.getPredicate(), Op0, Op1, TD))
6023 return ReplaceInstUsesWith(I, V);
6024
6025 const Type *Ty = Op0->getType();
Chris Lattner8b170942002-08-09 23:47:40 +00006026
Reid Spencere4d87aa2006-12-23 06:05:41 +00006027 // icmp's with boolean values can always be turned into bitwise operations
Chris Lattner4de84762010-01-04 07:02:48 +00006028 if (Ty == Type::getInt1Ty(I.getContext())) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006029 switch (I.getPredicate()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00006030 default: llvm_unreachable("Invalid icmp instruction!");
Chris Lattner85b5eb02008-07-11 04:20:58 +00006031 case ICmpInst::ICMP_EQ: { // icmp eq i1 A, B -> ~(A^B)
Chris Lattner74381062009-08-30 07:44:24 +00006032 Value *Xor = Builder->CreateXor(Op0, Op1, I.getName()+"tmp");
Dan Gohman4ae51262009-08-12 16:23:25 +00006033 return BinaryOperator::CreateNot(Xor);
Chris Lattner8b170942002-08-09 23:47:40 +00006034 }
Chris Lattner85b5eb02008-07-11 04:20:58 +00006035 case ICmpInst::ICMP_NE: // icmp eq i1 A, B -> A^B
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006036 return BinaryOperator::CreateXor(Op0, Op1);
Chris Lattner8b170942002-08-09 23:47:40 +00006037
Reid Spencere4d87aa2006-12-23 06:05:41 +00006038 case ICmpInst::ICMP_UGT:
Chris Lattner85b5eb02008-07-11 04:20:58 +00006039 std::swap(Op0, Op1); // Change icmp ugt -> icmp ult
Chris Lattner5dbef222004-08-11 00:50:51 +00006040 // FALL THROUGH
Chris Lattner85b5eb02008-07-11 04:20:58 +00006041 case ICmpInst::ICMP_ULT:{ // icmp ult i1 A, B -> ~A & B
Chris Lattner74381062009-08-30 07:44:24 +00006042 Value *Not = Builder->CreateNot(Op0, I.getName()+"tmp");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006043 return BinaryOperator::CreateAnd(Not, Op1);
Chris Lattner5dbef222004-08-11 00:50:51 +00006044 }
Chris Lattner85b5eb02008-07-11 04:20:58 +00006045 case ICmpInst::ICMP_SGT:
6046 std::swap(Op0, Op1); // Change icmp sgt -> icmp slt
Chris Lattner5dbef222004-08-11 00:50:51 +00006047 // FALL THROUGH
Chris Lattner85b5eb02008-07-11 04:20:58 +00006048 case ICmpInst::ICMP_SLT: { // icmp slt i1 A, B -> A & ~B
Chris Lattner74381062009-08-30 07:44:24 +00006049 Value *Not = Builder->CreateNot(Op1, I.getName()+"tmp");
Chris Lattner85b5eb02008-07-11 04:20:58 +00006050 return BinaryOperator::CreateAnd(Not, Op0);
6051 }
6052 case ICmpInst::ICMP_UGE:
6053 std::swap(Op0, Op1); // Change icmp uge -> icmp ule
6054 // FALL THROUGH
6055 case ICmpInst::ICMP_ULE: { // icmp ule i1 A, B -> ~A | B
Chris Lattner74381062009-08-30 07:44:24 +00006056 Value *Not = Builder->CreateNot(Op0, I.getName()+"tmp");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006057 return BinaryOperator::CreateOr(Not, Op1);
Chris Lattner5dbef222004-08-11 00:50:51 +00006058 }
Chris Lattner85b5eb02008-07-11 04:20:58 +00006059 case ICmpInst::ICMP_SGE:
6060 std::swap(Op0, Op1); // Change icmp sge -> icmp sle
6061 // FALL THROUGH
6062 case ICmpInst::ICMP_SLE: { // icmp sle i1 A, B -> A | ~B
Chris Lattner74381062009-08-30 07:44:24 +00006063 Value *Not = Builder->CreateNot(Op1, I.getName()+"tmp");
Chris Lattner85b5eb02008-07-11 04:20:58 +00006064 return BinaryOperator::CreateOr(Not, Op0);
6065 }
Chris Lattner5dbef222004-08-11 00:50:51 +00006066 }
Chris Lattner8b170942002-08-09 23:47:40 +00006067 }
6068
Dan Gohman1c8491e2009-04-25 17:12:48 +00006069 unsigned BitWidth = 0;
6070 if (TD)
Dan Gohmanc6ac3222009-06-16 19:55:29 +00006071 BitWidth = TD->getTypeSizeInBits(Ty->getScalarType());
6072 else if (Ty->isIntOrIntVector())
6073 BitWidth = Ty->getScalarSizeInBits();
Dan Gohman1c8491e2009-04-25 17:12:48 +00006074
6075 bool isSignBit = false;
6076
Dan Gohman81b28ce2008-09-16 18:46:06 +00006077 // See if we are doing a comparison with a constant.
Chris Lattner8b170942002-08-09 23:47:40 +00006078 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Nick Lewycky579214a2009-02-27 06:37:39 +00006079 Value *A = 0, *B = 0;
Christopher Lamb103e1a32007-12-20 07:21:11 +00006080
Chris Lattnerb6566012008-01-05 01:18:20 +00006081 // (icmp ne/eq (sub A B) 0) -> (icmp ne/eq A, B)
Chris Lattner1f12e442010-01-02 08:12:04 +00006082 if (I.isEquality() && CI->isZero() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00006083 match(Op0, m_Sub(m_Value(A), m_Value(B)))) {
Chris Lattnerb6566012008-01-05 01:18:20 +00006084 // (icmp cond A B) if cond is equality
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006085 return new ICmpInst(I.getPredicate(), A, B);
Owen Andersonf5783f82007-12-28 07:42:12 +00006086 }
Christopher Lamb103e1a32007-12-20 07:21:11 +00006087
Dan Gohman81b28ce2008-09-16 18:46:06 +00006088 // If we have an icmp le or icmp ge instruction, turn it into the
6089 // appropriate icmp lt or icmp gt instruction. This allows us to rely on
Chris Lattner210c5d42009-11-09 23:55:12 +00006090 // them being folded in the code below. The SimplifyICmpInst code has
6091 // already handled the edge cases for us, so we just assert on them.
Chris Lattner84dff672008-07-11 05:08:55 +00006092 switch (I.getPredicate()) {
6093 default: break;
6094 case ICmpInst::ICMP_ULE:
Chris Lattner210c5d42009-11-09 23:55:12 +00006095 assert(!CI->isMaxValue(false)); // A <=u MAX -> TRUE
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006096 return new ICmpInst(ICmpInst::ICMP_ULT, Op0,
Dan Gohman186a6362009-08-12 16:04:34 +00006097 AddOne(CI));
Chris Lattner84dff672008-07-11 05:08:55 +00006098 case ICmpInst::ICMP_SLE:
Chris Lattner210c5d42009-11-09 23:55:12 +00006099 assert(!CI->isMaxValue(true)); // A <=s MAX -> TRUE
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006100 return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
Dan Gohman186a6362009-08-12 16:04:34 +00006101 AddOne(CI));
Chris Lattner84dff672008-07-11 05:08:55 +00006102 case ICmpInst::ICMP_UGE:
Chris Lattner210c5d42009-11-09 23:55:12 +00006103 assert(!CI->isMinValue(false)); // A >=u MIN -> TRUE
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006104 return new ICmpInst(ICmpInst::ICMP_UGT, Op0,
Dan Gohman186a6362009-08-12 16:04:34 +00006105 SubOne(CI));
Chris Lattner84dff672008-07-11 05:08:55 +00006106 case ICmpInst::ICMP_SGE:
Chris Lattner210c5d42009-11-09 23:55:12 +00006107 assert(!CI->isMinValue(true)); // A >=s MIN -> TRUE
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006108 return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
Dan Gohman186a6362009-08-12 16:04:34 +00006109 SubOne(CI));
Chris Lattner84dff672008-07-11 05:08:55 +00006110 }
6111
Chris Lattner183661e2008-07-11 05:40:05 +00006112 // If this comparison is a normal comparison, it demands all
Chris Lattner4241e4d2007-07-15 20:54:51 +00006113 // bits, if it is a sign bit comparison, it only demands the sign bit.
Chris Lattner4241e4d2007-07-15 20:54:51 +00006114 bool UnusedBit;
Dan Gohman1c8491e2009-04-25 17:12:48 +00006115 isSignBit = isSignBitCheck(I.getPredicate(), CI, UnusedBit);
6116 }
6117
6118 // See if we can fold the comparison based on range information we can get
6119 // by checking whether bits are known to be zero or one in the input.
6120 if (BitWidth != 0) {
6121 APInt Op0KnownZero(BitWidth, 0), Op0KnownOne(BitWidth, 0);
6122 APInt Op1KnownZero(BitWidth, 0), Op1KnownOne(BitWidth, 0);
6123
6124 if (SimplifyDemandedBits(I.getOperandUse(0),
Chris Lattner4241e4d2007-07-15 20:54:51 +00006125 isSignBit ? APInt::getSignBit(BitWidth)
6126 : APInt::getAllOnesValue(BitWidth),
Dan Gohman1c8491e2009-04-25 17:12:48 +00006127 Op0KnownZero, Op0KnownOne, 0))
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00006128 return &I;
Dan Gohman1c8491e2009-04-25 17:12:48 +00006129 if (SimplifyDemandedBits(I.getOperandUse(1),
6130 APInt::getAllOnesValue(BitWidth),
6131 Op1KnownZero, Op1KnownOne, 0))
6132 return &I;
6133
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00006134 // Given the known and unknown bits, compute a range that the LHS could be
Chris Lattner84dff672008-07-11 05:08:55 +00006135 // in. Compute the Min, Max and RHS values based on the known bits. For the
6136 // EQ and NE we use unsigned values.
Dan Gohman1c8491e2009-04-25 17:12:48 +00006137 APInt Op0Min(BitWidth, 0), Op0Max(BitWidth, 0);
6138 APInt Op1Min(BitWidth, 0), Op1Max(BitWidth, 0);
Nick Lewycky4a134af2009-10-25 05:20:17 +00006139 if (I.isSigned()) {
Dan Gohman1c8491e2009-04-25 17:12:48 +00006140 ComputeSignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
6141 Op0Min, Op0Max);
6142 ComputeSignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
6143 Op1Min, Op1Max);
6144 } else {
6145 ComputeUnsignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
6146 Op0Min, Op0Max);
6147 ComputeUnsignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
6148 Op1Min, Op1Max);
6149 }
6150
Chris Lattner183661e2008-07-11 05:40:05 +00006151 // If Min and Max are known to be the same, then SimplifyDemandedBits
6152 // figured out that the LHS is a constant. Just constant fold this now so
6153 // that code below can assume that Min != Max.
Dan Gohman1c8491e2009-04-25 17:12:48 +00006154 if (!isa<Constant>(Op0) && Op0Min == Op0Max)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006155 return new ICmpInst(I.getPredicate(),
Chris Lattner4de84762010-01-04 07:02:48 +00006156 ConstantInt::get(I.getContext(), Op0Min), Op1);
Dan Gohman1c8491e2009-04-25 17:12:48 +00006157 if (!isa<Constant>(Op1) && Op1Min == Op1Max)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006158 return new ICmpInst(I.getPredicate(), Op0,
Chris Lattner4de84762010-01-04 07:02:48 +00006159 ConstantInt::get(I.getContext(), Op1Min));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006160
Chris Lattner183661e2008-07-11 05:40:05 +00006161 // Based on the range information we know about the LHS, see if we can
6162 // simplify this comparison. For example, (x&4) < 8 is always true.
Dan Gohman1c8491e2009-04-25 17:12:48 +00006163 switch (I.getPredicate()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00006164 default: llvm_unreachable("Unknown icmp opcode!");
Chris Lattner84dff672008-07-11 05:08:55 +00006165 case ICmpInst::ICMP_EQ:
Dan Gohman1c8491e2009-04-25 17:12:48 +00006166 if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
Chris Lattner4de84762010-01-04 07:02:48 +00006167 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getContext()));
Chris Lattner84dff672008-07-11 05:08:55 +00006168 break;
6169 case ICmpInst::ICMP_NE:
Dan Gohman1c8491e2009-04-25 17:12:48 +00006170 if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
Chris Lattner4de84762010-01-04 07:02:48 +00006171 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getContext()));
Chris Lattner84dff672008-07-11 05:08:55 +00006172 break;
6173 case ICmpInst::ICMP_ULT:
Dan Gohman1c8491e2009-04-25 17:12:48 +00006174 if (Op0Max.ult(Op1Min)) // A <u B -> true if max(A) < min(B)
Chris Lattner4de84762010-01-04 07:02:48 +00006175 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getContext()));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006176 if (Op0Min.uge(Op1Max)) // A <u B -> false if min(A) >= max(B)
Chris Lattner4de84762010-01-04 07:02:48 +00006177 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getContext()));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006178 if (Op1Min == Op0Max) // A <u B -> A != B if max(A) == min(B)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006179 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
Dan Gohman1c8491e2009-04-25 17:12:48 +00006180 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6181 if (Op1Max == Op0Min+1) // A <u C -> A == C-1 if min(A)+1 == C
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006182 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
Dan Gohman186a6362009-08-12 16:04:34 +00006183 SubOne(CI));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006184
6185 // (x <u 2147483648) -> (x >s -1) -> true if sign bit clear
6186 if (CI->isMinValue(true))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006187 return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
Owen Andersona7235ea2009-07-31 20:28:14 +00006188 Constant::getAllOnesValue(Op0->getType()));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006189 }
Chris Lattner84dff672008-07-11 05:08:55 +00006190 break;
6191 case ICmpInst::ICMP_UGT:
Dan Gohman1c8491e2009-04-25 17:12:48 +00006192 if (Op0Min.ugt(Op1Max)) // A >u B -> true if min(A) > max(B)
Chris Lattner4de84762010-01-04 07:02:48 +00006193 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getContext()));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006194 if (Op0Max.ule(Op1Min)) // A >u B -> false if max(A) <= max(B)
Chris Lattner4de84762010-01-04 07:02:48 +00006195 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getContext()));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006196
6197 if (Op1Max == Op0Min) // A >u B -> A != B if min(A) == max(B)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006198 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
Dan Gohman1c8491e2009-04-25 17:12:48 +00006199 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6200 if (Op1Min == Op0Max-1) // A >u C -> A == C+1 if max(a)-1 == C
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006201 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
Dan Gohman186a6362009-08-12 16:04:34 +00006202 AddOne(CI));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006203
6204 // (x >u 2147483647) -> (x <s 0) -> true if sign bit set
6205 if (CI->isMaxValue(true))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006206 return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
Owen Andersona7235ea2009-07-31 20:28:14 +00006207 Constant::getNullValue(Op0->getType()));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006208 }
Chris Lattner84dff672008-07-11 05:08:55 +00006209 break;
6210 case ICmpInst::ICMP_SLT:
Dan Gohman1c8491e2009-04-25 17:12:48 +00006211 if (Op0Max.slt(Op1Min)) // A <s B -> true if max(A) < min(C)
Chris Lattner4de84762010-01-04 07:02:48 +00006212 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getContext()));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006213 if (Op0Min.sge(Op1Max)) // A <s B -> false if min(A) >= max(C)
Chris Lattner4de84762010-01-04 07:02:48 +00006214 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getContext()));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006215 if (Op1Min == Op0Max) // A <s B -> A != B if max(A) == min(B)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006216 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
Dan Gohman1c8491e2009-04-25 17:12:48 +00006217 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6218 if (Op1Max == Op0Min+1) // A <s C -> A == C-1 if min(A)+1 == C
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006219 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
Dan Gohman186a6362009-08-12 16:04:34 +00006220 SubOne(CI));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006221 }
Chris Lattner84dff672008-07-11 05:08:55 +00006222 break;
Dan Gohman1c8491e2009-04-25 17:12:48 +00006223 case ICmpInst::ICMP_SGT:
6224 if (Op0Min.sgt(Op1Max)) // A >s B -> true if min(A) > max(B)
Chris Lattner4de84762010-01-04 07:02:48 +00006225 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getContext()));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006226 if (Op0Max.sle(Op1Min)) // A >s B -> false if max(A) <= min(B)
Chris Lattner4de84762010-01-04 07:02:48 +00006227 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getContext()));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006228
6229 if (Op1Max == Op0Min) // A >s B -> A != B if min(A) == max(B)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006230 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
Dan Gohman1c8491e2009-04-25 17:12:48 +00006231 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6232 if (Op1Min == Op0Max-1) // A >s C -> A == C+1 if max(A)-1 == C
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006233 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
Dan Gohman186a6362009-08-12 16:04:34 +00006234 AddOne(CI));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006235 }
6236 break;
6237 case ICmpInst::ICMP_SGE:
6238 assert(!isa<ConstantInt>(Op1) && "ICMP_SGE with ConstantInt not folded!");
6239 if (Op0Min.sge(Op1Max)) // A >=s B -> true if min(A) >= max(B)
Chris Lattner4de84762010-01-04 07:02:48 +00006240 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getContext()));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006241 if (Op0Max.slt(Op1Min)) // A >=s B -> false if max(A) < min(B)
Chris Lattner4de84762010-01-04 07:02:48 +00006242 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getContext()));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006243 break;
6244 case ICmpInst::ICMP_SLE:
6245 assert(!isa<ConstantInt>(Op1) && "ICMP_SLE with ConstantInt not folded!");
6246 if (Op0Max.sle(Op1Min)) // A <=s B -> true if max(A) <= min(B)
Chris Lattner4de84762010-01-04 07:02:48 +00006247 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getContext()));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006248 if (Op0Min.sgt(Op1Max)) // A <=s B -> false if min(A) > max(B)
Chris Lattner4de84762010-01-04 07:02:48 +00006249 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getContext()));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006250 break;
6251 case ICmpInst::ICMP_UGE:
6252 assert(!isa<ConstantInt>(Op1) && "ICMP_UGE with ConstantInt not folded!");
6253 if (Op0Min.uge(Op1Max)) // A >=u B -> true if min(A) >= max(B)
Chris Lattner4de84762010-01-04 07:02:48 +00006254 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getContext()));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006255 if (Op0Max.ult(Op1Min)) // A >=u B -> false if max(A) < min(B)
Chris Lattner4de84762010-01-04 07:02:48 +00006256 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getContext()));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006257 break;
6258 case ICmpInst::ICMP_ULE:
6259 assert(!isa<ConstantInt>(Op1) && "ICMP_ULE with ConstantInt not folded!");
6260 if (Op0Max.ule(Op1Min)) // A <=u B -> true if max(A) <= min(B)
Chris Lattner4de84762010-01-04 07:02:48 +00006261 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getContext()));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006262 if (Op0Min.ugt(Op1Max)) // A <=u B -> false if min(A) > max(B)
Chris Lattner4de84762010-01-04 07:02:48 +00006263 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getContext()));
Chris Lattner84dff672008-07-11 05:08:55 +00006264 break;
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00006265 }
Dan Gohman1c8491e2009-04-25 17:12:48 +00006266
6267 // Turn a signed comparison into an unsigned one if both operands
6268 // are known to have the same sign.
Nick Lewycky4a134af2009-10-25 05:20:17 +00006269 if (I.isSigned() &&
Dan Gohman1c8491e2009-04-25 17:12:48 +00006270 ((Op0KnownZero.isNegative() && Op1KnownZero.isNegative()) ||
6271 (Op0KnownOne.isNegative() && Op1KnownOne.isNegative())))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006272 return new ICmpInst(I.getUnsignedPredicate(), Op0, Op1);
Dan Gohman81b28ce2008-09-16 18:46:06 +00006273 }
6274
6275 // Test if the ICmpInst instruction is used exclusively by a select as
6276 // part of a minimum or maximum operation. If so, refrain from doing
6277 // any other folding. This helps out other analyses which understand
6278 // non-obfuscated minimum and maximum idioms, such as ScalarEvolution
6279 // and CodeGen. And in this case, at least one of the comparison
6280 // operands has at least one user besides the compare (the select),
6281 // which would often largely negate the benefit of folding anyway.
6282 if (I.hasOneUse())
6283 if (SelectInst *SI = dyn_cast<SelectInst>(*I.use_begin()))
6284 if ((SI->getOperand(1) == Op0 && SI->getOperand(2) == Op1) ||
6285 (SI->getOperand(2) == Op0 && SI->getOperand(1) == Op1))
6286 return 0;
6287
6288 // See if we are doing a comparison between a constant and an instruction that
6289 // can be folded into the comparison.
6290 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006291 // Since the RHS is a ConstantInt (CI), if the left hand side is an
Reid Spencer1628cec2006-10-26 06:15:43 +00006292 // instruction, see if that instruction also has constants so that the
Reid Spencere4d87aa2006-12-23 06:05:41 +00006293 // instruction can be folded into the icmp
Chris Lattner3c6a0d42004-05-25 06:32:08 +00006294 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
Chris Lattner01deb9d2007-04-03 17:43:25 +00006295 if (Instruction *Res = visitICmpInstWithInstAndIntCst(I, LHSI, CI))
6296 return Res;
Chris Lattner3f5b8772002-05-06 16:14:14 +00006297 }
6298
Chris Lattner01deb9d2007-04-03 17:43:25 +00006299 // Handle icmp with constant (but not simple integer constant) RHS
Chris Lattner6970b662005-04-23 15:31:55 +00006300 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
6301 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
6302 switch (LHSI->getOpcode()) {
Chris Lattner9fb25db2005-05-01 04:42:15 +00006303 case Instruction::GetElementPtr:
Reid Spencere4d87aa2006-12-23 06:05:41 +00006304 // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
Chris Lattnerec12d052010-01-01 23:09:08 +00006305 if (RHSC->isNullValue() &&
6306 cast<GetElementPtrInst>(LHSI)->hasAllZeroIndices())
6307 return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
6308 Constant::getNullValue(LHSI->getOperand(0)->getType()));
Chris Lattner9fb25db2005-05-01 04:42:15 +00006309 break;
Chris Lattner6970b662005-04-23 15:31:55 +00006310 case Instruction::PHI:
Chris Lattner213cd612009-09-27 20:46:36 +00006311 // Only fold icmp into the PHI if the phi and icmp are in the same
Chris Lattner7d8ab4e2008-06-08 20:52:11 +00006312 // block. If in the same block, we're encouraging jump threading. If
6313 // not, we are just pessimizing the code by making an i1 phi.
6314 if (LHSI->getParent() == I.getParent())
Chris Lattner213cd612009-09-27 20:46:36 +00006315 if (Instruction *NV = FoldOpIntoPhi(I, true))
Chris Lattner7d8ab4e2008-06-08 20:52:11 +00006316 return NV;
Chris Lattner6970b662005-04-23 15:31:55 +00006317 break;
Chris Lattner4802d902007-04-06 18:57:34 +00006318 case Instruction::Select: {
Chris Lattner6970b662005-04-23 15:31:55 +00006319 // If either operand of the select is a constant, we can fold the
6320 // comparison into the select arms, which will cause one to be
6321 // constant folded and the select turned into a bitwise or.
6322 Value *Op1 = 0, *Op2 = 0;
Eli Friedman97b087c2009-12-18 08:22:35 +00006323 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1)))
6324 Op1 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
6325 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2)))
6326 Op2 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
6327
6328 // We only want to perform this transformation if it will not lead to
6329 // additional code. This is true if either both sides of the select
6330 // fold to a constant (in which case the icmp is replaced with a select
6331 // which will usually simplify) or this is the only user of the
6332 // select (in which case we are trading a select+icmp for a simpler
6333 // select+icmp).
6334 if ((Op1 && Op2) || (LHSI->hasOneUse() && (Op1 || Op2))) {
6335 if (!Op1)
Chris Lattner74381062009-08-30 07:44:24 +00006336 Op1 = Builder->CreateICmp(I.getPredicate(), LHSI->getOperand(1),
6337 RHSC, I.getName());
Eli Friedman97b087c2009-12-18 08:22:35 +00006338 if (!Op2)
6339 Op2 = Builder->CreateICmp(I.getPredicate(), LHSI->getOperand(2),
6340 RHSC, I.getName());
Gabor Greif051a9502008-04-06 20:25:17 +00006341 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
Eli Friedman97b087c2009-12-18 08:22:35 +00006342 }
Chris Lattner6970b662005-04-23 15:31:55 +00006343 break;
6344 }
Victor Hernandez83d63912009-09-18 22:35:49 +00006345 case Instruction::Call:
6346 // If we have (malloc != null), and if the malloc has a single use, we
6347 // can assume it is successful and remove the malloc.
6348 if (isMalloc(LHSI) && LHSI->hasOneUse() &&
6349 isa<ConstantPointerNull>(RHSC)) {
Victor Hernandez68afa542009-10-21 19:11:40 +00006350 // Need to explicitly erase malloc call here, instead of adding it to
6351 // Worklist, because it won't get DCE'd from the Worklist since
6352 // isInstructionTriviallyDead() returns false for function calls.
6353 // It is OK to replace LHSI/MallocCall with Undef because the
6354 // instruction that uses it will be erased via Worklist.
6355 if (extractMallocCall(LHSI)) {
6356 LHSI->replaceAllUsesWith(UndefValue::get(LHSI->getType()));
6357 EraseInstFromFunction(*LHSI);
6358 return ReplaceInstUsesWith(I,
Chris Lattner4de84762010-01-04 07:02:48 +00006359 ConstantInt::get(Type::getInt1Ty(I.getContext()),
Victor Hernandez83d63912009-09-18 22:35:49 +00006360 !I.isTrueWhenEqual()));
Victor Hernandez68afa542009-10-21 19:11:40 +00006361 }
6362 if (CallInst* MallocCall = extractMallocCallFromBitCast(LHSI))
6363 if (MallocCall->hasOneUse()) {
6364 MallocCall->replaceAllUsesWith(
6365 UndefValue::get(MallocCall->getType()));
6366 EraseInstFromFunction(*MallocCall);
6367 Worklist.Add(LHSI); // The malloc's bitcast use.
6368 return ReplaceInstUsesWith(I,
Chris Lattner4de84762010-01-04 07:02:48 +00006369 ConstantInt::get(Type::getInt1Ty(I.getContext()),
Victor Hernandez68afa542009-10-21 19:11:40 +00006370 !I.isTrueWhenEqual()));
6371 }
Victor Hernandez83d63912009-09-18 22:35:49 +00006372 }
6373 break;
Chris Lattnerec12d052010-01-01 23:09:08 +00006374 case Instruction::IntToPtr:
6375 // icmp pred inttoptr(X), null -> icmp pred X, 0
6376 if (RHSC->isNullValue() && TD &&
6377 TD->getIntPtrType(RHSC->getContext()) ==
6378 LHSI->getOperand(0)->getType())
6379 return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
6380 Constant::getNullValue(LHSI->getOperand(0)->getType()));
6381 break;
Chris Lattner1f12e442010-01-02 08:12:04 +00006382
6383 case Instruction::Load:
Chris Lattnerdf3d63b2010-01-02 22:08:28 +00006384 // Try to optimize things like "A[i] > 4" to index computations.
Chris Lattner1f12e442010-01-02 08:12:04 +00006385 if (GetElementPtrInst *GEP =
Chris Lattner34e0c762010-01-02 08:20:51 +00006386 dyn_cast<GetElementPtrInst>(LHSI->getOperand(0))) {
Chris Lattner1f12e442010-01-02 08:12:04 +00006387 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0)))
6388 if (GV->isConstant() && GV->hasDefinitiveInitializer() &&
Chris Lattnera0085af2010-01-03 06:58:48 +00006389 !cast<LoadInst>(LHSI)->isVolatile())
Chris Lattner1f12e442010-01-02 08:12:04 +00006390 if (Instruction *Res = FoldCmpLoadFromIndexedGlobal(GEP, GV, I))
6391 return Res;
Chris Lattner34e0c762010-01-02 08:20:51 +00006392 }
Chris Lattner1f12e442010-01-02 08:12:04 +00006393 break;
Chris Lattner4802d902007-04-06 18:57:34 +00006394 }
Chris Lattner6970b662005-04-23 15:31:55 +00006395 }
6396
Reid Spencere4d87aa2006-12-23 06:05:41 +00006397 // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
Dan Gohmand6aa02d2009-07-28 01:40:03 +00006398 if (GEPOperator *GEP = dyn_cast<GEPOperator>(Op0))
Reid Spencere4d87aa2006-12-23 06:05:41 +00006399 if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
Chris Lattner574da9b2005-01-13 20:14:25 +00006400 return NI;
Dan Gohmand6aa02d2009-07-28 01:40:03 +00006401 if (GEPOperator *GEP = dyn_cast<GEPOperator>(Op1))
Reid Spencere4d87aa2006-12-23 06:05:41 +00006402 if (Instruction *NI = FoldGEPICmp(GEP, Op0,
6403 ICmpInst::getSwappedPredicate(I.getPredicate()), I))
Chris Lattner574da9b2005-01-13 20:14:25 +00006404 return NI;
6405
Reid Spencere4d87aa2006-12-23 06:05:41 +00006406 // Test to see if the operands of the icmp are casted versions of other
Chris Lattner57d86372007-01-06 01:45:59 +00006407 // values. If the ptr->ptr cast can be stripped off both arguments, we do so
6408 // now.
6409 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
6410 if (isa<PointerType>(Op0->getType()) &&
6411 (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) {
Chris Lattnerde90b762003-11-03 04:25:02 +00006412 // We keep moving the cast from the left operand over to the right
6413 // operand, where it can often be eliminated completely.
Chris Lattner57d86372007-01-06 01:45:59 +00006414 Op0 = CI->getOperand(0);
Misha Brukmanfd939082005-04-21 23:48:37 +00006415
Chris Lattner57d86372007-01-06 01:45:59 +00006416 // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
6417 // so eliminate it as well.
6418 if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
6419 Op1 = CI2->getOperand(0);
Misha Brukmanfd939082005-04-21 23:48:37 +00006420
Chris Lattnerde90b762003-11-03 04:25:02 +00006421 // If Op1 is a constant, we can fold the cast into the constant.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00006422 if (Op0->getType() != Op1->getType()) {
Chris Lattnerde90b762003-11-03 04:25:02 +00006423 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00006424 Op1 = ConstantExpr::getBitCast(Op1C, Op0->getType());
Chris Lattnerde90b762003-11-03 04:25:02 +00006425 } else {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006426 // Otherwise, cast the RHS right before the icmp
Chris Lattner08142f22009-08-30 19:47:22 +00006427 Op1 = Builder->CreateBitCast(Op1, Op0->getType());
Chris Lattnerde90b762003-11-03 04:25:02 +00006428 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00006429 }
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006430 return new ICmpInst(I.getPredicate(), Op0, Op1);
Chris Lattnerde90b762003-11-03 04:25:02 +00006431 }
Chris Lattner57d86372007-01-06 01:45:59 +00006432 }
6433
6434 if (isa<CastInst>(Op0)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006435 // Handle the special case of: icmp (cast bool to X), <cst>
Chris Lattner68708052003-11-03 05:17:03 +00006436 // This comes up when you have code like
6437 // int X = A < B;
6438 // if (X) ...
6439 // For generality, we handle any zero-extension of any operand comparison
Chris Lattner484d3cf2005-04-24 06:59:08 +00006440 // with a constant or another cast from the same type.
Eli Friedman8e4b1972009-12-17 21:27:47 +00006441 if (isa<Constant>(Op1) || isa<CastInst>(Op1))
Reid Spencere4d87aa2006-12-23 06:05:41 +00006442 if (Instruction *R = visitICmpInstWithCastAndCast(I))
Chris Lattner484d3cf2005-04-24 06:59:08 +00006443 return R;
Chris Lattner68708052003-11-03 05:17:03 +00006444 }
Chris Lattner26ab9a92006-02-27 01:44:11 +00006445
Nick Lewycky4bf1e592008-07-11 07:20:53 +00006446 // See if it's the same type of instruction on the left and right.
6447 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
6448 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
Nick Lewycky5d52c452008-08-21 05:56:10 +00006449 if (Op0I->getOpcode() == Op1I->getOpcode() && Op0I->hasOneUse() &&
Nick Lewycky4333f492009-01-31 21:30:05 +00006450 Op1I->hasOneUse() && Op0I->getOperand(1) == Op1I->getOperand(1)) {
Nick Lewycky23c04302008-09-03 06:24:21 +00006451 switch (Op0I->getOpcode()) {
Nick Lewycky4bf1e592008-07-11 07:20:53 +00006452 default: break;
6453 case Instruction::Add:
6454 case Instruction::Sub:
6455 case Instruction::Xor:
Chris Lattnerf5db1fb2009-02-02 07:15:30 +00006456 if (I.isEquality()) // a+x icmp eq/ne b+x --> a icmp b
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006457 return new ICmpInst(I.getPredicate(), Op0I->getOperand(0),
Nick Lewycky4333f492009-01-31 21:30:05 +00006458 Op1I->getOperand(0));
Chris Lattnerf5db1fb2009-02-02 07:15:30 +00006459 // icmp u/s (a ^ signbit), (b ^ signbit) --> icmp s/u a, b
6460 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
6461 if (CI->getValue().isSignBit()) {
Nick Lewycky4a134af2009-10-25 05:20:17 +00006462 ICmpInst::Predicate Pred = I.isSigned()
Chris Lattnerf5db1fb2009-02-02 07:15:30 +00006463 ? I.getUnsignedPredicate()
6464 : I.getSignedPredicate();
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006465 return new ICmpInst(Pred, Op0I->getOperand(0),
Chris Lattnerf5db1fb2009-02-02 07:15:30 +00006466 Op1I->getOperand(0));
6467 }
6468
6469 if (CI->getValue().isMaxSignedValue()) {
Nick Lewycky4a134af2009-10-25 05:20:17 +00006470 ICmpInst::Predicate Pred = I.isSigned()
Chris Lattnerf5db1fb2009-02-02 07:15:30 +00006471 ? I.getUnsignedPredicate()
6472 : I.getSignedPredicate();
6473 Pred = I.getSwappedPredicate(Pred);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006474 return new ICmpInst(Pred, Op0I->getOperand(0),
Chris Lattnerf5db1fb2009-02-02 07:15:30 +00006475 Op1I->getOperand(0));
Nick Lewycky4333f492009-01-31 21:30:05 +00006476 }
6477 }
Nick Lewycky4bf1e592008-07-11 07:20:53 +00006478 break;
6479 case Instruction::Mul:
Nick Lewycky4333f492009-01-31 21:30:05 +00006480 if (!I.isEquality())
6481 break;
6482
Nick Lewycky5d52c452008-08-21 05:56:10 +00006483 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
6484 // a * Cst icmp eq/ne b * Cst --> a & Mask icmp b & Mask
6485 // Mask = -1 >> count-trailing-zeros(Cst).
6486 if (!CI->isZero() && !CI->isOne()) {
6487 const APInt &AP = CI->getValue();
Chris Lattner4de84762010-01-04 07:02:48 +00006488 ConstantInt *Mask = ConstantInt::get(I.getContext(),
Nick Lewycky5d52c452008-08-21 05:56:10 +00006489 APInt::getLowBitsSet(AP.getBitWidth(),
6490 AP.getBitWidth() -
Nick Lewycky4bf1e592008-07-11 07:20:53 +00006491 AP.countTrailingZeros()));
Chris Lattner74381062009-08-30 07:44:24 +00006492 Value *And1 = Builder->CreateAnd(Op0I->getOperand(0), Mask);
6493 Value *And2 = Builder->CreateAnd(Op1I->getOperand(0), Mask);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006494 return new ICmpInst(I.getPredicate(), And1, And2);
Nick Lewycky4bf1e592008-07-11 07:20:53 +00006495 }
6496 }
6497 break;
6498 }
6499 }
6500 }
6501 }
6502
Chris Lattner7d2cbd22008-05-09 05:19:28 +00006503 // ~x < ~y --> y < x
6504 { Value *A, *B;
Dan Gohman4ae51262009-08-12 16:23:25 +00006505 if (match(Op0, m_Not(m_Value(A))) &&
6506 match(Op1, m_Not(m_Value(B))))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006507 return new ICmpInst(I.getPredicate(), B, A);
Chris Lattner7d2cbd22008-05-09 05:19:28 +00006508 }
6509
Chris Lattner65b72ba2006-09-18 04:22:48 +00006510 if (I.isEquality()) {
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006511 Value *A, *B, *C, *D;
Chris Lattner7d2cbd22008-05-09 05:19:28 +00006512
6513 // -x == -y --> x == y
Dan Gohman4ae51262009-08-12 16:23:25 +00006514 if (match(Op0, m_Neg(m_Value(A))) &&
6515 match(Op1, m_Neg(m_Value(B))))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006516 return new ICmpInst(I.getPredicate(), A, B);
Chris Lattner7d2cbd22008-05-09 05:19:28 +00006517
Dan Gohman4ae51262009-08-12 16:23:25 +00006518 if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006519 if (A == Op1 || B == Op1) { // (A^B) == A -> B == 0
6520 Value *OtherVal = A == Op1 ? B : A;
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006521 return new ICmpInst(I.getPredicate(), OtherVal,
Owen Andersona7235ea2009-07-31 20:28:14 +00006522 Constant::getNullValue(A->getType()));
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006523 }
6524
Dan Gohman4ae51262009-08-12 16:23:25 +00006525 if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) {
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006526 // A^c1 == C^c2 --> A == C^(c1^c2)
Chris Lattnercb504b92008-11-16 05:38:51 +00006527 ConstantInt *C1, *C2;
Dan Gohman4ae51262009-08-12 16:23:25 +00006528 if (match(B, m_ConstantInt(C1)) &&
6529 match(D, m_ConstantInt(C2)) && Op1->hasOneUse()) {
Chris Lattner4de84762010-01-04 07:02:48 +00006530 Constant *NC = ConstantInt::get(I.getContext(),
6531 C1->getValue() ^ C2->getValue());
Chris Lattner74381062009-08-30 07:44:24 +00006532 Value *Xor = Builder->CreateXor(C, NC, "tmp");
6533 return new ICmpInst(I.getPredicate(), A, Xor);
Chris Lattnercb504b92008-11-16 05:38:51 +00006534 }
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006535
6536 // A^B == A^D -> B == D
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006537 if (A == C) return new ICmpInst(I.getPredicate(), B, D);
6538 if (A == D) return new ICmpInst(I.getPredicate(), B, C);
6539 if (B == C) return new ICmpInst(I.getPredicate(), A, D);
6540 if (B == D) return new ICmpInst(I.getPredicate(), A, C);
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006541 }
6542 }
6543
Dan Gohman4ae51262009-08-12 16:23:25 +00006544 if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006545 (A == Op0 || B == Op0)) {
Chris Lattner26ab9a92006-02-27 01:44:11 +00006546 // A == (A^B) -> B == 0
6547 Value *OtherVal = A == Op0 ? B : A;
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006548 return new ICmpInst(I.getPredicate(), OtherVal,
Owen Andersona7235ea2009-07-31 20:28:14 +00006549 Constant::getNullValue(A->getType()));
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006550 }
Chris Lattnercb504b92008-11-16 05:38:51 +00006551
6552 // (A-B) == A -> B == 0
Dan Gohman4ae51262009-08-12 16:23:25 +00006553 if (match(Op0, m_Sub(m_Specific(Op1), m_Value(B))))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006554 return new ICmpInst(I.getPredicate(), B,
Owen Andersona7235ea2009-07-31 20:28:14 +00006555 Constant::getNullValue(B->getType()));
Chris Lattnercb504b92008-11-16 05:38:51 +00006556
6557 // A == (A-B) -> B == 0
Dan Gohman4ae51262009-08-12 16:23:25 +00006558 if (match(Op1, m_Sub(m_Specific(Op0), m_Value(B))))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006559 return new ICmpInst(I.getPredicate(), B,
Owen Andersona7235ea2009-07-31 20:28:14 +00006560 Constant::getNullValue(B->getType()));
Chris Lattner9c2328e2006-11-14 06:06:06 +00006561
Chris Lattner9c2328e2006-11-14 06:06:06 +00006562 // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
6563 if (Op0->hasOneUse() && Op1->hasOneUse() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00006564 match(Op0, m_And(m_Value(A), m_Value(B))) &&
6565 match(Op1, m_And(m_Value(C), m_Value(D)))) {
Chris Lattner9c2328e2006-11-14 06:06:06 +00006566 Value *X = 0, *Y = 0, *Z = 0;
6567
6568 if (A == C) {
6569 X = B; Y = D; Z = A;
6570 } else if (A == D) {
6571 X = B; Y = C; Z = A;
6572 } else if (B == C) {
6573 X = A; Y = D; Z = B;
6574 } else if (B == D) {
6575 X = A; Y = C; Z = B;
6576 }
6577
6578 if (X) { // Build (X^Y) & Z
Chris Lattner74381062009-08-30 07:44:24 +00006579 Op1 = Builder->CreateXor(X, Y, "tmp");
6580 Op1 = Builder->CreateAnd(Op1, Z, "tmp");
Chris Lattner9c2328e2006-11-14 06:06:06 +00006581 I.setOperand(0, Op1);
Owen Andersona7235ea2009-07-31 20:28:14 +00006582 I.setOperand(1, Constant::getNullValue(Op1->getType()));
Chris Lattner9c2328e2006-11-14 06:06:06 +00006583 return &I;
6584 }
6585 }
Chris Lattner26ab9a92006-02-27 01:44:11 +00006586 }
Chris Lattner2799baf2009-12-21 03:19:28 +00006587
6588 {
6589 Value *X; ConstantInt *Cst;
Chris Lattner3bf68152009-12-21 04:04:05 +00006590 // icmp X+Cst, X
Chris Lattner2799baf2009-12-21 03:19:28 +00006591 if (match(Op0, m_Add(m_Value(X), m_ConstantInt(Cst))) && Op1 == X)
Chris Lattner3bf68152009-12-21 04:04:05 +00006592 return FoldICmpAddOpCst(I, X, Cst, I.getPredicate(), Op0);
6593
Chris Lattner2799baf2009-12-21 03:19:28 +00006594 // icmp X, X+Cst
6595 if (match(Op1, m_Add(m_Value(X), m_ConstantInt(Cst))) && Op0 == X)
Chris Lattner3bf68152009-12-21 04:04:05 +00006596 return FoldICmpAddOpCst(I, X, Cst, I.getSwappedPredicate(), Op1);
Chris Lattner2799baf2009-12-21 03:19:28 +00006597 }
Chris Lattner7e708292002-06-25 16:13:24 +00006598 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00006599}
6600
Chris Lattner2799baf2009-12-21 03:19:28 +00006601/// FoldICmpAddOpCst - Fold "icmp pred (X+CI), X".
6602Instruction *InstCombiner::FoldICmpAddOpCst(ICmpInst &ICI,
6603 Value *X, ConstantInt *CI,
Chris Lattner3bf68152009-12-21 04:04:05 +00006604 ICmpInst::Predicate Pred,
6605 Value *TheAdd) {
Chris Lattner2799baf2009-12-21 03:19:28 +00006606 // If we have X+0, exit early (simplifying logic below) and let it get folded
6607 // elsewhere. icmp X+0, X -> icmp X, X
6608 if (CI->isZero()) {
6609 bool isTrue = ICmpInst::isTrueWhenEqual(Pred);
6610 return ReplaceInstUsesWith(ICI, ConstantInt::get(ICI.getType(), isTrue));
6611 }
6612
6613 // (X+4) == X -> false.
6614 if (Pred == ICmpInst::ICMP_EQ)
6615 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(X->getContext()));
6616
6617 // (X+4) != X -> true.
6618 if (Pred == ICmpInst::ICMP_NE)
6619 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(X->getContext()));
Chris Lattner3bf68152009-12-21 04:04:05 +00006620
6621 // If this is an instruction (as opposed to constantexpr) get NUW/NSW info.
6622 bool isNUW = false, isNSW = false;
6623 if (BinaryOperator *Add = dyn_cast<BinaryOperator>(TheAdd)) {
6624 isNUW = Add->hasNoUnsignedWrap();
6625 isNSW = Add->hasNoSignedWrap();
6626 }
Chris Lattner2799baf2009-12-21 03:19:28 +00006627
6628 // From this point on, we know that (X+C <= X) --> (X+C < X) because C != 0,
6629 // so the values can never be equal. Similiarly for all other "or equals"
6630 // operators.
6631
6632 // (X+1) <u X --> X >u (MAXUINT-1) --> X != 255
6633 // (X+2) <u X --> X >u (MAXUINT-2) --> X > 253
6634 // (X+MAXUINT) <u X --> X >u (MAXUINT-MAXUINT) --> X != 0
6635 if (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_ULE) {
Chris Lattner3bf68152009-12-21 04:04:05 +00006636 // If this is an NUW add, then this is always false.
6637 if (isNUW)
6638 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(X->getContext()));
6639
Chris Lattner2799baf2009-12-21 03:19:28 +00006640 Value *R = ConstantExpr::getSub(ConstantInt::get(CI->getType(), -1ULL), CI);
6641 return new ICmpInst(ICmpInst::ICMP_UGT, X, R);
6642 }
6643
6644 // (X+1) >u X --> X <u (0-1) --> X != 255
6645 // (X+2) >u X --> X <u (0-2) --> X <u 254
6646 // (X+MAXUINT) >u X --> X <u (0-MAXUINT) --> X <u 1 --> X == 0
Chris Lattner3bf68152009-12-21 04:04:05 +00006647 if (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_UGE) {
6648 // If this is an NUW add, then this is always true.
6649 if (isNUW)
6650 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(X->getContext()));
Chris Lattner2799baf2009-12-21 03:19:28 +00006651 return new ICmpInst(ICmpInst::ICMP_ULT, X, ConstantExpr::getNeg(CI));
Chris Lattner3bf68152009-12-21 04:04:05 +00006652 }
Chris Lattner2799baf2009-12-21 03:19:28 +00006653
6654 unsigned BitWidth = CI->getType()->getPrimitiveSizeInBits();
6655 ConstantInt *SMax = ConstantInt::get(X->getContext(),
6656 APInt::getSignedMaxValue(BitWidth));
6657
6658 // (X+ 1) <s X --> X >s (MAXSINT-1) --> X == 127
6659 // (X+ 2) <s X --> X >s (MAXSINT-2) --> X >s 125
6660 // (X+MAXSINT) <s X --> X >s (MAXSINT-MAXSINT) --> X >s 0
6661 // (X+MINSINT) <s X --> X >s (MAXSINT-MINSINT) --> X >s -1
6662 // (X+ -2) <s X --> X >s (MAXSINT- -2) --> X >s 126
6663 // (X+ -1) <s X --> X >s (MAXSINT- -1) --> X != 127
Chris Lattner3bf68152009-12-21 04:04:05 +00006664 if (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE) {
6665 // If this is an NSW add, then we have two cases: if the constant is
6666 // positive, then this is always false, if negative, this is always true.
6667 if (isNSW) {
6668 bool isTrue = CI->getValue().isNegative();
6669 return ReplaceInstUsesWith(ICI, ConstantInt::get(ICI.getType(), isTrue));
6670 }
6671
Chris Lattner2799baf2009-12-21 03:19:28 +00006672 return new ICmpInst(ICmpInst::ICMP_SGT, X, ConstantExpr::getSub(SMax, CI));
Chris Lattner3bf68152009-12-21 04:04:05 +00006673 }
Chris Lattner2799baf2009-12-21 03:19:28 +00006674
6675 // (X+ 1) >s X --> X <s (MAXSINT-(1-1)) --> X != 127
6676 // (X+ 2) >s X --> X <s (MAXSINT-(2-1)) --> X <s 126
6677 // (X+MAXSINT) >s X --> X <s (MAXSINT-(MAXSINT-1)) --> X <s 1
6678 // (X+MINSINT) >s X --> X <s (MAXSINT-(MINSINT-1)) --> X <s -2
6679 // (X+ -2) >s X --> X <s (MAXSINT-(-2-1)) --> X <s -126
6680 // (X+ -1) >s X --> X <s (MAXSINT-(-1-1)) --> X == -128
Chris Lattner3bf68152009-12-21 04:04:05 +00006681
6682 // If this is an NSW add, then we have two cases: if the constant is
6683 // positive, then this is always true, if negative, this is always false.
6684 if (isNSW) {
6685 bool isTrue = !CI->getValue().isNegative();
6686 return ReplaceInstUsesWith(ICI, ConstantInt::get(ICI.getType(), isTrue));
6687 }
6688
Chris Lattner2799baf2009-12-21 03:19:28 +00006689 assert(Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SGE);
6690 Constant *C = ConstantInt::get(X->getContext(), CI->getValue()-1);
6691 return new ICmpInst(ICmpInst::ICMP_SLT, X, ConstantExpr::getSub(SMax, C));
6692}
Chris Lattner562ef782007-06-20 23:46:26 +00006693
6694/// FoldICmpDivCst - Fold "icmp pred, ([su]div X, DivRHS), CmpRHS" where DivRHS
6695/// and CmpRHS are both known to be integer constants.
6696Instruction *InstCombiner::FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
6697 ConstantInt *DivRHS) {
6698 ConstantInt *CmpRHS = cast<ConstantInt>(ICI.getOperand(1));
6699 const APInt &CmpRHSV = CmpRHS->getValue();
6700
6701 // FIXME: If the operand types don't match the type of the divide
6702 // then don't attempt this transform. The code below doesn't have the
6703 // logic to deal with a signed divide and an unsigned compare (and
6704 // vice versa). This is because (x /s C1) <s C2 produces different
6705 // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
6706 // (x /u C1) <u C2. Simply casting the operands and result won't
6707 // work. :( The if statement below tests that condition and bails
6708 // if it finds it.
6709 bool DivIsSigned = DivI->getOpcode() == Instruction::SDiv;
Nick Lewycky4a134af2009-10-25 05:20:17 +00006710 if (!ICI.isEquality() && DivIsSigned != ICI.isSigned())
Chris Lattner562ef782007-06-20 23:46:26 +00006711 return 0;
6712 if (DivRHS->isZero())
Chris Lattner1dbfd482007-06-21 18:11:19 +00006713 return 0; // The ProdOV computation fails on divide by zero.
Chris Lattnera6321b42008-10-11 22:55:00 +00006714 if (DivIsSigned && DivRHS->isAllOnesValue())
6715 return 0; // The overflow computation also screws up here
6716 if (DivRHS->isOne())
6717 return 0; // Not worth bothering, and eliminates some funny cases
6718 // with INT_MIN.
Chris Lattner562ef782007-06-20 23:46:26 +00006719
6720 // Compute Prod = CI * DivRHS. We are essentially solving an equation
6721 // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and
6722 // C2 (CI). By solving for X we can turn this into a range check
6723 // instead of computing a divide.
Owen Andersonbaf3c402009-07-29 18:55:55 +00006724 Constant *Prod = ConstantExpr::getMul(CmpRHS, DivRHS);
Chris Lattner562ef782007-06-20 23:46:26 +00006725
6726 // Determine if the product overflows by seeing if the product is
6727 // not equal to the divide. Make sure we do the same kind of divide
6728 // as in the LHS instruction that we're folding.
Owen Andersonbaf3c402009-07-29 18:55:55 +00006729 bool ProdOV = (DivIsSigned ? ConstantExpr::getSDiv(Prod, DivRHS) :
6730 ConstantExpr::getUDiv(Prod, DivRHS)) != CmpRHS;
Chris Lattner562ef782007-06-20 23:46:26 +00006731
6732 // Get the ICmp opcode
Chris Lattner1dbfd482007-06-21 18:11:19 +00006733 ICmpInst::Predicate Pred = ICI.getPredicate();
Chris Lattner562ef782007-06-20 23:46:26 +00006734
Chris Lattner1dbfd482007-06-21 18:11:19 +00006735 // Figure out the interval that is being checked. For example, a comparison
6736 // like "X /u 5 == 0" is really checking that X is in the interval [0, 5).
6737 // Compute this interval based on the constants involved and the signedness of
6738 // the compare/divide. This computes a half-open interval, keeping track of
6739 // whether either value in the interval overflows. After analysis each
6740 // overflow variable is set to 0 if it's corresponding bound variable is valid
6741 // -1 if overflowed off the bottom end, or +1 if overflowed off the top end.
6742 int LoOverflow = 0, HiOverflow = 0;
Dan Gohman6de29f82009-06-15 22:12:54 +00006743 Constant *LoBound = 0, *HiBound = 0;
Chris Lattner1dbfd482007-06-21 18:11:19 +00006744
Chris Lattner562ef782007-06-20 23:46:26 +00006745 if (!DivIsSigned) { // udiv
Chris Lattner1dbfd482007-06-21 18:11:19 +00006746 // e.g. X/5 op 3 --> [15, 20)
Chris Lattner562ef782007-06-20 23:46:26 +00006747 LoBound = Prod;
Chris Lattner1dbfd482007-06-21 18:11:19 +00006748 HiOverflow = LoOverflow = ProdOV;
6749 if (!HiOverflow)
Chris Lattner4de84762010-01-04 07:02:48 +00006750 HiOverflow = AddWithOverflow(HiBound, LoBound, DivRHS, false);
Dan Gohman76491272008-02-13 22:09:18 +00006751 } else if (DivRHS->getValue().isStrictlyPositive()) { // Divisor is > 0.
Chris Lattner562ef782007-06-20 23:46:26 +00006752 if (CmpRHSV == 0) { // (X / pos) op 0
Chris Lattner1dbfd482007-06-21 18:11:19 +00006753 // Can't overflow. e.g. X/2 op 0 --> [-1, 2)
Dan Gohman186a6362009-08-12 16:04:34 +00006754 LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
Chris Lattner562ef782007-06-20 23:46:26 +00006755 HiBound = DivRHS;
Dan Gohman76491272008-02-13 22:09:18 +00006756 } else if (CmpRHSV.isStrictlyPositive()) { // (X / pos) op pos
Chris Lattner1dbfd482007-06-21 18:11:19 +00006757 LoBound = Prod; // e.g. X/5 op 3 --> [15, 20)
6758 HiOverflow = LoOverflow = ProdOV;
6759 if (!HiOverflow)
Chris Lattner4de84762010-01-04 07:02:48 +00006760 HiOverflow = AddWithOverflow(HiBound, Prod, DivRHS, true);
Chris Lattner562ef782007-06-20 23:46:26 +00006761 } else { // (X / pos) op neg
Chris Lattner1dbfd482007-06-21 18:11:19 +00006762 // e.g. X/5 op -3 --> [-15-4, -15+1) --> [-19, -14)
Dan Gohman186a6362009-08-12 16:04:34 +00006763 HiBound = AddOne(Prod);
Chris Lattnera6321b42008-10-11 22:55:00 +00006764 LoOverflow = HiOverflow = ProdOV ? -1 : 0;
6765 if (!LoOverflow) {
Owen Andersond672ecb2009-07-03 00:17:18 +00006766 ConstantInt* DivNeg =
Owen Andersonbaf3c402009-07-29 18:55:55 +00006767 cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
Chris Lattner4de84762010-01-04 07:02:48 +00006768 LoOverflow = AddWithOverflow(LoBound, HiBound, DivNeg, true) ? -1 : 0;
Chris Lattnera6321b42008-10-11 22:55:00 +00006769 }
Chris Lattner562ef782007-06-20 23:46:26 +00006770 }
Dan Gohman76491272008-02-13 22:09:18 +00006771 } else if (DivRHS->getValue().isNegative()) { // Divisor is < 0.
Chris Lattner562ef782007-06-20 23:46:26 +00006772 if (CmpRHSV == 0) { // (X / neg) op 0
Chris Lattner1dbfd482007-06-21 18:11:19 +00006773 // e.g. X/-5 op 0 --> [-4, 5)
Dan Gohman186a6362009-08-12 16:04:34 +00006774 LoBound = AddOne(DivRHS);
Owen Andersonbaf3c402009-07-29 18:55:55 +00006775 HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
Chris Lattner1dbfd482007-06-21 18:11:19 +00006776 if (HiBound == DivRHS) { // -INTMIN = INTMIN
6777 HiOverflow = 1; // [INTMIN+1, overflow)
6778 HiBound = 0; // e.g. X/INTMIN = 0 --> X > INTMIN
6779 }
Dan Gohman76491272008-02-13 22:09:18 +00006780 } else if (CmpRHSV.isStrictlyPositive()) { // (X / neg) op pos
Chris Lattner1dbfd482007-06-21 18:11:19 +00006781 // e.g. X/-5 op 3 --> [-19, -14)
Dan Gohman186a6362009-08-12 16:04:34 +00006782 HiBound = AddOne(Prod);
Chris Lattner1dbfd482007-06-21 18:11:19 +00006783 HiOverflow = LoOverflow = ProdOV ? -1 : 0;
Chris Lattner562ef782007-06-20 23:46:26 +00006784 if (!LoOverflow)
Chris Lattner4de84762010-01-04 07:02:48 +00006785 LoOverflow = AddWithOverflow(LoBound, HiBound, DivRHS, true) ? -1 : 0;
Chris Lattner562ef782007-06-20 23:46:26 +00006786 } else { // (X / neg) op neg
Chris Lattnera6321b42008-10-11 22:55:00 +00006787 LoBound = Prod; // e.g. X/-5 op -3 --> [15, 20)
6788 LoOverflow = HiOverflow = ProdOV;
Dan Gohman7f85fbd2008-09-11 00:25:00 +00006789 if (!HiOverflow)
Chris Lattner4de84762010-01-04 07:02:48 +00006790 HiOverflow = SubWithOverflow(HiBound, Prod, DivRHS, true);
Chris Lattner562ef782007-06-20 23:46:26 +00006791 }
6792
Chris Lattner1dbfd482007-06-21 18:11:19 +00006793 // Dividing by a negative swaps the condition. LT <-> GT
6794 Pred = ICmpInst::getSwappedPredicate(Pred);
Chris Lattner562ef782007-06-20 23:46:26 +00006795 }
6796
6797 Value *X = DivI->getOperand(0);
Chris Lattner1dbfd482007-06-21 18:11:19 +00006798 switch (Pred) {
Torok Edwinc23197a2009-07-14 16:55:14 +00006799 default: llvm_unreachable("Unhandled icmp opcode!");
Chris Lattner562ef782007-06-20 23:46:26 +00006800 case ICmpInst::ICMP_EQ:
6801 if (LoOverflow && HiOverflow)
Chris Lattner4de84762010-01-04 07:02:48 +00006802 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(ICI.getContext()));
Chris Lattner562ef782007-06-20 23:46:26 +00006803 else if (HiOverflow)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006804 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
Chris Lattner562ef782007-06-20 23:46:26 +00006805 ICmpInst::ICMP_UGE, X, LoBound);
6806 else if (LoOverflow)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006807 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
Chris Lattner562ef782007-06-20 23:46:26 +00006808 ICmpInst::ICMP_ULT, X, HiBound);
6809 else
Chris Lattner1dbfd482007-06-21 18:11:19 +00006810 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, true, ICI);
Chris Lattner562ef782007-06-20 23:46:26 +00006811 case ICmpInst::ICMP_NE:
6812 if (LoOverflow && HiOverflow)
Chris Lattner4de84762010-01-04 07:02:48 +00006813 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(ICI.getContext()));
Chris Lattner562ef782007-06-20 23:46:26 +00006814 else if (HiOverflow)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006815 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
Chris Lattner562ef782007-06-20 23:46:26 +00006816 ICmpInst::ICMP_ULT, X, LoBound);
6817 else if (LoOverflow)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006818 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
Chris Lattner562ef782007-06-20 23:46:26 +00006819 ICmpInst::ICMP_UGE, X, HiBound);
6820 else
Chris Lattner1dbfd482007-06-21 18:11:19 +00006821 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, false, ICI);
Chris Lattner562ef782007-06-20 23:46:26 +00006822 case ICmpInst::ICMP_ULT:
6823 case ICmpInst::ICMP_SLT:
Chris Lattner1dbfd482007-06-21 18:11:19 +00006824 if (LoOverflow == +1) // Low bound is greater than input range.
Chris Lattner4de84762010-01-04 07:02:48 +00006825 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(ICI.getContext()));
Chris Lattner1dbfd482007-06-21 18:11:19 +00006826 if (LoOverflow == -1) // Low bound is less than input range.
Chris Lattner4de84762010-01-04 07:02:48 +00006827 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(ICI.getContext()));
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006828 return new ICmpInst(Pred, X, LoBound);
Chris Lattner562ef782007-06-20 23:46:26 +00006829 case ICmpInst::ICMP_UGT:
6830 case ICmpInst::ICMP_SGT:
Chris Lattner1dbfd482007-06-21 18:11:19 +00006831 if (HiOverflow == +1) // High bound greater than input range.
Chris Lattner4de84762010-01-04 07:02:48 +00006832 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(ICI.getContext()));
Chris Lattner1dbfd482007-06-21 18:11:19 +00006833 else if (HiOverflow == -1) // High bound less than input range.
Chris Lattner4de84762010-01-04 07:02:48 +00006834 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(ICI.getContext()));
Chris Lattner1dbfd482007-06-21 18:11:19 +00006835 if (Pred == ICmpInst::ICMP_UGT)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006836 return new ICmpInst(ICmpInst::ICMP_UGE, X, HiBound);
Chris Lattner562ef782007-06-20 23:46:26 +00006837 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006838 return new ICmpInst(ICmpInst::ICMP_SGE, X, HiBound);
Chris Lattner562ef782007-06-20 23:46:26 +00006839 }
6840}
6841
6842
Chris Lattner01deb9d2007-04-03 17:43:25 +00006843/// visitICmpInstWithInstAndIntCst - Handle "icmp (instr, intcst)".
6844///
6845Instruction *InstCombiner::visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
6846 Instruction *LHSI,
6847 ConstantInt *RHS) {
6848 const APInt &RHSV = RHS->getValue();
6849
6850 switch (LHSI->getOpcode()) {
Chris Lattnera80d6682009-01-09 07:47:06 +00006851 case Instruction::Trunc:
6852 if (ICI.isEquality() && LHSI->hasOneUse()) {
6853 // Simplify icmp eq (trunc x to i8), 42 -> icmp eq x, 42|highbits if all
6854 // of the high bits truncated out of x are known.
6855 unsigned DstBits = LHSI->getType()->getPrimitiveSizeInBits(),
6856 SrcBits = LHSI->getOperand(0)->getType()->getPrimitiveSizeInBits();
6857 APInt Mask(APInt::getHighBitsSet(SrcBits, SrcBits-DstBits));
6858 APInt KnownZero(SrcBits, 0), KnownOne(SrcBits, 0);
6859 ComputeMaskedBits(LHSI->getOperand(0), Mask, KnownZero, KnownOne);
6860
6861 // If all the high bits are known, we can do this xform.
6862 if ((KnownZero|KnownOne).countLeadingOnes() >= SrcBits-DstBits) {
6863 // Pull in the high bits from known-ones set.
6864 APInt NewRHS(RHS->getValue());
6865 NewRHS.zext(SrcBits);
6866 NewRHS |= KnownOne;
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006867 return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
Chris Lattner4de84762010-01-04 07:02:48 +00006868 ConstantInt::get(ICI.getContext(), NewRHS));
Chris Lattnera80d6682009-01-09 07:47:06 +00006869 }
6870 }
6871 break;
6872
Duncan Sands0091bf22007-04-04 06:42:45 +00006873 case Instruction::Xor: // (icmp pred (xor X, XorCST), CI)
Chris Lattner01deb9d2007-04-03 17:43:25 +00006874 if (ConstantInt *XorCST = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
6875 // If this is a comparison that tests the signbit (X < 0) or (x > -1),
6876 // fold the xor.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00006877 if ((ICI.getPredicate() == ICmpInst::ICMP_SLT && RHSV == 0) ||
6878 (ICI.getPredicate() == ICmpInst::ICMP_SGT && RHSV.isAllOnesValue())) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00006879 Value *CompareVal = LHSI->getOperand(0);
6880
6881 // If the sign bit of the XorCST is not set, there is no change to
6882 // the operation, just stop using the Xor.
6883 if (!XorCST->getValue().isNegative()) {
6884 ICI.setOperand(0, CompareVal);
Chris Lattner7a1e9242009-08-30 06:13:40 +00006885 Worklist.Add(LHSI);
Chris Lattner01deb9d2007-04-03 17:43:25 +00006886 return &ICI;
6887 }
6888
6889 // Was the old condition true if the operand is positive?
6890 bool isTrueIfPositive = ICI.getPredicate() == ICmpInst::ICMP_SGT;
6891
6892 // If so, the new one isn't.
6893 isTrueIfPositive ^= true;
6894
6895 if (isTrueIfPositive)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006896 return new ICmpInst(ICmpInst::ICMP_SGT, CompareVal,
Dan Gohman186a6362009-08-12 16:04:34 +00006897 SubOne(RHS));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006898 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006899 return new ICmpInst(ICmpInst::ICMP_SLT, CompareVal,
Dan Gohman186a6362009-08-12 16:04:34 +00006900 AddOne(RHS));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006901 }
Nick Lewycky4333f492009-01-31 21:30:05 +00006902
6903 if (LHSI->hasOneUse()) {
6904 // (icmp u/s (xor A SignBit), C) -> (icmp s/u A, (xor C SignBit))
6905 if (!ICI.isEquality() && XorCST->getValue().isSignBit()) {
6906 const APInt &SignBit = XorCST->getValue();
Nick Lewycky4a134af2009-10-25 05:20:17 +00006907 ICmpInst::Predicate Pred = ICI.isSigned()
Nick Lewycky4333f492009-01-31 21:30:05 +00006908 ? ICI.getUnsignedPredicate()
6909 : ICI.getSignedPredicate();
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006910 return new ICmpInst(Pred, LHSI->getOperand(0),
Chris Lattner4de84762010-01-04 07:02:48 +00006911 ConstantInt::get(ICI.getContext(),
6912 RHSV ^ SignBit));
Nick Lewycky4333f492009-01-31 21:30:05 +00006913 }
6914
6915 // (icmp u/s (xor A ~SignBit), C) -> (icmp s/u (xor C ~SignBit), A)
Chris Lattnerf5db1fb2009-02-02 07:15:30 +00006916 if (!ICI.isEquality() && XorCST->getValue().isMaxSignedValue()) {
Nick Lewycky4333f492009-01-31 21:30:05 +00006917 const APInt &NotSignBit = XorCST->getValue();
Nick Lewycky4a134af2009-10-25 05:20:17 +00006918 ICmpInst::Predicate Pred = ICI.isSigned()
Nick Lewycky4333f492009-01-31 21:30:05 +00006919 ? ICI.getUnsignedPredicate()
6920 : ICI.getSignedPredicate();
6921 Pred = ICI.getSwappedPredicate(Pred);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006922 return new ICmpInst(Pred, LHSI->getOperand(0),
Chris Lattner4de84762010-01-04 07:02:48 +00006923 ConstantInt::get(ICI.getContext(),
6924 RHSV ^ NotSignBit));
Nick Lewycky4333f492009-01-31 21:30:05 +00006925 }
6926 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00006927 }
6928 break;
6929 case Instruction::And: // (icmp pred (and X, AndCST), RHS)
6930 if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
6931 LHSI->getOperand(0)->hasOneUse()) {
6932 ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
6933
6934 // If the LHS is an AND of a truncating cast, we can widen the
6935 // and/compare to be the input width without changing the value
6936 // produced, eliminating a cast.
6937 if (TruncInst *Cast = dyn_cast<TruncInst>(LHSI->getOperand(0))) {
6938 // We can do this transformation if either the AND constant does not
6939 // have its sign bit set or if it is an equality comparison.
6940 // Extending a relational comparison when we're checking the sign
6941 // bit would not work.
6942 if (Cast->hasOneUse() &&
Anton Korobeynikov4aefd6b2008-02-20 12:07:57 +00006943 (ICI.isEquality() ||
6944 (AndCST->getValue().isNonNegative() && RHSV.isNonNegative()))) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00006945 uint32_t BitWidth =
6946 cast<IntegerType>(Cast->getOperand(0)->getType())->getBitWidth();
6947 APInt NewCST = AndCST->getValue();
6948 NewCST.zext(BitWidth);
6949 APInt NewCI = RHSV;
6950 NewCI.zext(BitWidth);
Chris Lattner74381062009-08-30 07:44:24 +00006951 Value *NewAnd =
6952 Builder->CreateAnd(Cast->getOperand(0),
Chris Lattner4de84762010-01-04 07:02:48 +00006953 ConstantInt::get(ICI.getContext(), NewCST),
6954 LHSI->getName());
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006955 return new ICmpInst(ICI.getPredicate(), NewAnd,
Chris Lattner4de84762010-01-04 07:02:48 +00006956 ConstantInt::get(ICI.getContext(), NewCI));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006957 }
6958 }
6959
6960 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
6961 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
6962 // happens a LOT in code produced by the C front-end, for bitfield
6963 // access.
6964 BinaryOperator *Shift = dyn_cast<BinaryOperator>(LHSI->getOperand(0));
6965 if (Shift && !Shift->isShift())
6966 Shift = 0;
6967
6968 ConstantInt *ShAmt;
6969 ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
6970 const Type *Ty = Shift ? Shift->getType() : 0; // Type of the shift.
6971 const Type *AndTy = AndCST->getType(); // Type of the and.
6972
6973 // We can fold this as long as we can't shift unknown bits
6974 // into the mask. This can only happen with signed shift
6975 // rights, as they sign-extend.
6976 if (ShAmt) {
6977 bool CanFold = Shift->isLogicalShift();
6978 if (!CanFold) {
6979 // To test for the bad case of the signed shr, see if any
6980 // of the bits shifted in could be tested after the mask.
6981 uint32_t TyBits = Ty->getPrimitiveSizeInBits();
6982 int ShAmtVal = TyBits - ShAmt->getLimitedValue(TyBits);
6983
6984 uint32_t BitWidth = AndTy->getPrimitiveSizeInBits();
6985 if ((APInt::getHighBitsSet(BitWidth, BitWidth-ShAmtVal) &
6986 AndCST->getValue()) == 0)
6987 CanFold = true;
6988 }
6989
6990 if (CanFold) {
6991 Constant *NewCst;
6992 if (Shift->getOpcode() == Instruction::Shl)
Owen Andersonbaf3c402009-07-29 18:55:55 +00006993 NewCst = ConstantExpr::getLShr(RHS, ShAmt);
Chris Lattner01deb9d2007-04-03 17:43:25 +00006994 else
Owen Andersonbaf3c402009-07-29 18:55:55 +00006995 NewCst = ConstantExpr::getShl(RHS, ShAmt);
Chris Lattner01deb9d2007-04-03 17:43:25 +00006996
6997 // Check to see if we are shifting out any of the bits being
6998 // compared.
Owen Andersonbaf3c402009-07-29 18:55:55 +00006999 if (ConstantExpr::get(Shift->getOpcode(),
Owen Andersond672ecb2009-07-03 00:17:18 +00007000 NewCst, ShAmt) != RHS) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00007001 // If we shifted bits out, the fold is not going to work out.
7002 // As a special case, check to see if this means that the
7003 // result is always true or false now.
7004 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
Chris Lattner4de84762010-01-04 07:02:48 +00007005 return ReplaceInstUsesWith(ICI,
7006 ConstantInt::getFalse(ICI.getContext()));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007007 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
Chris Lattner4de84762010-01-04 07:02:48 +00007008 return ReplaceInstUsesWith(ICI,
7009 ConstantInt::getTrue(ICI.getContext()));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007010 } else {
7011 ICI.setOperand(1, NewCst);
7012 Constant *NewAndCST;
7013 if (Shift->getOpcode() == Instruction::Shl)
Owen Andersonbaf3c402009-07-29 18:55:55 +00007014 NewAndCST = ConstantExpr::getLShr(AndCST, ShAmt);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007015 else
Owen Andersonbaf3c402009-07-29 18:55:55 +00007016 NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007017 LHSI->setOperand(1, NewAndCST);
7018 LHSI->setOperand(0, Shift->getOperand(0));
Chris Lattner7a1e9242009-08-30 06:13:40 +00007019 Worklist.Add(Shift); // Shift is dead.
Chris Lattner01deb9d2007-04-03 17:43:25 +00007020 return &ICI;
7021 }
7022 }
7023 }
7024
7025 // Turn ((X >> Y) & C) == 0 into (X & (C << Y)) == 0. The later is
7026 // preferable because it allows the C<<Y expression to be hoisted out
7027 // of a loop if Y is invariant and X is not.
7028 if (Shift && Shift->hasOneUse() && RHSV == 0 &&
Chris Lattnere8e49212009-03-25 00:28:58 +00007029 ICI.isEquality() && !Shift->isArithmeticShift() &&
7030 !isa<Constant>(Shift->getOperand(0))) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00007031 // Compute C << Y.
7032 Value *NS;
7033 if (Shift->getOpcode() == Instruction::LShr) {
Chris Lattner74381062009-08-30 07:44:24 +00007034 NS = Builder->CreateShl(AndCST, Shift->getOperand(1), "tmp");
Chris Lattner01deb9d2007-04-03 17:43:25 +00007035 } else {
7036 // Insert a logical shift.
Chris Lattner74381062009-08-30 07:44:24 +00007037 NS = Builder->CreateLShr(AndCST, Shift->getOperand(1), "tmp");
Chris Lattner01deb9d2007-04-03 17:43:25 +00007038 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00007039
7040 // Compute X & (C << Y).
Chris Lattner74381062009-08-30 07:44:24 +00007041 Value *NewAnd =
7042 Builder->CreateAnd(Shift->getOperand(0), NS, LHSI->getName());
Chris Lattner01deb9d2007-04-03 17:43:25 +00007043
7044 ICI.setOperand(0, NewAnd);
7045 return &ICI;
7046 }
7047 }
Chris Lattnerdf3d63b2010-01-02 22:08:28 +00007048
7049 // Try to optimize things like "A[i]&42 == 0" to index computations.
7050 if (LoadInst *LI = dyn_cast<LoadInst>(LHSI->getOperand(0))) {
7051 if (GetElementPtrInst *GEP =
7052 dyn_cast<GetElementPtrInst>(LI->getOperand(0)))
7053 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0)))
7054 if (GV->isConstant() && GV->hasDefinitiveInitializer() &&
7055 !LI->isVolatile() && isa<ConstantInt>(LHSI->getOperand(1))) {
7056 ConstantInt *C = cast<ConstantInt>(LHSI->getOperand(1));
7057 if (Instruction *Res = FoldCmpLoadFromIndexedGlobal(GEP, GV,ICI, C))
7058 return Res;
Chris Lattnerdf3d63b2010-01-02 22:08:28 +00007059 }
7060 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00007061 break;
Nick Lewycky546d6312010-01-02 15:25:44 +00007062
7063 case Instruction::Or: {
7064 if (!ICI.isEquality() || !RHS->isNullValue() || !LHSI->hasOneUse())
7065 break;
7066 Value *P, *Q;
7067 if (match(LHSI, m_Or(m_PtrToInt(m_Value(P)), m_PtrToInt(m_Value(Q))))) {
7068 // Simplify icmp eq (or (ptrtoint P), (ptrtoint Q)), 0
7069 // -> and (icmp eq P, null), (icmp eq Q, null).
7070
7071 Value *ICIP = Builder->CreateICmp(ICI.getPredicate(), P,
7072 Constant::getNullValue(P->getType()));
7073 Value *ICIQ = Builder->CreateICmp(ICI.getPredicate(), Q,
7074 Constant::getNullValue(Q->getType()));
Nick Lewyckyf994bf02010-01-02 16:14:56 +00007075 Instruction *Op;
7076 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
Nick Lewycky11ed0312010-01-03 00:55:31 +00007077 Op = BinaryOperator::CreateAnd(ICIP, ICIQ);
Nick Lewyckyf994bf02010-01-02 16:14:56 +00007078 else
Nick Lewycky11ed0312010-01-03 00:55:31 +00007079 Op = BinaryOperator::CreateOr(ICIP, ICIQ);
Nick Lewyckyf994bf02010-01-02 16:14:56 +00007080 return Op;
Nick Lewycky546d6312010-01-02 15:25:44 +00007081 }
7082 break;
7083 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00007084
Chris Lattnera0141b92007-07-15 20:42:37 +00007085 case Instruction::Shl: { // (icmp pred (shl X, ShAmt), CI)
7086 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
7087 if (!ShAmt) break;
7088
7089 uint32_t TypeBits = RHSV.getBitWidth();
7090
7091 // Check that the shift amount is in range. If not, don't perform
7092 // undefined shifts. When the shift is visited it will be
7093 // simplified.
7094 if (ShAmt->uge(TypeBits))
7095 break;
7096
7097 if (ICI.isEquality()) {
7098 // If we are comparing against bits always shifted out, the
7099 // comparison cannot succeed.
7100 Constant *Comp =
Owen Andersonbaf3c402009-07-29 18:55:55 +00007101 ConstantExpr::getShl(ConstantExpr::getLShr(RHS, ShAmt),
Owen Andersond672ecb2009-07-03 00:17:18 +00007102 ShAmt);
Chris Lattnera0141b92007-07-15 20:42:37 +00007103 if (Comp != RHS) {// Comparing against a bit that we know is zero.
7104 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
Chris Lattner4de84762010-01-04 07:02:48 +00007105 Constant *Cst =
7106 ConstantInt::get(Type::getInt1Ty(ICI.getContext()), IsICMP_NE);
Chris Lattnera0141b92007-07-15 20:42:37 +00007107 return ReplaceInstUsesWith(ICI, Cst);
7108 }
7109
7110 if (LHSI->hasOneUse()) {
7111 // Otherwise strength reduce the shift into an and.
7112 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
7113 Constant *Mask =
Chris Lattner4de84762010-01-04 07:02:48 +00007114 ConstantInt::get(ICI.getContext(), APInt::getLowBitsSet(TypeBits,
Owen Andersond672ecb2009-07-03 00:17:18 +00007115 TypeBits-ShAmtVal));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007116
Chris Lattner74381062009-08-30 07:44:24 +00007117 Value *And =
7118 Builder->CreateAnd(LHSI->getOperand(0),Mask, LHSI->getName()+".mask");
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007119 return new ICmpInst(ICI.getPredicate(), And,
Chris Lattner4de84762010-01-04 07:02:48 +00007120 ConstantInt::get(ICI.getContext(),
7121 RHSV.lshr(ShAmtVal)));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007122 }
7123 }
Chris Lattnera0141b92007-07-15 20:42:37 +00007124
7125 // Otherwise, if this is a comparison of the sign bit, simplify to and/test.
7126 bool TrueIfSigned = false;
7127 if (LHSI->hasOneUse() &&
7128 isSignBitCheck(ICI.getPredicate(), RHS, TrueIfSigned)) {
7129 // (X << 31) <s 0 --> (X&1) != 0
Chris Lattner4de84762010-01-04 07:02:48 +00007130 Constant *Mask = ConstantInt::get(ICI.getContext(), APInt(TypeBits, 1) <<
Chris Lattnera0141b92007-07-15 20:42:37 +00007131 (TypeBits-ShAmt->getZExtValue()-1));
Chris Lattner74381062009-08-30 07:44:24 +00007132 Value *And =
7133 Builder->CreateAnd(LHSI->getOperand(0), Mask, LHSI->getName()+".mask");
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007134 return new ICmpInst(TrueIfSigned ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ,
Owen Andersona7235ea2009-07-31 20:28:14 +00007135 And, Constant::getNullValue(And->getType()));
Chris Lattnera0141b92007-07-15 20:42:37 +00007136 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00007137 break;
Chris Lattnera0141b92007-07-15 20:42:37 +00007138 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00007139
7140 case Instruction::LShr: // (icmp pred (shr X, ShAmt), CI)
Chris Lattnera0141b92007-07-15 20:42:37 +00007141 case Instruction::AShr: {
Chris Lattner41dc0fc2008-03-21 05:19:58 +00007142 // Only handle equality comparisons of shift-by-constant.
Chris Lattnera0141b92007-07-15 20:42:37 +00007143 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
Chris Lattner41dc0fc2008-03-21 05:19:58 +00007144 if (!ShAmt || !ICI.isEquality()) break;
Chris Lattnera0141b92007-07-15 20:42:37 +00007145
Chris Lattner41dc0fc2008-03-21 05:19:58 +00007146 // Check that the shift amount is in range. If not, don't perform
7147 // undefined shifts. When the shift is visited it will be
7148 // simplified.
7149 uint32_t TypeBits = RHSV.getBitWidth();
7150 if (ShAmt->uge(TypeBits))
7151 break;
7152
7153 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
Chris Lattnera0141b92007-07-15 20:42:37 +00007154
Chris Lattner41dc0fc2008-03-21 05:19:58 +00007155 // If we are comparing against bits always shifted out, the
7156 // comparison cannot succeed.
7157 APInt Comp = RHSV << ShAmtVal;
7158 if (LHSI->getOpcode() == Instruction::LShr)
7159 Comp = Comp.lshr(ShAmtVal);
7160 else
7161 Comp = Comp.ashr(ShAmtVal);
7162
7163 if (Comp != RHSV) { // Comparing against a bit that we know is zero.
7164 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
Chris Lattner4de84762010-01-04 07:02:48 +00007165 Constant *Cst = ConstantInt::get(Type::getInt1Ty(ICI.getContext()),
7166 IsICMP_NE);
Chris Lattner41dc0fc2008-03-21 05:19:58 +00007167 return ReplaceInstUsesWith(ICI, Cst);
7168 }
7169
7170 // Otherwise, check to see if the bits shifted out are known to be zero.
7171 // If so, we can compare against the unshifted value:
7172 // (X & 4) >> 1 == 2 --> (X & 4) == 4.
Evan Chengf30752c2008-04-23 00:38:06 +00007173 if (LHSI->hasOneUse() &&
7174 MaskedValueIsZero(LHSI->getOperand(0),
Chris Lattner41dc0fc2008-03-21 05:19:58 +00007175 APInt::getLowBitsSet(Comp.getBitWidth(), ShAmtVal))) {
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007176 return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
Owen Andersonbaf3c402009-07-29 18:55:55 +00007177 ConstantExpr::getShl(RHS, ShAmt));
Chris Lattner41dc0fc2008-03-21 05:19:58 +00007178 }
Chris Lattnera0141b92007-07-15 20:42:37 +00007179
Evan Chengf30752c2008-04-23 00:38:06 +00007180 if (LHSI->hasOneUse()) {
Chris Lattner41dc0fc2008-03-21 05:19:58 +00007181 // Otherwise strength reduce the shift into an and.
7182 APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal));
Chris Lattner4de84762010-01-04 07:02:48 +00007183 Constant *Mask = ConstantInt::get(ICI.getContext(), Val);
Chris Lattnera0141b92007-07-15 20:42:37 +00007184
Chris Lattner74381062009-08-30 07:44:24 +00007185 Value *And = Builder->CreateAnd(LHSI->getOperand(0),
7186 Mask, LHSI->getName()+".mask");
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007187 return new ICmpInst(ICI.getPredicate(), And,
Owen Andersonbaf3c402009-07-29 18:55:55 +00007188 ConstantExpr::getShl(RHS, ShAmt));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007189 }
7190 break;
Chris Lattnera0141b92007-07-15 20:42:37 +00007191 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00007192
7193 case Instruction::SDiv:
7194 case Instruction::UDiv:
7195 // Fold: icmp pred ([us]div X, C1), C2 -> range test
7196 // Fold this div into the comparison, producing a range check.
7197 // Determine, based on the divide type, what the range is being
7198 // checked. If there is an overflow on the low or high side, remember
7199 // it, otherwise compute the range [low, hi) bounding the new value.
7200 // See: InsertRangeTest above for the kinds of replacements possible.
Chris Lattner562ef782007-06-20 23:46:26 +00007201 if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1)))
7202 if (Instruction *R = FoldICmpDivCst(ICI, cast<BinaryOperator>(LHSI),
7203 DivRHS))
7204 return R;
Chris Lattner01deb9d2007-04-03 17:43:25 +00007205 break;
Nick Lewycky5be29202008-02-03 16:33:09 +00007206
7207 case Instruction::Add:
Chris Lattner2799baf2009-12-21 03:19:28 +00007208 // Fold: icmp pred (add X, C1), C2
Nick Lewycky5be29202008-02-03 16:33:09 +00007209 if (!ICI.isEquality()) {
7210 ConstantInt *LHSC = dyn_cast<ConstantInt>(LHSI->getOperand(1));
7211 if (!LHSC) break;
7212 const APInt &LHSV = LHSC->getValue();
7213
7214 ConstantRange CR = ICI.makeConstantRange(ICI.getPredicate(), RHSV)
7215 .subtract(LHSV);
7216
Nick Lewycky4a134af2009-10-25 05:20:17 +00007217 if (ICI.isSigned()) {
Nick Lewycky5be29202008-02-03 16:33:09 +00007218 if (CR.getLower().isSignBit()) {
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007219 return new ICmpInst(ICmpInst::ICMP_SLT, LHSI->getOperand(0),
Chris Lattner4de84762010-01-04 07:02:48 +00007220 ConstantInt::get(ICI.getContext(),CR.getUpper()));
Nick Lewycky5be29202008-02-03 16:33:09 +00007221 } else if (CR.getUpper().isSignBit()) {
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007222 return new ICmpInst(ICmpInst::ICMP_SGE, LHSI->getOperand(0),
Chris Lattner4de84762010-01-04 07:02:48 +00007223 ConstantInt::get(ICI.getContext(),CR.getLower()));
Nick Lewycky5be29202008-02-03 16:33:09 +00007224 }
7225 } else {
7226 if (CR.getLower().isMinValue()) {
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007227 return new ICmpInst(ICmpInst::ICMP_ULT, LHSI->getOperand(0),
Chris Lattner4de84762010-01-04 07:02:48 +00007228 ConstantInt::get(ICI.getContext(),CR.getUpper()));
Nick Lewycky5be29202008-02-03 16:33:09 +00007229 } else if (CR.getUpper().isMinValue()) {
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007230 return new ICmpInst(ICmpInst::ICMP_UGE, LHSI->getOperand(0),
Chris Lattner4de84762010-01-04 07:02:48 +00007231 ConstantInt::get(ICI.getContext(),CR.getLower()));
Nick Lewycky5be29202008-02-03 16:33:09 +00007232 }
7233 }
7234 }
7235 break;
Chris Lattner01deb9d2007-04-03 17:43:25 +00007236 }
7237
7238 // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
7239 if (ICI.isEquality()) {
7240 bool isICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
7241
7242 // If the first operand is (add|sub|and|or|xor|rem) with a constant, and
7243 // the second operand is a constant, simplify a bit.
7244 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(LHSI)) {
7245 switch (BO->getOpcode()) {
7246 case Instruction::SRem:
7247 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
7248 if (RHSV == 0 && isa<ConstantInt>(BO->getOperand(1)) &&BO->hasOneUse()){
7249 const APInt &V = cast<ConstantInt>(BO->getOperand(1))->getValue();
7250 if (V.sgt(APInt(V.getBitWidth(), 1)) && V.isPowerOf2()) {
Chris Lattner74381062009-08-30 07:44:24 +00007251 Value *NewRem =
7252 Builder->CreateURem(BO->getOperand(0), BO->getOperand(1),
7253 BO->getName());
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007254 return new ICmpInst(ICI.getPredicate(), NewRem,
Owen Andersona7235ea2009-07-31 20:28:14 +00007255 Constant::getNullValue(BO->getType()));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007256 }
7257 }
7258 break;
7259 case Instruction::Add:
7260 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
7261 if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
7262 if (BO->hasOneUse())
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007263 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
Owen Andersonbaf3c402009-07-29 18:55:55 +00007264 ConstantExpr::getSub(RHS, BOp1C));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007265 } else if (RHSV == 0) {
7266 // Replace ((add A, B) != 0) with (A != -B) if A or B is
7267 // efficiently invertible, or if the add has just this one use.
7268 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
7269
Dan Gohman186a6362009-08-12 16:04:34 +00007270 if (Value *NegVal = dyn_castNegVal(BOp1))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007271 return new ICmpInst(ICI.getPredicate(), BOp0, NegVal);
Dan Gohman186a6362009-08-12 16:04:34 +00007272 else if (Value *NegVal = dyn_castNegVal(BOp0))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007273 return new ICmpInst(ICI.getPredicate(), NegVal, BOp1);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007274 else if (BO->hasOneUse()) {
Chris Lattner74381062009-08-30 07:44:24 +00007275 Value *Neg = Builder->CreateNeg(BOp1);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007276 Neg->takeName(BO);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007277 return new ICmpInst(ICI.getPredicate(), BOp0, Neg);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007278 }
7279 }
7280 break;
7281 case Instruction::Xor:
7282 // For the xor case, we can xor two constants together, eliminating
7283 // the explicit xor.
7284 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007285 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
Owen Andersonbaf3c402009-07-29 18:55:55 +00007286 ConstantExpr::getXor(RHS, BOC));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007287
7288 // FALLTHROUGH
7289 case Instruction::Sub:
7290 // Replace (([sub|xor] A, B) != 0) with (A != B)
7291 if (RHSV == 0)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007292 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
Chris Lattner01deb9d2007-04-03 17:43:25 +00007293 BO->getOperand(1));
7294 break;
7295
7296 case Instruction::Or:
7297 // If bits are being or'd in that are not present in the constant we
7298 // are comparing against, then the comparison could never succeed!
7299 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00007300 Constant *NotCI = ConstantExpr::getNot(RHS);
7301 if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
Owen Andersond672ecb2009-07-03 00:17:18 +00007302 return ReplaceInstUsesWith(ICI,
Chris Lattner4de84762010-01-04 07:02:48 +00007303 ConstantInt::get(Type::getInt1Ty(ICI.getContext()),
Owen Andersond672ecb2009-07-03 00:17:18 +00007304 isICMP_NE));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007305 }
7306 break;
7307
7308 case Instruction::And:
7309 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
7310 // If bits are being compared against that are and'd out, then the
7311 // comparison can never succeed!
7312 if ((RHSV & ~BOC->getValue()) != 0)
Owen Andersond672ecb2009-07-03 00:17:18 +00007313 return ReplaceInstUsesWith(ICI,
Chris Lattner4de84762010-01-04 07:02:48 +00007314 ConstantInt::get(Type::getInt1Ty(ICI.getContext()),
Owen Andersond672ecb2009-07-03 00:17:18 +00007315 isICMP_NE));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007316
7317 // If we have ((X & C) == C), turn it into ((X & C) != 0).
7318 if (RHS == BOC && RHSV.isPowerOf2())
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007319 return new ICmpInst(isICMP_NE ? ICmpInst::ICMP_EQ :
Chris Lattner01deb9d2007-04-03 17:43:25 +00007320 ICmpInst::ICMP_NE, LHSI,
Owen Andersona7235ea2009-07-31 20:28:14 +00007321 Constant::getNullValue(RHS->getType()));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007322
7323 // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
Chris Lattner833f25d2008-06-02 01:29:46 +00007324 if (BOC->getValue().isSignBit()) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00007325 Value *X = BO->getOperand(0);
Owen Andersona7235ea2009-07-31 20:28:14 +00007326 Constant *Zero = Constant::getNullValue(X->getType());
Chris Lattner01deb9d2007-04-03 17:43:25 +00007327 ICmpInst::Predicate pred = isICMP_NE ?
7328 ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007329 return new ICmpInst(pred, X, Zero);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007330 }
7331
7332 // ((X & ~7) == 0) --> X < 8
7333 if (RHSV == 0 && isHighOnes(BOC)) {
7334 Value *X = BO->getOperand(0);
Owen Andersonbaf3c402009-07-29 18:55:55 +00007335 Constant *NegX = ConstantExpr::getNeg(BOC);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007336 ICmpInst::Predicate pred = isICMP_NE ?
7337 ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007338 return new ICmpInst(pred, X, NegX);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007339 }
7340 }
7341 default: break;
7342 }
7343 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(LHSI)) {
7344 // Handle icmp {eq|ne} <intrinsic>, intcst.
7345 if (II->getIntrinsicID() == Intrinsic::bswap) {
Chris Lattner7a1e9242009-08-30 06:13:40 +00007346 Worklist.Add(II);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007347 ICI.setOperand(0, II->getOperand(1));
Chris Lattner4de84762010-01-04 07:02:48 +00007348 ICI.setOperand(1, ConstantInt::get(II->getContext(), RHSV.byteSwap()));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007349 return &ICI;
7350 }
7351 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00007352 }
7353 return 0;
7354}
7355
7356/// visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
7357/// We only handle extending casts so far.
7358///
Reid Spencere4d87aa2006-12-23 06:05:41 +00007359Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
7360 const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
Reid Spencer3da59db2006-11-27 01:05:10 +00007361 Value *LHSCIOp = LHSCI->getOperand(0);
7362 const Type *SrcTy = LHSCIOp->getType();
Reid Spencere4d87aa2006-12-23 06:05:41 +00007363 const Type *DestTy = LHSCI->getType();
Chris Lattner484d3cf2005-04-24 06:59:08 +00007364 Value *RHSCIOp;
7365
Chris Lattner8c756c12007-05-05 22:41:33 +00007366 // Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the
7367 // integer type is the same size as the pointer type.
Dan Gohmance9fe9f2009-07-21 23:21:54 +00007368 if (TD && LHSCI->getOpcode() == Instruction::PtrToInt &&
7369 TD->getPointerSizeInBits() ==
Chris Lattner8c756c12007-05-05 22:41:33 +00007370 cast<IntegerType>(DestTy)->getBitWidth()) {
7371 Value *RHSOp = 0;
7372 if (Constant *RHSC = dyn_cast<Constant>(ICI.getOperand(1))) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00007373 RHSOp = ConstantExpr::getIntToPtr(RHSC, SrcTy);
Chris Lattner8c756c12007-05-05 22:41:33 +00007374 } else if (PtrToIntInst *RHSC = dyn_cast<PtrToIntInst>(ICI.getOperand(1))) {
7375 RHSOp = RHSC->getOperand(0);
7376 // If the pointer types don't match, insert a bitcast.
7377 if (LHSCIOp->getType() != RHSOp->getType())
Chris Lattner08142f22009-08-30 19:47:22 +00007378 RHSOp = Builder->CreateBitCast(RHSOp, LHSCIOp->getType());
Chris Lattner8c756c12007-05-05 22:41:33 +00007379 }
7380
7381 if (RHSOp)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007382 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSOp);
Chris Lattner8c756c12007-05-05 22:41:33 +00007383 }
7384
7385 // The code below only handles extension cast instructions, so far.
7386 // Enforce this.
Reid Spencere4d87aa2006-12-23 06:05:41 +00007387 if (LHSCI->getOpcode() != Instruction::ZExt &&
7388 LHSCI->getOpcode() != Instruction::SExt)
Chris Lattnerb352fa52005-01-17 03:20:02 +00007389 return 0;
7390
Reid Spencere4d87aa2006-12-23 06:05:41 +00007391 bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
Nick Lewycky4a134af2009-10-25 05:20:17 +00007392 bool isSignedCmp = ICI.isSigned();
Chris Lattner484d3cf2005-04-24 06:59:08 +00007393
Reid Spencere4d87aa2006-12-23 06:05:41 +00007394 if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
Chris Lattner484d3cf2005-04-24 06:59:08 +00007395 // Not an extension from the same type?
7396 RHSCIOp = CI->getOperand(0);
Reid Spencere4d87aa2006-12-23 06:05:41 +00007397 if (RHSCIOp->getType() != LHSCIOp->getType())
7398 return 0;
Chris Lattnera5c5e772007-01-13 23:11:38 +00007399
Nick Lewycky4189a532008-01-28 03:48:02 +00007400 // If the signedness of the two casts doesn't agree (i.e. one is a sext
Chris Lattnera5c5e772007-01-13 23:11:38 +00007401 // and the other is a zext), then we can't handle this.
7402 if (CI->getOpcode() != LHSCI->getOpcode())
7403 return 0;
7404
Nick Lewycky4189a532008-01-28 03:48:02 +00007405 // Deal with equality cases early.
7406 if (ICI.isEquality())
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007407 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
Nick Lewycky4189a532008-01-28 03:48:02 +00007408
7409 // A signed comparison of sign extended values simplifies into a
7410 // signed comparison.
7411 if (isSignedCmp && isSignedExt)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007412 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
Nick Lewycky4189a532008-01-28 03:48:02 +00007413
7414 // The other three cases all fold into an unsigned comparison.
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007415 return new ICmpInst(ICI.getUnsignedPredicate(), LHSCIOp, RHSCIOp);
Reid Spencer6731d5c2004-11-28 21:31:15 +00007416 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00007417
Reid Spencere4d87aa2006-12-23 06:05:41 +00007418 // If we aren't dealing with a constant on the RHS, exit early
7419 ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
7420 if (!CI)
7421 return 0;
7422
7423 // Compute the constant that would happen if we truncated to SrcTy then
7424 // reextended to DestTy.
Owen Andersonbaf3c402009-07-29 18:55:55 +00007425 Constant *Res1 = ConstantExpr::getTrunc(CI, SrcTy);
7426 Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(),
Owen Andersond672ecb2009-07-03 00:17:18 +00007427 Res1, DestTy);
Reid Spencere4d87aa2006-12-23 06:05:41 +00007428
7429 // If the re-extended constant didn't change...
7430 if (Res2 == CI) {
Eli Friedmanb17cb062009-12-17 22:42:29 +00007431 // Deal with equality cases early.
7432 if (ICI.isEquality())
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007433 return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
Eli Friedmanb17cb062009-12-17 22:42:29 +00007434
7435 // A signed comparison of sign extended values simplifies into a
7436 // signed comparison.
7437 if (isSignedExt && isSignedCmp)
7438 return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
7439
7440 // The other three cases all fold into an unsigned comparison.
7441 return new ICmpInst(ICI.getUnsignedPredicate(), LHSCIOp, Res1);
Reid Spencere4d87aa2006-12-23 06:05:41 +00007442 }
7443
7444 // The re-extended constant changed so the constant cannot be represented
7445 // in the shorter type. Consequently, we cannot emit a simple comparison.
7446
7447 // First, handle some easy cases. We know the result cannot be equal at this
7448 // point so handle the ICI.isEquality() cases
7449 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
Chris Lattner4de84762010-01-04 07:02:48 +00007450 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(ICI.getContext()));
Reid Spencere4d87aa2006-12-23 06:05:41 +00007451 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
Chris Lattner4de84762010-01-04 07:02:48 +00007452 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(ICI.getContext()));
Reid Spencere4d87aa2006-12-23 06:05:41 +00007453
7454 // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
7455 // should have been folded away previously and not enter in here.
7456 Value *Result;
7457 if (isSignedCmp) {
7458 // We're performing a signed comparison.
Reid Spencer0460fb32007-03-22 20:36:03 +00007459 if (cast<ConstantInt>(CI)->getValue().isNegative())
Chris Lattner4de84762010-01-04 07:02:48 +00007460 Result = ConstantInt::getFalse(ICI.getContext()); // X < (small) --> false
Reid Spencere4d87aa2006-12-23 06:05:41 +00007461 else
Chris Lattner4de84762010-01-04 07:02:48 +00007462 Result = ConstantInt::getTrue(ICI.getContext()); // X < (large) --> true
Reid Spencere4d87aa2006-12-23 06:05:41 +00007463 } else {
7464 // We're performing an unsigned comparison.
7465 if (isSignedExt) {
7466 // We're performing an unsigned comp with a sign extended value.
7467 // This is true if the input is >= 0. [aka >s -1]
Owen Andersona7235ea2009-07-31 20:28:14 +00007468 Constant *NegOne = Constant::getAllOnesValue(SrcTy);
Chris Lattner74381062009-08-30 07:44:24 +00007469 Result = Builder->CreateICmpSGT(LHSCIOp, NegOne, ICI.getName());
Reid Spencere4d87aa2006-12-23 06:05:41 +00007470 } else {
7471 // Unsigned extend & unsigned compare -> always true.
Chris Lattner4de84762010-01-04 07:02:48 +00007472 Result = ConstantInt::getTrue(ICI.getContext());
Reid Spencere4d87aa2006-12-23 06:05:41 +00007473 }
7474 }
7475
7476 // Finally, return the value computed.
7477 if (ICI.getPredicate() == ICmpInst::ICMP_ULT ||
Chris Lattnerf2991842008-07-11 04:09:09 +00007478 ICI.getPredicate() == ICmpInst::ICMP_SLT)
Reid Spencere4d87aa2006-12-23 06:05:41 +00007479 return ReplaceInstUsesWith(ICI, Result);
Chris Lattnerf2991842008-07-11 04:09:09 +00007480
7481 assert((ICI.getPredicate()==ICmpInst::ICMP_UGT ||
7482 ICI.getPredicate()==ICmpInst::ICMP_SGT) &&
7483 "ICmp should be folded!");
7484 if (Constant *CI = dyn_cast<Constant>(Result))
Owen Andersonbaf3c402009-07-29 18:55:55 +00007485 return ReplaceInstUsesWith(ICI, ConstantExpr::getNot(CI));
Dan Gohman4ae51262009-08-12 16:23:25 +00007486 return BinaryOperator::CreateNot(Result);
Chris Lattner484d3cf2005-04-24 06:59:08 +00007487}
Chris Lattner3f5b8772002-05-06 16:14:14 +00007488
Reid Spencer832254e2007-02-02 02:16:23 +00007489Instruction *InstCombiner::visitShl(BinaryOperator &I) {
7490 return commonShiftTransforms(I);
7491}
7492
7493Instruction *InstCombiner::visitLShr(BinaryOperator &I) {
7494 return commonShiftTransforms(I);
7495}
7496
7497Instruction *InstCombiner::visitAShr(BinaryOperator &I) {
Chris Lattner348f6652007-12-06 01:59:46 +00007498 if (Instruction *R = commonShiftTransforms(I))
7499 return R;
7500
7501 Value *Op0 = I.getOperand(0);
7502
7503 // ashr int -1, X = -1 (for any arithmetic shift rights of ~0)
7504 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
7505 if (CSI->isAllOnesValue())
7506 return ReplaceInstUsesWith(I, CSI);
Dan Gohman0001e562009-02-24 02:00:40 +00007507
Dan Gohmanc6ac3222009-06-16 19:55:29 +00007508 // See if we can turn a signed shr into an unsigned shr.
7509 if (MaskedValueIsZero(Op0,
7510 APInt::getSignBit(I.getType()->getScalarSizeInBits())))
7511 return BinaryOperator::CreateLShr(Op0, I.getOperand(1));
7512
7513 // Arithmetic shifting an all-sign-bit value is a no-op.
7514 unsigned NumSignBits = ComputeNumSignBits(Op0);
7515 if (NumSignBits == Op0->getType()->getScalarSizeInBits())
7516 return ReplaceInstUsesWith(I, Op0);
Dan Gohman0001e562009-02-24 02:00:40 +00007517
Chris Lattner348f6652007-12-06 01:59:46 +00007518 return 0;
Reid Spencer832254e2007-02-02 02:16:23 +00007519}
7520
7521Instruction *InstCombiner::commonShiftTransforms(BinaryOperator &I) {
7522 assert(I.getOperand(1)->getType() == I.getOperand(0)->getType());
Chris Lattner7e708292002-06-25 16:13:24 +00007523 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00007524
7525 // shl X, 0 == X and shr X, 0 == X
7526 // shl 0, X == 0 and shr 0, X == 0
Owen Andersona7235ea2009-07-31 20:28:14 +00007527 if (Op1 == Constant::getNullValue(Op1->getType()) ||
7528 Op0 == Constant::getNullValue(Op0->getType()))
Chris Lattner233f7dc2002-08-12 21:17:25 +00007529 return ReplaceInstUsesWith(I, Op0);
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00007530
Reid Spencere4d87aa2006-12-23 06:05:41 +00007531 if (isa<UndefValue>(Op0)) {
7532 if (I.getOpcode() == Instruction::AShr) // undef >>s X -> undef
Chris Lattner79a564c2004-10-16 23:28:04 +00007533 return ReplaceInstUsesWith(I, Op0);
Reid Spencere4d87aa2006-12-23 06:05:41 +00007534 else // undef << X -> 0, undef >>u X -> 0
Owen Andersona7235ea2009-07-31 20:28:14 +00007535 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00007536 }
7537 if (isa<UndefValue>(Op1)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00007538 if (I.getOpcode() == Instruction::AShr) // X >>s undef -> X
7539 return ReplaceInstUsesWith(I, Op0);
7540 else // X << undef, X >>u undef -> 0
Owen Andersona7235ea2009-07-31 20:28:14 +00007541 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00007542 }
7543
Dan Gohman9004c8a2009-05-21 02:28:33 +00007544 // See if we can fold away this shift.
Dan Gohman6de29f82009-06-15 22:12:54 +00007545 if (SimplifyDemandedInstructionBits(I))
Dan Gohman9004c8a2009-05-21 02:28:33 +00007546 return &I;
7547
Chris Lattner2eefe512004-04-09 19:05:30 +00007548 // Try to fold constant and into select arguments.
7549 if (isa<Constant>(Op0))
7550 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner6e7ba452005-01-01 16:22:27 +00007551 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00007552 return R;
7553
Reid Spencerb83eb642006-10-20 07:07:24 +00007554 if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
Reid Spencerc5b206b2006-12-31 05:48:39 +00007555 if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
7556 return Res;
Chris Lattner4d5542c2006-01-06 07:12:35 +00007557 return 0;
7558}
7559
Reid Spencerb83eb642006-10-20 07:07:24 +00007560Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
Reid Spencer832254e2007-02-02 02:16:23 +00007561 BinaryOperator &I) {
Chris Lattner4598c942009-01-31 08:24:16 +00007562 bool isLeftShift = I.getOpcode() == Instruction::Shl;
Chris Lattner4d5542c2006-01-06 07:12:35 +00007563
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00007564 // See if we can simplify any instructions used by the instruction whose sole
7565 // purpose is to compute bits we don't care about.
Dan Gohmanc6ac3222009-06-16 19:55:29 +00007566 uint32_t TypeBits = Op0->getType()->getScalarSizeInBits();
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00007567
Dan Gohmana119de82009-06-14 23:30:43 +00007568 // shl i32 X, 32 = 0 and srl i8 Y, 9 = 0, ... just don't eliminate
7569 // a signed shift.
Chris Lattner4d5542c2006-01-06 07:12:35 +00007570 //
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00007571 if (Op1->uge(TypeBits)) {
Chris Lattner0737c242007-02-02 05:29:55 +00007572 if (I.getOpcode() != Instruction::AShr)
Owen Andersona7235ea2009-07-31 20:28:14 +00007573 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
Chris Lattner4d5542c2006-01-06 07:12:35 +00007574 else {
Owen Andersoneed707b2009-07-24 23:12:02 +00007575 I.setOperand(1, ConstantInt::get(I.getType(), TypeBits-1));
Chris Lattner4d5542c2006-01-06 07:12:35 +00007576 return &I;
Chris Lattner8adac752004-02-23 20:30:06 +00007577 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007578 }
7579
7580 // ((X*C1) << C2) == (X * (C1 << C2))
7581 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
7582 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
7583 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007584 return BinaryOperator::CreateMul(BO->getOperand(0),
Owen Andersonbaf3c402009-07-29 18:55:55 +00007585 ConstantExpr::getShl(BOOp, Op1));
Chris Lattner4d5542c2006-01-06 07:12:35 +00007586
7587 // Try to fold constant and into select arguments.
7588 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
7589 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
7590 return R;
7591 if (isa<PHINode>(Op0))
7592 if (Instruction *NV = FoldOpIntoPhi(I))
7593 return NV;
7594
Chris Lattner8999dd32007-12-22 09:07:47 +00007595 // Fold shift2(trunc(shift1(x,c1)), c2) -> trunc(shift2(shift1(x,c1),c2))
7596 if (TruncInst *TI = dyn_cast<TruncInst>(Op0)) {
7597 Instruction *TrOp = dyn_cast<Instruction>(TI->getOperand(0));
7598 // If 'shift2' is an ashr, we would have to get the sign bit into a funny
7599 // place. Don't try to do this transformation in this case. Also, we
7600 // require that the input operand is a shift-by-constant so that we have
7601 // confidence that the shifts will get folded together. We could do this
7602 // xform in more cases, but it is unlikely to be profitable.
7603 if (TrOp && I.isLogicalShift() && TrOp->isShift() &&
7604 isa<ConstantInt>(TrOp->getOperand(1))) {
7605 // Okay, we'll do this xform. Make the shift of shift.
Owen Andersonbaf3c402009-07-29 18:55:55 +00007606 Constant *ShAmt = ConstantExpr::getZExt(Op1, TrOp->getType());
Chris Lattner74381062009-08-30 07:44:24 +00007607 // (shift2 (shift1 & 0x00FF), c2)
7608 Value *NSh = Builder->CreateBinOp(I.getOpcode(), TrOp, ShAmt,I.getName());
Chris Lattner8999dd32007-12-22 09:07:47 +00007609
7610 // For logical shifts, the truncation has the effect of making the high
7611 // part of the register be zeros. Emulate this by inserting an AND to
7612 // clear the top bits as needed. This 'and' will usually be zapped by
7613 // other xforms later if dead.
Dan Gohmanc6ac3222009-06-16 19:55:29 +00007614 unsigned SrcSize = TrOp->getType()->getScalarSizeInBits();
7615 unsigned DstSize = TI->getType()->getScalarSizeInBits();
Chris Lattner8999dd32007-12-22 09:07:47 +00007616 APInt MaskV(APInt::getLowBitsSet(SrcSize, DstSize));
7617
7618 // The mask we constructed says what the trunc would do if occurring
7619 // between the shifts. We want to know the effect *after* the second
7620 // shift. We know that it is a logical shift by a constant, so adjust the
7621 // mask as appropriate.
7622 if (I.getOpcode() == Instruction::Shl)
7623 MaskV <<= Op1->getZExtValue();
7624 else {
7625 assert(I.getOpcode() == Instruction::LShr && "Unknown logical shift");
7626 MaskV = MaskV.lshr(Op1->getZExtValue());
7627 }
7628
Chris Lattner74381062009-08-30 07:44:24 +00007629 // shift1 & 0x00FF
Chris Lattner4de84762010-01-04 07:02:48 +00007630 Value *And = Builder->CreateAnd(NSh,
7631 ConstantInt::get(I.getContext(), MaskV),
Chris Lattner74381062009-08-30 07:44:24 +00007632 TI->getName());
Chris Lattner8999dd32007-12-22 09:07:47 +00007633
7634 // Return the value truncated to the interesting size.
7635 return new TruncInst(And, I.getType());
7636 }
7637 }
7638
Chris Lattner4d5542c2006-01-06 07:12:35 +00007639 if (Op0->hasOneUse()) {
Chris Lattner4d5542c2006-01-06 07:12:35 +00007640 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
7641 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
7642 Value *V1, *V2;
7643 ConstantInt *CC;
7644 switch (Op0BO->getOpcode()) {
Chris Lattner11021cb2005-09-18 05:12:10 +00007645 default: break;
7646 case Instruction::Add:
7647 case Instruction::And:
7648 case Instruction::Or:
Reid Spencera07cb7d2007-02-02 14:41:37 +00007649 case Instruction::Xor: {
Chris Lattner11021cb2005-09-18 05:12:10 +00007650 // These operators commute.
7651 // Turn (Y + (X >> C)) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00007652 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00007653 match(Op0BO->getOperand(1), m_Shr(m_Value(V1),
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007654 m_Specific(Op1)))) {
7655 Value *YS = // (Y << C)
7656 Builder->CreateShl(Op0BO->getOperand(0), Op1, Op0BO->getName());
7657 // (X + (Y << C))
7658 Value *X = Builder->CreateBinOp(Op0BO->getOpcode(), YS, V1,
7659 Op0BO->getOperand(1)->getName());
Zhou Sheng302748d2007-03-30 17:20:39 +00007660 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
Chris Lattner4de84762010-01-04 07:02:48 +00007661 return BinaryOperator::CreateAnd(X, ConstantInt::get(I.getContext(),
Zhou Sheng90b96812007-03-30 05:45:18 +00007662 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
Chris Lattner150f12a2005-09-18 06:30:59 +00007663 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007664
Chris Lattner150f12a2005-09-18 06:30:59 +00007665 // Turn (Y + ((X >> C) & CC)) << C -> ((X & (CC << C)) + (Y << C))
Reid Spencera07cb7d2007-02-02 14:41:37 +00007666 Value *Op0BOOp1 = Op0BO->getOperand(1);
Chris Lattner3c698492007-03-05 00:11:19 +00007667 if (isLeftShift && Op0BOOp1->hasOneUse() &&
Reid Spencera07cb7d2007-02-02 14:41:37 +00007668 match(Op0BOOp1,
Chris Lattnercb504b92008-11-16 05:38:51 +00007669 m_And(m_Shr(m_Value(V1), m_Specific(Op1)),
Dan Gohman4ae51262009-08-12 16:23:25 +00007670 m_ConstantInt(CC))) &&
Chris Lattnercb504b92008-11-16 05:38:51 +00007671 cast<BinaryOperator>(Op0BOOp1)->getOperand(0)->hasOneUse()) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007672 Value *YS = // (Y << C)
7673 Builder->CreateShl(Op0BO->getOperand(0), Op1,
7674 Op0BO->getName());
7675 // X & (CC << C)
7676 Value *XM = Builder->CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
7677 V1->getName()+".mask");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007678 return BinaryOperator::Create(Op0BO->getOpcode(), YS, XM);
Chris Lattner150f12a2005-09-18 06:30:59 +00007679 }
Reid Spencera07cb7d2007-02-02 14:41:37 +00007680 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007681
Reid Spencera07cb7d2007-02-02 14:41:37 +00007682 // FALL THROUGH.
7683 case Instruction::Sub: {
Chris Lattner11021cb2005-09-18 05:12:10 +00007684 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00007685 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00007686 match(Op0BO->getOperand(0), m_Shr(m_Value(V1),
Dan Gohman4ae51262009-08-12 16:23:25 +00007687 m_Specific(Op1)))) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007688 Value *YS = // (Y << C)
7689 Builder->CreateShl(Op0BO->getOperand(1), Op1, Op0BO->getName());
7690 // (X + (Y << C))
7691 Value *X = Builder->CreateBinOp(Op0BO->getOpcode(), V1, YS,
7692 Op0BO->getOperand(0)->getName());
Zhou Sheng302748d2007-03-30 17:20:39 +00007693 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
Chris Lattner4de84762010-01-04 07:02:48 +00007694 return BinaryOperator::CreateAnd(X, ConstantInt::get(I.getContext(),
Zhou Sheng90b96812007-03-30 05:45:18 +00007695 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
Chris Lattner150f12a2005-09-18 06:30:59 +00007696 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007697
Chris Lattner13d4ab42006-05-31 21:14:00 +00007698 // Turn (((X >> C)&CC) + Y) << C -> (X + (Y << C)) & (CC << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00007699 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
7700 match(Op0BO->getOperand(0),
7701 m_And(m_Shr(m_Value(V1), m_Value(V2)),
Dan Gohman4ae51262009-08-12 16:23:25 +00007702 m_ConstantInt(CC))) && V2 == Op1 &&
Chris Lattner9a4cacb2006-02-09 07:41:14 +00007703 cast<BinaryOperator>(Op0BO->getOperand(0))
7704 ->getOperand(0)->hasOneUse()) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007705 Value *YS = // (Y << C)
7706 Builder->CreateShl(Op0BO->getOperand(1), Op1, Op0BO->getName());
7707 // X & (CC << C)
7708 Value *XM = Builder->CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
7709 V1->getName()+".mask");
Chris Lattner150f12a2005-09-18 06:30:59 +00007710
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007711 return BinaryOperator::Create(Op0BO->getOpcode(), XM, YS);
Chris Lattner150f12a2005-09-18 06:30:59 +00007712 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007713
Chris Lattner11021cb2005-09-18 05:12:10 +00007714 break;
Reid Spencera07cb7d2007-02-02 14:41:37 +00007715 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007716 }
7717
7718
7719 // If the operand is an bitwise operator with a constant RHS, and the
7720 // shift is the only use, we can pull it out of the shift.
7721 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
7722 bool isValid = true; // Valid only for And, Or, Xor
7723 bool highBitSet = false; // Transform if high bit of constant set?
7724
7725 switch (Op0BO->getOpcode()) {
Chris Lattnerdf17af12003-08-12 21:53:41 +00007726 default: isValid = false; break; // Do not perform transform!
Chris Lattner1f7e1602004-10-08 03:46:20 +00007727 case Instruction::Add:
7728 isValid = isLeftShift;
7729 break;
Chris Lattnerdf17af12003-08-12 21:53:41 +00007730 case Instruction::Or:
7731 case Instruction::Xor:
7732 highBitSet = false;
7733 break;
7734 case Instruction::And:
7735 highBitSet = true;
7736 break;
Chris Lattner4d5542c2006-01-06 07:12:35 +00007737 }
7738
7739 // If this is a signed shift right, and the high bit is modified
7740 // by the logical operation, do not perform the transformation.
7741 // The highBitSet boolean indicates the value of the high bit of
7742 // the constant which would cause it to be modified for this
7743 // operation.
7744 //
Chris Lattnerc95ba442007-12-06 06:25:04 +00007745 if (isValid && I.getOpcode() == Instruction::AShr)
Zhou Shenge9e03f62007-03-28 15:02:20 +00007746 isValid = Op0C->getValue()[TypeBits-1] == highBitSet;
Chris Lattner4d5542c2006-01-06 07:12:35 +00007747
7748 if (isValid) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00007749 Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
Chris Lattner4d5542c2006-01-06 07:12:35 +00007750
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007751 Value *NewShift =
7752 Builder->CreateBinOp(I.getOpcode(), Op0BO->getOperand(0), Op1);
Chris Lattner6934a042007-02-11 01:23:03 +00007753 NewShift->takeName(Op0BO);
Chris Lattner4d5542c2006-01-06 07:12:35 +00007754
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007755 return BinaryOperator::Create(Op0BO->getOpcode(), NewShift,
Chris Lattner4d5542c2006-01-06 07:12:35 +00007756 NewRHS);
7757 }
7758 }
7759 }
7760 }
7761
Chris Lattnerad0124c2006-01-06 07:52:12 +00007762 // Find out if this is a shift of a shift by a constant.
Reid Spencer832254e2007-02-02 02:16:23 +00007763 BinaryOperator *ShiftOp = dyn_cast<BinaryOperator>(Op0);
7764 if (ShiftOp && !ShiftOp->isShift())
7765 ShiftOp = 0;
Chris Lattnerad0124c2006-01-06 07:52:12 +00007766
Reid Spencerb83eb642006-10-20 07:07:24 +00007767 if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
Reid Spencerb83eb642006-10-20 07:07:24 +00007768 ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00007769 uint32_t ShiftAmt1 = ShiftAmt1C->getLimitedValue(TypeBits);
7770 uint32_t ShiftAmt2 = Op1->getLimitedValue(TypeBits);
Chris Lattnerb87056f2007-02-05 00:57:54 +00007771 assert(ShiftAmt2 != 0 && "Should have been simplified earlier");
7772 if (ShiftAmt1 == 0) return 0; // Will be simplified in the future.
7773 Value *X = ShiftOp->getOperand(0);
Chris Lattnerad0124c2006-01-06 07:52:12 +00007774
Zhou Sheng4351c642007-04-02 08:20:41 +00007775 uint32_t AmtSum = ShiftAmt1+ShiftAmt2; // Fold into one big shift.
Chris Lattnerb87056f2007-02-05 00:57:54 +00007776
7777 const IntegerType *Ty = cast<IntegerType>(I.getType());
7778
7779 // Check for (X << c1) << c2 and (X >> c1) >> c2
Chris Lattner7f3da2d2007-02-03 23:28:07 +00007780 if (I.getOpcode() == ShiftOp->getOpcode()) {
Chris Lattner344c7c52009-03-20 22:41:15 +00007781 // If this is oversized composite shift, then unsigned shifts get 0, ashr
7782 // saturates.
7783 if (AmtSum >= TypeBits) {
7784 if (I.getOpcode() != Instruction::AShr)
Owen Andersona7235ea2009-07-31 20:28:14 +00007785 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner344c7c52009-03-20 22:41:15 +00007786 AmtSum = TypeBits-1; // Saturate to 31 for i32 ashr.
7787 }
7788
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007789 return BinaryOperator::Create(I.getOpcode(), X,
Owen Andersoneed707b2009-07-24 23:12:02 +00007790 ConstantInt::get(Ty, AmtSum));
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007791 }
7792
7793 if (ShiftOp->getOpcode() == Instruction::LShr &&
7794 I.getOpcode() == Instruction::AShr) {
Chris Lattner344c7c52009-03-20 22:41:15 +00007795 if (AmtSum >= TypeBits)
Owen Andersona7235ea2009-07-31 20:28:14 +00007796 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner344c7c52009-03-20 22:41:15 +00007797
Chris Lattnerb87056f2007-02-05 00:57:54 +00007798 // ((X >>u C1) >>s C2) -> (X >>u (C1+C2)) since C1 != 0.
Owen Andersoneed707b2009-07-24 23:12:02 +00007799 return BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, AmtSum));
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007800 }
7801
7802 if (ShiftOp->getOpcode() == Instruction::AShr &&
7803 I.getOpcode() == Instruction::LShr) {
Chris Lattnerb87056f2007-02-05 00:57:54 +00007804 // ((X >>s C1) >>u C2) -> ((X >>s (C1+C2)) & mask) since C1 != 0.
Chris Lattner344c7c52009-03-20 22:41:15 +00007805 if (AmtSum >= TypeBits)
7806 AmtSum = TypeBits-1;
7807
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007808 Value *Shift = Builder->CreateAShr(X, ConstantInt::get(Ty, AmtSum));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007809
Zhou Shenge9e03f62007-03-28 15:02:20 +00007810 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Chris Lattner4de84762010-01-04 07:02:48 +00007811 return BinaryOperator::CreateAnd(Shift,
7812 ConstantInt::get(I.getContext(), Mask));
Chris Lattnerad0124c2006-01-06 07:52:12 +00007813 }
7814
Chris Lattnerb87056f2007-02-05 00:57:54 +00007815 // Okay, if we get here, one shift must be left, and the other shift must be
7816 // right. See if the amounts are equal.
7817 if (ShiftAmt1 == ShiftAmt2) {
7818 // If we have ((X >>? C) << C), turn this into X & (-1 << C).
7819 if (I.getOpcode() == Instruction::Shl) {
Reid Spencer55702aa2007-03-25 21:11:44 +00007820 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt1));
Chris Lattner4de84762010-01-04 07:02:48 +00007821 return BinaryOperator::CreateAnd(X,
7822 ConstantInt::get(I.getContext(),Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007823 }
7824 // If we have ((X << C) >>u C), turn this into X & (-1 >>u C).
7825 if (I.getOpcode() == Instruction::LShr) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00007826 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt1));
Chris Lattner4de84762010-01-04 07:02:48 +00007827 return BinaryOperator::CreateAnd(X,
7828 ConstantInt::get(I.getContext(), Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007829 }
7830 // We can simplify ((X << C) >>s C) into a trunc + sext.
7831 // NOTE: we could do this for any C, but that would make 'unusual' integer
7832 // types. For now, just stick to ones well-supported by the code
7833 // generators.
7834 const Type *SExtType = 0;
7835 switch (Ty->getBitWidth() - ShiftAmt1) {
Zhou Shenge9e03f62007-03-28 15:02:20 +00007836 case 1 :
7837 case 8 :
7838 case 16 :
7839 case 32 :
7840 case 64 :
7841 case 128:
Chris Lattner4de84762010-01-04 07:02:48 +00007842 SExtType = IntegerType::get(I.getContext(),
7843 Ty->getBitWidth() - ShiftAmt1);
Zhou Shenge9e03f62007-03-28 15:02:20 +00007844 break;
Chris Lattnerb87056f2007-02-05 00:57:54 +00007845 default: break;
7846 }
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007847 if (SExtType)
7848 return new SExtInst(Builder->CreateTrunc(X, SExtType, "sext"), Ty);
Chris Lattnerb87056f2007-02-05 00:57:54 +00007849 // Otherwise, we can't handle it yet.
7850 } else if (ShiftAmt1 < ShiftAmt2) {
Zhou Sheng4351c642007-04-02 08:20:41 +00007851 uint32_t ShiftDiff = ShiftAmt2-ShiftAmt1;
Chris Lattnerad0124c2006-01-06 07:52:12 +00007852
Chris Lattnerb0b991a2007-02-05 05:57:49 +00007853 // (X >>? C1) << C2 --> X << (C2-C1) & (-1 << C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00007854 if (I.getOpcode() == Instruction::Shl) {
7855 assert(ShiftOp->getOpcode() == Instruction::LShr ||
7856 ShiftOp->getOpcode() == Instruction::AShr);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007857 Value *Shift = Builder->CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
Chris Lattnere8d56c52006-01-07 01:32:28 +00007858
Reid Spencer55702aa2007-03-25 21:11:44 +00007859 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersoneed707b2009-07-24 23:12:02 +00007860 return BinaryOperator::CreateAnd(Shift,
Chris Lattner4de84762010-01-04 07:02:48 +00007861 ConstantInt::get(I.getContext(),Mask));
Chris Lattnerad0124c2006-01-06 07:52:12 +00007862 }
Chris Lattnerb87056f2007-02-05 00:57:54 +00007863
Chris Lattnerb0b991a2007-02-05 05:57:49 +00007864 // (X << C1) >>u C2 --> X >>u (C2-C1) & (-1 >> C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00007865 if (I.getOpcode() == Instruction::LShr) {
7866 assert(ShiftOp->getOpcode() == Instruction::Shl);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007867 Value *Shift = Builder->CreateLShr(X, ConstantInt::get(Ty, ShiftDiff));
Chris Lattnerad0124c2006-01-06 07:52:12 +00007868
Reid Spencerd5e30f02007-03-26 17:18:58 +00007869 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersoneed707b2009-07-24 23:12:02 +00007870 return BinaryOperator::CreateAnd(Shift,
Chris Lattner4de84762010-01-04 07:02:48 +00007871 ConstantInt::get(I.getContext(),Mask));
Chris Lattner11021cb2005-09-18 05:12:10 +00007872 }
Chris Lattnerb87056f2007-02-05 00:57:54 +00007873
7874 // We can't handle (X << C1) >>s C2, it shifts arbitrary bits in.
7875 } else {
7876 assert(ShiftAmt2 < ShiftAmt1);
Zhou Sheng4351c642007-04-02 08:20:41 +00007877 uint32_t ShiftDiff = ShiftAmt1-ShiftAmt2;
Chris Lattnerb87056f2007-02-05 00:57:54 +00007878
Chris Lattnerb0b991a2007-02-05 05:57:49 +00007879 // (X >>? C1) << C2 --> X >>? (C1-C2) & (-1 << C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00007880 if (I.getOpcode() == Instruction::Shl) {
7881 assert(ShiftOp->getOpcode() == Instruction::LShr ||
7882 ShiftOp->getOpcode() == Instruction::AShr);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007883 Value *Shift = Builder->CreateBinOp(ShiftOp->getOpcode(), X,
7884 ConstantInt::get(Ty, ShiftDiff));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007885
Reid Spencer55702aa2007-03-25 21:11:44 +00007886 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersoneed707b2009-07-24 23:12:02 +00007887 return BinaryOperator::CreateAnd(Shift,
Chris Lattner4de84762010-01-04 07:02:48 +00007888 ConstantInt::get(I.getContext(),Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007889 }
7890
Chris Lattnerb0b991a2007-02-05 05:57:49 +00007891 // (X << C1) >>u C2 --> X << (C1-C2) & (-1 >> C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00007892 if (I.getOpcode() == Instruction::LShr) {
7893 assert(ShiftOp->getOpcode() == Instruction::Shl);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007894 Value *Shift = Builder->CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007895
Reid Spencer68d27cf2007-03-26 23:45:51 +00007896 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersoneed707b2009-07-24 23:12:02 +00007897 return BinaryOperator::CreateAnd(Shift,
Chris Lattner4de84762010-01-04 07:02:48 +00007898 ConstantInt::get(I.getContext(),Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007899 }
7900
7901 // We can't handle (X << C1) >>a C2, it shifts arbitrary bits in.
Chris Lattner6e7ba452005-01-01 16:22:27 +00007902 }
Chris Lattnerad0124c2006-01-06 07:52:12 +00007903 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00007904 return 0;
7905}
7906
Chris Lattnera1be5662002-05-02 17:06:02 +00007907
Chris Lattnercfd65102005-10-29 04:36:15 +00007908/// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
7909/// expression. If so, decompose it, returning some value X, such that Val is
7910/// X*Scale+Offset.
7911///
7912static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
Chris Lattner4de84762010-01-04 07:02:48 +00007913 int &Offset) {
7914 assert(Val->getType() == Type::getInt32Ty(Val->getContext()) &&
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007915 "Unexpected allocation size type!");
Reid Spencerb83eb642006-10-20 07:07:24 +00007916 if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00007917 Offset = CI->getZExtValue();
Chris Lattner6a94de22007-10-12 05:30:59 +00007918 Scale = 0;
Chris Lattner4de84762010-01-04 07:02:48 +00007919 return ConstantInt::get(Type::getInt32Ty(Val->getContext()), 0);
Chris Lattner6a94de22007-10-12 05:30:59 +00007920 } else if (BinaryOperator *I = dyn_cast<BinaryOperator>(Val)) {
7921 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
7922 if (I->getOpcode() == Instruction::Shl) {
7923 // This is a value scaled by '1 << the shift amt'.
7924 Scale = 1U << RHS->getZExtValue();
7925 Offset = 0;
7926 return I->getOperand(0);
7927 } else if (I->getOpcode() == Instruction::Mul) {
7928 // This value is scaled by 'RHS'.
7929 Scale = RHS->getZExtValue();
7930 Offset = 0;
7931 return I->getOperand(0);
7932 } else if (I->getOpcode() == Instruction::Add) {
7933 // We have X+C. Check to see if we really have (X*C2)+C1,
7934 // where C1 is divisible by C2.
7935 unsigned SubScale;
7936 Value *SubVal =
Chris Lattner4de84762010-01-04 07:02:48 +00007937 DecomposeSimpleLinearExpr(I->getOperand(0), SubScale, Offset);
Chris Lattner6a94de22007-10-12 05:30:59 +00007938 Offset += RHS->getZExtValue();
7939 Scale = SubScale;
7940 return SubVal;
Chris Lattnercfd65102005-10-29 04:36:15 +00007941 }
7942 }
7943 }
7944
7945 // Otherwise, we can't look past this.
7946 Scale = 1;
7947 Offset = 0;
7948 return Val;
7949}
7950
7951
Chris Lattnerb3f83972005-10-24 06:03:58 +00007952/// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
7953/// try to eliminate the cast by moving the type information into the alloc.
Chris Lattnerd3e28342007-04-27 17:44:50 +00007954Instruction *InstCombiner::PromoteCastOfAllocation(BitCastInst &CI,
Victor Hernandez7b929da2009-10-23 21:09:37 +00007955 AllocaInst &AI) {
Chris Lattnerd3e28342007-04-27 17:44:50 +00007956 const PointerType *PTy = cast<PointerType>(CI.getType());
Chris Lattnerb3f83972005-10-24 06:03:58 +00007957
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007958 BuilderTy AllocaBuilder(*Builder);
7959 AllocaBuilder.SetInsertPoint(AI.getParent(), &AI);
7960
Chris Lattnerb53c2382005-10-24 06:22:12 +00007961 // Remove any uses of AI that are dead.
7962 assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
Chris Lattner535014f2007-02-15 22:52:10 +00007963
Chris Lattnerb53c2382005-10-24 06:22:12 +00007964 for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
7965 Instruction *User = cast<Instruction>(*UI++);
7966 if (isInstructionTriviallyDead(User)) {
7967 while (UI != E && *UI == User)
7968 ++UI; // If this instruction uses AI more than once, don't break UI.
7969
Chris Lattnerb53c2382005-10-24 06:22:12 +00007970 ++NumDeadInst;
Chris Lattnerbdff5482009-08-23 04:37:46 +00007971 DEBUG(errs() << "IC: DCE: " << *User << '\n');
Chris Lattnerf22a5c62007-03-02 19:59:19 +00007972 EraseInstFromFunction(*User);
Chris Lattnerb53c2382005-10-24 06:22:12 +00007973 }
7974 }
Dan Gohmance9fe9f2009-07-21 23:21:54 +00007975
7976 // This requires TargetData to get the alloca alignment and size information.
7977 if (!TD) return 0;
7978
Chris Lattnerb3f83972005-10-24 06:03:58 +00007979 // Get the type really allocated and the type casted to.
7980 const Type *AllocElTy = AI.getAllocatedType();
7981 const Type *CastElTy = PTy->getElementType();
7982 if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
Chris Lattner18e78bb2005-10-24 06:26:18 +00007983
Chris Lattnerd2b7cec2007-02-14 05:52:17 +00007984 unsigned AllocElTyAlign = TD->getABITypeAlignment(AllocElTy);
7985 unsigned CastElTyAlign = TD->getABITypeAlignment(CastElTy);
Chris Lattner18e78bb2005-10-24 06:26:18 +00007986 if (CastElTyAlign < AllocElTyAlign) return 0;
7987
Chris Lattner39387a52005-10-24 06:35:18 +00007988 // If the allocation has multiple uses, only promote it if we are strictly
7989 // increasing the alignment of the resultant allocation. If we keep it the
Dale Johannesena0a66372009-03-05 00:39:02 +00007990 // same, we open the door to infinite loops of various kinds. (A reference
7991 // from a dbg.declare doesn't count as a use for this purpose.)
7992 if (!AI.hasOneUse() && !hasOneUsePlusDeclare(&AI) &&
7993 CastElTyAlign == AllocElTyAlign) return 0;
Chris Lattner39387a52005-10-24 06:35:18 +00007994
Duncan Sands777d2302009-05-09 07:06:46 +00007995 uint64_t AllocElTySize = TD->getTypeAllocSize(AllocElTy);
7996 uint64_t CastElTySize = TD->getTypeAllocSize(CastElTy);
Chris Lattner0ddac2a2005-10-27 05:53:56 +00007997 if (CastElTySize == 0 || AllocElTySize == 0) return 0;
Chris Lattner18e78bb2005-10-24 06:26:18 +00007998
Chris Lattner455fcc82005-10-29 03:19:53 +00007999 // See if we can satisfy the modulus by pulling a scale out of the array
8000 // size argument.
Jeff Cohen86796be2007-04-04 16:58:57 +00008001 unsigned ArraySizeScale;
8002 int ArrayOffset;
Chris Lattnercfd65102005-10-29 04:36:15 +00008003 Value *NumElements = // See if the array size is a decomposable linear expr.
Chris Lattner4de84762010-01-04 07:02:48 +00008004 DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale, ArrayOffset);
Chris Lattnercfd65102005-10-29 04:36:15 +00008005
Chris Lattner455fcc82005-10-29 03:19:53 +00008006 // If we can now satisfy the modulus, by using a non-1 scale, we really can
8007 // do the xform.
Chris Lattnercfd65102005-10-29 04:36:15 +00008008 if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
8009 (AllocElTySize*ArrayOffset ) % CastElTySize != 0) return 0;
Chris Lattner8142b0a2005-10-27 06:12:00 +00008010
Chris Lattner455fcc82005-10-29 03:19:53 +00008011 unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
8012 Value *Amt = 0;
8013 if (Scale == 1) {
8014 Amt = NumElements;
8015 } else {
Chris Lattner4de84762010-01-04 07:02:48 +00008016 Amt = ConstantInt::get(Type::getInt32Ty(CI.getContext()), Scale);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008017 // Insert before the alloca, not before the cast.
8018 Amt = AllocaBuilder.CreateMul(Amt, NumElements, "tmp");
Chris Lattner0ddac2a2005-10-27 05:53:56 +00008019 }
8020
Jeff Cohen86796be2007-04-04 16:58:57 +00008021 if (int Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
Chris Lattner4de84762010-01-04 07:02:48 +00008022 Value *Off = ConstantInt::get(Type::getInt32Ty(CI.getContext()),
8023 Offset, true);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008024 Amt = AllocaBuilder.CreateAdd(Amt, Off, "tmp");
Chris Lattnercfd65102005-10-29 04:36:15 +00008025 }
8026
Victor Hernandez7b929da2009-10-23 21:09:37 +00008027 AllocaInst *New = AllocaBuilder.CreateAlloca(CastElTy, Amt);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008028 New->setAlignment(AI.getAlignment());
Chris Lattner6934a042007-02-11 01:23:03 +00008029 New->takeName(&AI);
Chris Lattner39387a52005-10-24 06:35:18 +00008030
Dale Johannesena0a66372009-03-05 00:39:02 +00008031 // If the allocation has one real use plus a dbg.declare, just remove the
8032 // declare.
8033 if (DbgDeclareInst *DI = hasOneUsePlusDeclare(&AI)) {
8034 EraseInstFromFunction(*DI);
8035 }
8036 // If the allocation has multiple real uses, insert a cast and change all
8037 // things that used it to use the new cast. This will also hack on CI, but it
8038 // will die soon.
8039 else if (!AI.hasOneUse()) {
Reid Spencer3da59db2006-11-27 01:05:10 +00008040 // New is the allocation instruction, pointer typed. AI is the original
8041 // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008042 Value *NewCast = AllocaBuilder.CreateBitCast(New, AI.getType(), "tmpcast");
Chris Lattner39387a52005-10-24 06:35:18 +00008043 AI.replaceAllUsesWith(NewCast);
8044 }
Chris Lattnerb3f83972005-10-24 06:03:58 +00008045 return ReplaceInstUsesWith(CI, New);
8046}
8047
Chris Lattner70074e02006-05-13 02:06:03 +00008048/// CanEvaluateInDifferentType - Return true if we can take the specified value
Chris Lattnerc739cd62007-03-03 05:27:34 +00008049/// and return it as type Ty without inserting any new casts and without
8050/// changing the computed value. This is used by code that tries to decide
8051/// whether promoting or shrinking integer operations to wider or smaller types
8052/// will allow us to eliminate a truncate or extend.
8053///
8054/// This is a truncation operation if Ty is smaller than V->getType(), or an
8055/// extension operation if Ty is larger.
Chris Lattner8114b712008-06-18 04:00:49 +00008056///
8057/// If CastOpc is a truncation, then Ty will be a type smaller than V. We
8058/// should return true if trunc(V) can be computed by computing V in the smaller
8059/// type. If V is an instruction, then trunc(inst(x,y)) can be computed as
8060/// inst(trunc(x),trunc(y)), which only makes sense if x and y can be
8061/// efficiently truncated.
8062///
8063/// If CastOpc is a sext or zext, we are asking if the low bits of the value can
8064/// bit computed in a larger type, which is then and'd or sext_in_reg'd to get
8065/// the final result.
Dan Gohman6de29f82009-06-15 22:12:54 +00008066bool InstCombiner::CanEvaluateInDifferentType(Value *V, const Type *Ty,
Evan Cheng4e56ab22009-01-16 02:11:43 +00008067 unsigned CastOpc,
8068 int &NumCastsRemoved){
Chris Lattnerc739cd62007-03-03 05:27:34 +00008069 // We can always evaluate constants in another type.
Dan Gohman6de29f82009-06-15 22:12:54 +00008070 if (isa<Constant>(V))
Chris Lattnerc739cd62007-03-03 05:27:34 +00008071 return true;
Chris Lattner70074e02006-05-13 02:06:03 +00008072
8073 Instruction *I = dyn_cast<Instruction>(V);
Chris Lattnerc739cd62007-03-03 05:27:34 +00008074 if (!I) return false;
8075
Dan Gohman6de29f82009-06-15 22:12:54 +00008076 const Type *OrigTy = V->getType();
Chris Lattner70074e02006-05-13 02:06:03 +00008077
Chris Lattner951626b2007-08-02 06:11:14 +00008078 // If this is an extension or truncate, we can often eliminate it.
8079 if (isa<TruncInst>(I) || isa<ZExtInst>(I) || isa<SExtInst>(I)) {
8080 // If this is a cast from the destination type, we can trivially eliminate
8081 // it, and this will remove a cast overall.
8082 if (I->getOperand(0)->getType() == Ty) {
8083 // If the first operand is itself a cast, and is eliminable, do not count
8084 // this as an eliminable cast. We would prefer to eliminate those two
8085 // casts first.
Chris Lattner8114b712008-06-18 04:00:49 +00008086 if (!isa<CastInst>(I->getOperand(0)) && I->hasOneUse())
Chris Lattner951626b2007-08-02 06:11:14 +00008087 ++NumCastsRemoved;
8088 return true;
8089 }
8090 }
8091
8092 // We can't extend or shrink something that has multiple uses: doing so would
8093 // require duplicating the instruction in general, which isn't profitable.
8094 if (!I->hasOneUse()) return false;
8095
Evan Chengf35fd542009-01-15 17:01:23 +00008096 unsigned Opc = I->getOpcode();
8097 switch (Opc) {
Chris Lattnerc739cd62007-03-03 05:27:34 +00008098 case Instruction::Add:
8099 case Instruction::Sub:
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00008100 case Instruction::Mul:
Chris Lattner70074e02006-05-13 02:06:03 +00008101 case Instruction::And:
8102 case Instruction::Or:
8103 case Instruction::Xor:
8104 // These operators can all arbitrarily be extended or truncated.
Chris Lattner951626b2007-08-02 06:11:14 +00008105 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00008106 NumCastsRemoved) &&
Chris Lattner951626b2007-08-02 06:11:14 +00008107 CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00008108 NumCastsRemoved);
Chris Lattnerc739cd62007-03-03 05:27:34 +00008109
Eli Friedman070a9812009-07-13 22:46:01 +00008110 case Instruction::UDiv:
8111 case Instruction::URem: {
8112 // UDiv and URem can be truncated if all the truncated bits are zero.
8113 uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
8114 uint32_t BitWidth = Ty->getScalarSizeInBits();
8115 if (BitWidth < OrigBitWidth) {
8116 APInt Mask = APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth);
8117 if (MaskedValueIsZero(I->getOperand(0), Mask) &&
8118 MaskedValueIsZero(I->getOperand(1), Mask)) {
8119 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
8120 NumCastsRemoved) &&
8121 CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
8122 NumCastsRemoved);
8123 }
8124 }
8125 break;
8126 }
Chris Lattner46b96052006-11-29 07:18:39 +00008127 case Instruction::Shl:
Chris Lattnerc739cd62007-03-03 05:27:34 +00008128 // If we are truncating the result of this SHL, and if it's a shift of a
8129 // constant amount, we can always perform a SHL in a smaller type.
8130 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
Dan Gohman6de29f82009-06-15 22:12:54 +00008131 uint32_t BitWidth = Ty->getScalarSizeInBits();
8132 if (BitWidth < OrigTy->getScalarSizeInBits() &&
Zhou Sheng302748d2007-03-30 17:20:39 +00008133 CI->getLimitedValue(BitWidth) < BitWidth)
Chris Lattner951626b2007-08-02 06:11:14 +00008134 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00008135 NumCastsRemoved);
Chris Lattnerc739cd62007-03-03 05:27:34 +00008136 }
8137 break;
8138 case Instruction::LShr:
Chris Lattnerc739cd62007-03-03 05:27:34 +00008139 // If this is a truncate of a logical shr, we can truncate it to a smaller
8140 // lshr iff we know that the bits we would otherwise be shifting in are
8141 // already zeros.
8142 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
Dan Gohman6de29f82009-06-15 22:12:54 +00008143 uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
8144 uint32_t BitWidth = Ty->getScalarSizeInBits();
Zhou Sheng302748d2007-03-30 17:20:39 +00008145 if (BitWidth < OrigBitWidth &&
Chris Lattnerc739cd62007-03-03 05:27:34 +00008146 MaskedValueIsZero(I->getOperand(0),
Zhou Sheng302748d2007-03-30 17:20:39 +00008147 APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth)) &&
8148 CI->getLimitedValue(BitWidth) < BitWidth) {
Chris Lattner951626b2007-08-02 06:11:14 +00008149 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00008150 NumCastsRemoved);
Chris Lattnerc739cd62007-03-03 05:27:34 +00008151 }
8152 }
Chris Lattner46b96052006-11-29 07:18:39 +00008153 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00008154 case Instruction::ZExt:
8155 case Instruction::SExt:
Chris Lattner951626b2007-08-02 06:11:14 +00008156 case Instruction::Trunc:
8157 // If this is the same kind of case as our original (e.g. zext+zext), we
Chris Lattner5543a852007-08-02 17:23:38 +00008158 // can safely replace it. Note that replacing it does not reduce the number
8159 // of casts in the input.
Evan Chengf35fd542009-01-15 17:01:23 +00008160 if (Opc == CastOpc)
8161 return true;
8162
8163 // sext (zext ty1), ty2 -> zext ty2
Evan Cheng661d9c32009-01-15 17:09:07 +00008164 if (CastOpc == Instruction::SExt && Opc == Instruction::ZExt)
Chris Lattner70074e02006-05-13 02:06:03 +00008165 return true;
Reid Spencer3da59db2006-11-27 01:05:10 +00008166 break;
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00008167 case Instruction::Select: {
8168 SelectInst *SI = cast<SelectInst>(I);
8169 return CanEvaluateInDifferentType(SI->getTrueValue(), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00008170 NumCastsRemoved) &&
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00008171 CanEvaluateInDifferentType(SI->getFalseValue(), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00008172 NumCastsRemoved);
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00008173 }
Chris Lattner8114b712008-06-18 04:00:49 +00008174 case Instruction::PHI: {
8175 // We can change a phi if we can change all operands.
8176 PHINode *PN = cast<PHINode>(I);
8177 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
8178 if (!CanEvaluateInDifferentType(PN->getIncomingValue(i), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00008179 NumCastsRemoved))
Chris Lattner8114b712008-06-18 04:00:49 +00008180 return false;
8181 return true;
8182 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008183 default:
Chris Lattner70074e02006-05-13 02:06:03 +00008184 // TODO: Can handle more cases here.
8185 break;
8186 }
8187
8188 return false;
8189}
8190
8191/// EvaluateInDifferentType - Given an expression that
8192/// CanEvaluateInDifferentType returns true for, actually insert the code to
8193/// evaluate the expression.
Reid Spencerc55b2432006-12-13 18:21:21 +00008194Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty,
Chris Lattnerc739cd62007-03-03 05:27:34 +00008195 bool isSigned) {
Chris Lattner70074e02006-05-13 02:06:03 +00008196 if (Constant *C = dyn_cast<Constant>(V))
Chris Lattner9956c052009-11-08 19:23:30 +00008197 return ConstantExpr::getIntegerCast(C, Ty, isSigned /*Sext or ZExt*/);
Chris Lattner70074e02006-05-13 02:06:03 +00008198
8199 // Otherwise, it must be an instruction.
8200 Instruction *I = cast<Instruction>(V);
Chris Lattner01859e82006-05-20 23:14:03 +00008201 Instruction *Res = 0;
Evan Chengf35fd542009-01-15 17:01:23 +00008202 unsigned Opc = I->getOpcode();
8203 switch (Opc) {
Chris Lattnerc739cd62007-03-03 05:27:34 +00008204 case Instruction::Add:
8205 case Instruction::Sub:
Nick Lewyckye6b0c002008-01-22 05:08:48 +00008206 case Instruction::Mul:
Chris Lattner70074e02006-05-13 02:06:03 +00008207 case Instruction::And:
8208 case Instruction::Or:
Chris Lattnerc739cd62007-03-03 05:27:34 +00008209 case Instruction::Xor:
Chris Lattner46b96052006-11-29 07:18:39 +00008210 case Instruction::AShr:
8211 case Instruction::LShr:
Eli Friedman070a9812009-07-13 22:46:01 +00008212 case Instruction::Shl:
8213 case Instruction::UDiv:
8214 case Instruction::URem: {
Reid Spencerc55b2432006-12-13 18:21:21 +00008215 Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
Chris Lattnerc739cd62007-03-03 05:27:34 +00008216 Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
Evan Chengf35fd542009-01-15 17:01:23 +00008217 Res = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
Chris Lattner46b96052006-11-29 07:18:39 +00008218 break;
8219 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008220 case Instruction::Trunc:
8221 case Instruction::ZExt:
8222 case Instruction::SExt:
Reid Spencer3da59db2006-11-27 01:05:10 +00008223 // If the source type of the cast is the type we're trying for then we can
Chris Lattner951626b2007-08-02 06:11:14 +00008224 // just return the source. There's no need to insert it because it is not
8225 // new.
Chris Lattner70074e02006-05-13 02:06:03 +00008226 if (I->getOperand(0)->getType() == Ty)
8227 return I->getOperand(0);
8228
Chris Lattner8114b712008-06-18 04:00:49 +00008229 // Otherwise, must be the same type of cast, so just reinsert a new one.
Chris Lattner9956c052009-11-08 19:23:30 +00008230 Res = CastInst::Create(cast<CastInst>(I)->getOpcode(), I->getOperand(0),Ty);
Chris Lattner951626b2007-08-02 06:11:14 +00008231 break;
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00008232 case Instruction::Select: {
8233 Value *True = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
8234 Value *False = EvaluateInDifferentType(I->getOperand(2), Ty, isSigned);
8235 Res = SelectInst::Create(I->getOperand(0), True, False);
8236 break;
8237 }
Chris Lattner8114b712008-06-18 04:00:49 +00008238 case Instruction::PHI: {
8239 PHINode *OPN = cast<PHINode>(I);
8240 PHINode *NPN = PHINode::Create(Ty);
8241 for (unsigned i = 0, e = OPN->getNumIncomingValues(); i != e; ++i) {
8242 Value *V =EvaluateInDifferentType(OPN->getIncomingValue(i), Ty, isSigned);
8243 NPN->addIncoming(V, OPN->getIncomingBlock(i));
8244 }
8245 Res = NPN;
8246 break;
8247 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008248 default:
Chris Lattner70074e02006-05-13 02:06:03 +00008249 // TODO: Can handle more cases here.
Torok Edwinc23197a2009-07-14 16:55:14 +00008250 llvm_unreachable("Unreachable!");
Chris Lattner70074e02006-05-13 02:06:03 +00008251 break;
8252 }
8253
Chris Lattner8114b712008-06-18 04:00:49 +00008254 Res->takeName(I);
Chris Lattner70074e02006-05-13 02:06:03 +00008255 return InsertNewInstBefore(Res, *I);
8256}
8257
Reid Spencer3da59db2006-11-27 01:05:10 +00008258/// @brief Implement the transforms common to all CastInst visitors.
8259Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
Chris Lattner79d35b32003-06-23 21:59:52 +00008260 Value *Src = CI.getOperand(0);
8261
Dan Gohman23d9d272007-05-11 21:10:54 +00008262 // Many cases of "cast of a cast" are eliminable. If it's eliminable we just
Reid Spencer3da59db2006-11-27 01:05:10 +00008263 // eliminate it now.
Chris Lattner6e7ba452005-01-01 16:22:27 +00008264 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
Reid Spencer3da59db2006-11-27 01:05:10 +00008265 if (Instruction::CastOps opc =
8266 isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
8267 // The first cast (CSrc) is eliminable so we need to fix up or replace
8268 // the second cast (CI). CSrc will then have a good chance of being dead.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008269 return CastInst::Create(opc, CSrc->getOperand(0), CI.getType());
Chris Lattner8fd217c2002-08-02 20:00:25 +00008270 }
8271 }
Chris Lattnera710ddc2004-05-25 04:29:21 +00008272
Reid Spencer3da59db2006-11-27 01:05:10 +00008273 // If we are casting a select then fold the cast into the select
Chris Lattner6e7ba452005-01-01 16:22:27 +00008274 if (SelectInst *SI = dyn_cast<SelectInst>(Src))
8275 if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
8276 return NV;
Reid Spencer3da59db2006-11-27 01:05:10 +00008277
8278 // If we are casting a PHI then fold the cast into the PHI
Chris Lattner9956c052009-11-08 19:23:30 +00008279 if (isa<PHINode>(Src)) {
8280 // We don't do this if this would create a PHI node with an illegal type if
8281 // it is currently legal.
8282 if (!isa<IntegerType>(Src->getType()) ||
8283 !isa<IntegerType>(CI.getType()) ||
Chris Lattnerc22d4d12009-11-10 07:23:37 +00008284 ShouldChangeType(CI.getType(), Src->getType(), TD))
Chris Lattner9956c052009-11-08 19:23:30 +00008285 if (Instruction *NV = FoldOpIntoPhi(CI))
8286 return NV;
Chris Lattner9956c052009-11-08 19:23:30 +00008287 }
Chris Lattner9fb92132006-04-12 18:09:35 +00008288
Reid Spencer3da59db2006-11-27 01:05:10 +00008289 return 0;
8290}
8291
Chris Lattner46cd5a12009-01-09 05:44:56 +00008292/// FindElementAtOffset - Given a type and a constant offset, determine whether
8293/// or not there is a sequence of GEP indices into the type that will land us at
Chris Lattner3914f722009-01-24 01:00:13 +00008294/// the specified offset. If so, fill them into NewIndices and return the
8295/// resultant element type, otherwise return null.
8296static const Type *FindElementAtOffset(const Type *Ty, int64_t Offset,
8297 SmallVectorImpl<Value*> &NewIndices,
Chris Lattner4de84762010-01-04 07:02:48 +00008298 const TargetData *TD) {
Dan Gohmance9fe9f2009-07-21 23:21:54 +00008299 if (!TD) return 0;
Chris Lattner3914f722009-01-24 01:00:13 +00008300 if (!Ty->isSized()) return 0;
Chris Lattner46cd5a12009-01-09 05:44:56 +00008301
8302 // Start with the index over the outer type. Note that the type size
8303 // might be zero (even if the offset isn't zero) if the indexed type
8304 // is something like [0 x {int, int}]
Chris Lattner4de84762010-01-04 07:02:48 +00008305 const Type *IntPtrTy = TD->getIntPtrType(Ty->getContext());
Chris Lattner46cd5a12009-01-09 05:44:56 +00008306 int64_t FirstIdx = 0;
Duncan Sands777d2302009-05-09 07:06:46 +00008307 if (int64_t TySize = TD->getTypeAllocSize(Ty)) {
Chris Lattner46cd5a12009-01-09 05:44:56 +00008308 FirstIdx = Offset/TySize;
Chris Lattner31a69cb2009-01-11 20:41:36 +00008309 Offset -= FirstIdx*TySize;
Chris Lattner46cd5a12009-01-09 05:44:56 +00008310
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008311 // Handle hosts where % returns negative instead of values [0..TySize).
Chris Lattner46cd5a12009-01-09 05:44:56 +00008312 if (Offset < 0) {
8313 --FirstIdx;
8314 Offset += TySize;
8315 assert(Offset >= 0);
8316 }
8317 assert((uint64_t)Offset < (uint64_t)TySize && "Out of range offset");
8318 }
8319
Owen Andersoneed707b2009-07-24 23:12:02 +00008320 NewIndices.push_back(ConstantInt::get(IntPtrTy, FirstIdx));
Chris Lattner46cd5a12009-01-09 05:44:56 +00008321
8322 // Index into the types. If we fail, set OrigBase to null.
8323 while (Offset) {
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008324 // Indexing into tail padding between struct/array elements.
8325 if (uint64_t(Offset*8) >= TD->getTypeSizeInBits(Ty))
Chris Lattner3914f722009-01-24 01:00:13 +00008326 return 0;
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008327
Chris Lattner46cd5a12009-01-09 05:44:56 +00008328 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
8329 const StructLayout *SL = TD->getStructLayout(STy);
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008330 assert(Offset < (int64_t)SL->getSizeInBytes() &&
8331 "Offset must stay within the indexed type");
8332
Chris Lattner46cd5a12009-01-09 05:44:56 +00008333 unsigned Elt = SL->getElementContainingOffset(Offset);
Chris Lattner4de84762010-01-04 07:02:48 +00008334 NewIndices.push_back(ConstantInt::get(Type::getInt32Ty(Ty->getContext()),
8335 Elt));
Chris Lattner46cd5a12009-01-09 05:44:56 +00008336
8337 Offset -= SL->getElementOffset(Elt);
8338 Ty = STy->getElementType(Elt);
Chris Lattner1c412d92009-01-11 20:23:52 +00008339 } else if (const ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
Duncan Sands777d2302009-05-09 07:06:46 +00008340 uint64_t EltSize = TD->getTypeAllocSize(AT->getElementType());
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008341 assert(EltSize && "Cannot index into a zero-sized array");
Owen Andersoneed707b2009-07-24 23:12:02 +00008342 NewIndices.push_back(ConstantInt::get(IntPtrTy,Offset/EltSize));
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008343 Offset %= EltSize;
Chris Lattner1c412d92009-01-11 20:23:52 +00008344 Ty = AT->getElementType();
Chris Lattner46cd5a12009-01-09 05:44:56 +00008345 } else {
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008346 // Otherwise, we can't index into the middle of this atomic type, bail.
Chris Lattner3914f722009-01-24 01:00:13 +00008347 return 0;
Chris Lattner46cd5a12009-01-09 05:44:56 +00008348 }
8349 }
8350
Chris Lattner3914f722009-01-24 01:00:13 +00008351 return Ty;
Chris Lattner46cd5a12009-01-09 05:44:56 +00008352}
8353
Chris Lattnerd3e28342007-04-27 17:44:50 +00008354/// @brief Implement the transforms for cast of pointer (bitcast/ptrtoint)
8355Instruction *InstCombiner::commonPointerCastTransforms(CastInst &CI) {
8356 Value *Src = CI.getOperand(0);
8357
Chris Lattnerd3e28342007-04-27 17:44:50 +00008358 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
Chris Lattner9bc14642007-04-28 00:57:34 +00008359 // If casting the result of a getelementptr instruction with no offset, turn
8360 // this into a cast of the original pointer!
Chris Lattnerd3e28342007-04-27 17:44:50 +00008361 if (GEP->hasAllZeroIndices()) {
8362 // Changing the cast operand is usually not a good idea but it is safe
8363 // here because the pointer operand is being replaced with another
8364 // pointer operand so the opcode doesn't need to change.
Chris Lattner7a1e9242009-08-30 06:13:40 +00008365 Worklist.Add(GEP);
Chris Lattnerd3e28342007-04-27 17:44:50 +00008366 CI.setOperand(0, GEP->getOperand(0));
8367 return &CI;
8368 }
Chris Lattner9bc14642007-04-28 00:57:34 +00008369
8370 // If the GEP has a single use, and the base pointer is a bitcast, and the
8371 // GEP computes a constant offset, see if we can convert these three
8372 // instructions into fewer. This typically happens with unions and other
8373 // non-type-safe code.
Dan Gohmance9fe9f2009-07-21 23:21:54 +00008374 if (TD && GEP->hasOneUse() && isa<BitCastInst>(GEP->getOperand(0))) {
Chris Lattner9bc14642007-04-28 00:57:34 +00008375 if (GEP->hasAllConstantIndices()) {
8376 // We are guaranteed to get a constant from EmitGEPOffset.
Chris Lattner092543c2009-11-04 08:05:20 +00008377 ConstantInt *OffsetV = cast<ConstantInt>(EmitGEPOffset(GEP, *this));
Chris Lattner9bc14642007-04-28 00:57:34 +00008378 int64_t Offset = OffsetV->getSExtValue();
8379
8380 // Get the base pointer input of the bitcast, and the type it points to.
8381 Value *OrigBase = cast<BitCastInst>(GEP->getOperand(0))->getOperand(0);
8382 const Type *GEPIdxTy =
8383 cast<PointerType>(OrigBase->getType())->getElementType();
Chris Lattner46cd5a12009-01-09 05:44:56 +00008384 SmallVector<Value*, 8> NewIndices;
Chris Lattner4de84762010-01-04 07:02:48 +00008385 if (FindElementAtOffset(GEPIdxTy, Offset, NewIndices, TD)) {
Chris Lattner46cd5a12009-01-09 05:44:56 +00008386 // If we were able to index down into an element, create the GEP
8387 // and bitcast the result. This eliminates one bitcast, potentially
8388 // two.
Dan Gohmanf8dbee72009-09-07 23:54:19 +00008389 Value *NGEP = cast<GEPOperator>(GEP)->isInBounds() ?
8390 Builder->CreateInBoundsGEP(OrigBase,
8391 NewIndices.begin(), NewIndices.end()) :
8392 Builder->CreateGEP(OrigBase, NewIndices.begin(), NewIndices.end());
Chris Lattner46cd5a12009-01-09 05:44:56 +00008393 NGEP->takeName(GEP);
Chris Lattner9bc14642007-04-28 00:57:34 +00008394
Chris Lattner46cd5a12009-01-09 05:44:56 +00008395 if (isa<BitCastInst>(CI))
8396 return new BitCastInst(NGEP, CI.getType());
8397 assert(isa<PtrToIntInst>(CI));
8398 return new PtrToIntInst(NGEP, CI.getType());
Chris Lattner9bc14642007-04-28 00:57:34 +00008399 }
8400 }
8401 }
Chris Lattnerd3e28342007-04-27 17:44:50 +00008402 }
8403
8404 return commonCastTransforms(CI);
8405}
8406
Eli Friedmaneb7f7a82009-07-13 20:58:59 +00008407/// commonIntCastTransforms - This function implements the common transforms
8408/// for trunc, zext, and sext.
Reid Spencer3da59db2006-11-27 01:05:10 +00008409Instruction *InstCombiner::commonIntCastTransforms(CastInst &CI) {
8410 if (Instruction *Result = commonCastTransforms(CI))
8411 return Result;
8412
8413 Value *Src = CI.getOperand(0);
8414 const Type *SrcTy = Src->getType();
8415 const Type *DestTy = CI.getType();
Dan Gohman6de29f82009-06-15 22:12:54 +00008416 uint32_t SrcBitSize = SrcTy->getScalarSizeInBits();
8417 uint32_t DestBitSize = DestTy->getScalarSizeInBits();
Reid Spencer3da59db2006-11-27 01:05:10 +00008418
Reid Spencer3da59db2006-11-27 01:05:10 +00008419 // See if we can simplify any instructions used by the LHS whose sole
8420 // purpose is to compute bits we don't care about.
Chris Lattner886ab6c2009-01-31 08:15:18 +00008421 if (SimplifyDemandedInstructionBits(CI))
Reid Spencer3da59db2006-11-27 01:05:10 +00008422 return &CI;
8423
8424 // If the source isn't an instruction or has more than one use then we
8425 // can't do anything more.
Reid Spencere4d87aa2006-12-23 06:05:41 +00008426 Instruction *SrcI = dyn_cast<Instruction>(Src);
8427 if (!SrcI || !Src->hasOneUse())
Reid Spencer3da59db2006-11-27 01:05:10 +00008428 return 0;
8429
Chris Lattnerc739cd62007-03-03 05:27:34 +00008430 // Attempt to propagate the cast into the instruction for int->int casts.
Reid Spencer3da59db2006-11-27 01:05:10 +00008431 int NumCastsRemoved = 0;
Eli Friedman65445c52009-07-13 21:45:57 +00008432 // Only do this if the dest type is a simple type, don't convert the
8433 // expression tree to something weird like i93 unless the source is also
8434 // strange.
Chris Lattner6b583912009-11-10 17:00:47 +00008435 if ((isa<VectorType>(DestTy) ||
8436 ShouldChangeType(SrcI->getType(), DestTy, TD)) &&
8437 CanEvaluateInDifferentType(SrcI, DestTy,
8438 CI.getOpcode(), NumCastsRemoved)) {
Reid Spencer3da59db2006-11-27 01:05:10 +00008439 // If this cast is a truncate, evaluting in a different type always
Chris Lattner951626b2007-08-02 06:11:14 +00008440 // eliminates the cast, so it is always a win. If this is a zero-extension,
8441 // we need to do an AND to maintain the clear top-part of the computation,
8442 // so we require that the input have eliminated at least one cast. If this
8443 // is a sign extension, we insert two new casts (to do the extension) so we
Reid Spencer3da59db2006-11-27 01:05:10 +00008444 // require that two casts have been eliminated.
Evan Chengf35fd542009-01-15 17:01:23 +00008445 bool DoXForm = false;
8446 bool JustReplace = false;
Chris Lattnerc739cd62007-03-03 05:27:34 +00008447 switch (CI.getOpcode()) {
8448 default:
8449 // All the others use floating point so we shouldn't actually
8450 // get here because of the check above.
Torok Edwinc23197a2009-07-14 16:55:14 +00008451 llvm_unreachable("Unknown cast type");
Chris Lattnerc739cd62007-03-03 05:27:34 +00008452 case Instruction::Trunc:
8453 DoXForm = true;
8454 break;
Evan Cheng4e56ab22009-01-16 02:11:43 +00008455 case Instruction::ZExt: {
Chris Lattnerc739cd62007-03-03 05:27:34 +00008456 DoXForm = NumCastsRemoved >= 1;
Chris Lattner918871e2009-11-07 19:11:46 +00008457
Chris Lattner39c27ed2009-01-31 19:05:27 +00008458 if (!DoXForm && 0) {
Evan Cheng4e56ab22009-01-16 02:11:43 +00008459 // If it's unnecessary to issue an AND to clear the high bits, it's
8460 // always profitable to do this xform.
Chris Lattner39c27ed2009-01-31 19:05:27 +00008461 Value *TryRes = EvaluateInDifferentType(SrcI, DestTy, false);
Evan Cheng4e56ab22009-01-16 02:11:43 +00008462 APInt Mask(APInt::getBitsSet(DestBitSize, SrcBitSize, DestBitSize));
8463 if (MaskedValueIsZero(TryRes, Mask))
8464 return ReplaceInstUsesWith(CI, TryRes);
Chris Lattner39c27ed2009-01-31 19:05:27 +00008465
8466 if (Instruction *TryI = dyn_cast<Instruction>(TryRes))
Evan Cheng4e56ab22009-01-16 02:11:43 +00008467 if (TryI->use_empty())
8468 EraseInstFromFunction(*TryI);
8469 }
Chris Lattnerc739cd62007-03-03 05:27:34 +00008470 break;
Evan Cheng4e56ab22009-01-16 02:11:43 +00008471 }
Evan Chengf35fd542009-01-15 17:01:23 +00008472 case Instruction::SExt: {
Chris Lattnerc739cd62007-03-03 05:27:34 +00008473 DoXForm = NumCastsRemoved >= 2;
Chris Lattner39c27ed2009-01-31 19:05:27 +00008474 if (!DoXForm && !isa<TruncInst>(SrcI) && 0) {
Evan Cheng4e56ab22009-01-16 02:11:43 +00008475 // If we do not have to emit the truncate + sext pair, then it's always
8476 // profitable to do this xform.
Evan Chengf35fd542009-01-15 17:01:23 +00008477 //
8478 // It's not safe to eliminate the trunc + sext pair if one of the
8479 // eliminated cast is a truncate. e.g.
8480 // t2 = trunc i32 t1 to i16
8481 // t3 = sext i16 t2 to i32
8482 // !=
8483 // i32 t1
Chris Lattner39c27ed2009-01-31 19:05:27 +00008484 Value *TryRes = EvaluateInDifferentType(SrcI, DestTy, true);
Evan Cheng4e56ab22009-01-16 02:11:43 +00008485 unsigned NumSignBits = ComputeNumSignBits(TryRes);
8486 if (NumSignBits > (DestBitSize - SrcBitSize))
8487 return ReplaceInstUsesWith(CI, TryRes);
Chris Lattner39c27ed2009-01-31 19:05:27 +00008488
8489 if (Instruction *TryI = dyn_cast<Instruction>(TryRes))
Evan Cheng4e56ab22009-01-16 02:11:43 +00008490 if (TryI->use_empty())
8491 EraseInstFromFunction(*TryI);
Evan Chengf35fd542009-01-15 17:01:23 +00008492 }
Chris Lattnerc739cd62007-03-03 05:27:34 +00008493 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00008494 }
Evan Chengf35fd542009-01-15 17:01:23 +00008495 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008496
8497 if (DoXForm) {
Chris Lattnerbdff5482009-08-23 04:37:46 +00008498 DEBUG(errs() << "ICE: EvaluateInDifferentType converting expression type"
8499 " to avoid cast: " << CI);
Reid Spencerc55b2432006-12-13 18:21:21 +00008500 Value *Res = EvaluateInDifferentType(SrcI, DestTy,
8501 CI.getOpcode() == Instruction::SExt);
Evan Cheng4e56ab22009-01-16 02:11:43 +00008502 if (JustReplace)
Chris Lattner39c27ed2009-01-31 19:05:27 +00008503 // Just replace this cast with the result.
8504 return ReplaceInstUsesWith(CI, Res);
Evan Cheng4e56ab22009-01-16 02:11:43 +00008505
Reid Spencer3da59db2006-11-27 01:05:10 +00008506 assert(Res->getType() == DestTy);
8507 switch (CI.getOpcode()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00008508 default: llvm_unreachable("Unknown cast type!");
Reid Spencer3da59db2006-11-27 01:05:10 +00008509 case Instruction::Trunc:
Reid Spencer3da59db2006-11-27 01:05:10 +00008510 // Just replace this cast with the result.
8511 return ReplaceInstUsesWith(CI, Res);
8512 case Instruction::ZExt: {
Reid Spencer3da59db2006-11-27 01:05:10 +00008513 assert(SrcBitSize < DestBitSize && "Not a zext?");
Evan Cheng4e56ab22009-01-16 02:11:43 +00008514
8515 // If the high bits are already zero, just replace this cast with the
8516 // result.
8517 APInt Mask(APInt::getBitsSet(DestBitSize, SrcBitSize, DestBitSize));
8518 if (MaskedValueIsZero(Res, Mask))
8519 return ReplaceInstUsesWith(CI, Res);
8520
8521 // We need to emit an AND to clear the high bits.
Chris Lattner4de84762010-01-04 07:02:48 +00008522 Constant *C = ConstantInt::get(CI.getContext(),
Owen Andersoneed707b2009-07-24 23:12:02 +00008523 APInt::getLowBitsSet(DestBitSize, SrcBitSize));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008524 return BinaryOperator::CreateAnd(Res, C);
Reid Spencer3da59db2006-11-27 01:05:10 +00008525 }
Evan Cheng4e56ab22009-01-16 02:11:43 +00008526 case Instruction::SExt: {
8527 // If the high bits are already filled with sign bit, just replace this
8528 // cast with the result.
8529 unsigned NumSignBits = ComputeNumSignBits(Res);
8530 if (NumSignBits > (DestBitSize - SrcBitSize))
Evan Chengf35fd542009-01-15 17:01:23 +00008531 return ReplaceInstUsesWith(CI, Res);
8532
Reid Spencer3da59db2006-11-27 01:05:10 +00008533 // We need to emit a cast to truncate, then a cast to sext.
Chris Lattner2345d1d2009-08-30 20:01:10 +00008534 return new SExtInst(Builder->CreateTrunc(Res, Src->getType()), DestTy);
Reid Spencer3da59db2006-11-27 01:05:10 +00008535 }
Evan Cheng4e56ab22009-01-16 02:11:43 +00008536 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008537 }
8538 }
8539
8540 Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
8541 Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
8542
8543 switch (SrcI->getOpcode()) {
8544 case Instruction::Add:
8545 case Instruction::Mul:
8546 case Instruction::And:
8547 case Instruction::Or:
8548 case Instruction::Xor:
Chris Lattner01deb9d2007-04-03 17:43:25 +00008549 // If we are discarding information, rewrite.
Eli Friedman65445c52009-07-13 21:45:57 +00008550 if (DestBitSize < SrcBitSize && DestBitSize != 1) {
8551 // Don't insert two casts unless at least one can be eliminated.
8552 if (!ValueRequiresCast(CI.getOpcode(), Op1, DestTy, TD) ||
Reid Spencere4d87aa2006-12-23 06:05:41 +00008553 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
Chris Lattner2345d1d2009-08-30 20:01:10 +00008554 Value *Op0c = Builder->CreateTrunc(Op0, DestTy, Op0->getName());
8555 Value *Op1c = Builder->CreateTrunc(Op1, DestTy, Op1->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008556 return BinaryOperator::Create(
Reid Spencer17212df2006-12-12 09:18:51 +00008557 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
Reid Spencer3da59db2006-11-27 01:05:10 +00008558 }
8559 }
8560
8561 // cast (xor bool X, true) to int --> xor (cast bool X to int), 1
8562 if (isa<ZExtInst>(CI) && SrcBitSize == 1 &&
8563 SrcI->getOpcode() == Instruction::Xor &&
Chris Lattner4de84762010-01-04 07:02:48 +00008564 Op1 == ConstantInt::getTrue(CI.getContext()) &&
Reid Spencere4d87aa2006-12-23 06:05:41 +00008565 (!Op0->hasOneUse() || !isa<CmpInst>(Op0))) {
Chris Lattner2345d1d2009-08-30 20:01:10 +00008566 Value *New = Builder->CreateZExt(Op0, DestTy, Op0->getName());
Owen Andersond672ecb2009-07-03 00:17:18 +00008567 return BinaryOperator::CreateXor(New,
Owen Andersoneed707b2009-07-24 23:12:02 +00008568 ConstantInt::get(CI.getType(), 1));
Reid Spencer3da59db2006-11-27 01:05:10 +00008569 }
8570 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00008571
Eli Friedman65445c52009-07-13 21:45:57 +00008572 case Instruction::Shl: {
8573 // Canonicalize trunc inside shl, if we can.
8574 ConstantInt *CI = dyn_cast<ConstantInt>(Op1);
8575 if (CI && DestBitSize < SrcBitSize &&
8576 CI->getLimitedValue(DestBitSize) < DestBitSize) {
Chris Lattner2345d1d2009-08-30 20:01:10 +00008577 Value *Op0c = Builder->CreateTrunc(Op0, DestTy, Op0->getName());
8578 Value *Op1c = Builder->CreateTrunc(Op1, DestTy, Op1->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008579 return BinaryOperator::CreateShl(Op0c, Op1c);
Reid Spencer3da59db2006-11-27 01:05:10 +00008580 }
8581 break;
Eli Friedman65445c52009-07-13 21:45:57 +00008582 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008583 }
8584 return 0;
8585}
8586
Chris Lattner8a9f5712007-04-11 06:57:46 +00008587Instruction *InstCombiner::visitTrunc(TruncInst &CI) {
Chris Lattner6aa5eb12006-11-29 07:04:07 +00008588 if (Instruction *Result = commonIntCastTransforms(CI))
8589 return Result;
8590
8591 Value *Src = CI.getOperand(0);
8592 const Type *Ty = CI.getType();
Dan Gohman6de29f82009-06-15 22:12:54 +00008593 uint32_t DestBitWidth = Ty->getScalarSizeInBits();
8594 uint32_t SrcBitWidth = Src->getType()->getScalarSizeInBits();
Chris Lattner4f9797d2009-03-24 18:15:30 +00008595
8596 // Canonicalize trunc x to i1 -> (icmp ne (and x, 1), 0)
Eli Friedman191a0ae2009-07-18 09:21:25 +00008597 if (DestBitWidth == 1) {
Owen Andersoneed707b2009-07-24 23:12:02 +00008598 Constant *One = ConstantInt::get(Src->getType(), 1);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008599 Src = Builder->CreateAnd(Src, One, "tmp");
Owen Andersona7235ea2009-07-31 20:28:14 +00008600 Value *Zero = Constant::getNullValue(Src->getType());
Dan Gohman1c8a23c2009-08-25 23:17:54 +00008601 return new ICmpInst(ICmpInst::ICMP_NE, Src, Zero);
Chris Lattner4f9797d2009-03-24 18:15:30 +00008602 }
Dan Gohman6de29f82009-06-15 22:12:54 +00008603
Chris Lattner4f9797d2009-03-24 18:15:30 +00008604 // Optimize trunc(lshr(), c) to pull the shift through the truncate.
8605 ConstantInt *ShAmtV = 0;
8606 Value *ShiftOp = 0;
8607 if (Src->hasOneUse() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00008608 match(Src, m_LShr(m_Value(ShiftOp), m_ConstantInt(ShAmtV)))) {
Chris Lattner4f9797d2009-03-24 18:15:30 +00008609 uint32_t ShAmt = ShAmtV->getLimitedValue(SrcBitWidth);
8610
8611 // Get a mask for the bits shifting in.
8612 APInt Mask(APInt::getLowBitsSet(SrcBitWidth, ShAmt).shl(DestBitWidth));
8613 if (MaskedValueIsZero(ShiftOp, Mask)) {
8614 if (ShAmt >= DestBitWidth) // All zeros.
Owen Andersona7235ea2009-07-31 20:28:14 +00008615 return ReplaceInstUsesWith(CI, Constant::getNullValue(Ty));
Chris Lattner4f9797d2009-03-24 18:15:30 +00008616
8617 // Okay, we can shrink this. Truncate the input, then return a new
8618 // shift.
Chris Lattner2345d1d2009-08-30 20:01:10 +00008619 Value *V1 = Builder->CreateTrunc(ShiftOp, Ty, ShiftOp->getName());
Owen Andersonbaf3c402009-07-29 18:55:55 +00008620 Value *V2 = ConstantExpr::getTrunc(ShAmtV, Ty);
Chris Lattner4f9797d2009-03-24 18:15:30 +00008621 return BinaryOperator::CreateLShr(V1, V2);
Chris Lattner6aa5eb12006-11-29 07:04:07 +00008622 }
8623 }
Chris Lattner9956c052009-11-08 19:23:30 +00008624
Chris Lattner6aa5eb12006-11-29 07:04:07 +00008625 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00008626}
8627
Evan Chengb98a10e2008-03-24 00:21:34 +00008628/// transformZExtICmp - Transform (zext icmp) to bitwise / integer operations
8629/// in order to eliminate the icmp.
8630Instruction *InstCombiner::transformZExtICmp(ICmpInst *ICI, Instruction &CI,
8631 bool DoXform) {
8632 // If we are just checking for a icmp eq of a single bit and zext'ing it
8633 // to an integer, then shift the bit to the appropriate place and then
8634 // cast to integer to avoid the comparison.
8635 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
8636 const APInt &Op1CV = Op1C->getValue();
8637
8638 // zext (x <s 0) to i32 --> x>>u31 true if signbit set.
8639 // zext (x >s -1) to i32 --> (x>>u31)^1 true if signbit clear.
8640 if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
8641 (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())) {
8642 if (!DoXform) return ICI;
8643
8644 Value *In = ICI->getOperand(0);
Owen Andersoneed707b2009-07-24 23:12:02 +00008645 Value *Sh = ConstantInt::get(In->getType(),
Dan Gohman6de29f82009-06-15 22:12:54 +00008646 In->getType()->getScalarSizeInBits()-1);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008647 In = Builder->CreateLShr(In, Sh, In->getName()+".lobit");
Evan Chengb98a10e2008-03-24 00:21:34 +00008648 if (In->getType() != CI.getType())
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008649 In = Builder->CreateIntCast(In, CI.getType(), false/*ZExt*/, "tmp");
Evan Chengb98a10e2008-03-24 00:21:34 +00008650
8651 if (ICI->getPredicate() == ICmpInst::ICMP_SGT) {
Owen Andersoneed707b2009-07-24 23:12:02 +00008652 Constant *One = ConstantInt::get(In->getType(), 1);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008653 In = Builder->CreateXor(In, One, In->getName()+".not");
Evan Chengb98a10e2008-03-24 00:21:34 +00008654 }
8655
8656 return ReplaceInstUsesWith(CI, In);
8657 }
8658
8659
8660
8661 // zext (X == 0) to i32 --> X^1 iff X has only the low bit set.
8662 // zext (X == 0) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8663 // zext (X == 1) to i32 --> X iff X has only the low bit set.
8664 // zext (X == 2) to i32 --> X>>1 iff X has only the 2nd bit set.
8665 // zext (X != 0) to i32 --> X iff X has only the low bit set.
8666 // zext (X != 0) to i32 --> X>>1 iff X has only the 2nd bit set.
8667 // zext (X != 1) to i32 --> X^1 iff X has only the low bit set.
8668 // zext (X != 2) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8669 if ((Op1CV == 0 || Op1CV.isPowerOf2()) &&
8670 // This only works for EQ and NE
8671 ICI->isEquality()) {
8672 // If Op1C some other power of two, convert:
8673 uint32_t BitWidth = Op1C->getType()->getBitWidth();
8674 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
8675 APInt TypeMask(APInt::getAllOnesValue(BitWidth));
8676 ComputeMaskedBits(ICI->getOperand(0), TypeMask, KnownZero, KnownOne);
8677
8678 APInt KnownZeroMask(~KnownZero);
8679 if (KnownZeroMask.isPowerOf2()) { // Exactly 1 possible 1?
8680 if (!DoXform) return ICI;
8681
8682 bool isNE = ICI->getPredicate() == ICmpInst::ICMP_NE;
8683 if (Op1CV != 0 && (Op1CV != KnownZeroMask)) {
8684 // (X&4) == 2 --> false
8685 // (X&4) != 2 --> true
Chris Lattner4de84762010-01-04 07:02:48 +00008686 Constant *Res = ConstantInt::get(Type::getInt1Ty(CI.getContext()),
8687 isNE);
Owen Andersonbaf3c402009-07-29 18:55:55 +00008688 Res = ConstantExpr::getZExt(Res, CI.getType());
Evan Chengb98a10e2008-03-24 00:21:34 +00008689 return ReplaceInstUsesWith(CI, Res);
8690 }
8691
8692 uint32_t ShiftAmt = KnownZeroMask.logBase2();
8693 Value *In = ICI->getOperand(0);
8694 if (ShiftAmt) {
8695 // Perform a logical shr by shiftamt.
8696 // Insert the shift to put the result in the low bit.
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008697 In = Builder->CreateLShr(In, ConstantInt::get(In->getType(),ShiftAmt),
8698 In->getName()+".lobit");
Evan Chengb98a10e2008-03-24 00:21:34 +00008699 }
8700
8701 if ((Op1CV != 0) == isNE) { // Toggle the low bit.
Owen Andersoneed707b2009-07-24 23:12:02 +00008702 Constant *One = ConstantInt::get(In->getType(), 1);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008703 In = Builder->CreateXor(In, One, "tmp");
Evan Chengb98a10e2008-03-24 00:21:34 +00008704 }
8705
8706 if (CI.getType() == In->getType())
8707 return ReplaceInstUsesWith(CI, In);
8708 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008709 return CastInst::CreateIntegerCast(In, CI.getType(), false/*ZExt*/);
Evan Chengb98a10e2008-03-24 00:21:34 +00008710 }
8711 }
8712 }
8713
Nick Lewycky55bd8bd2009-11-23 03:17:33 +00008714 // icmp ne A, B is equal to xor A, B when A and B only really have one bit.
8715 // It is also profitable to transform icmp eq into not(xor(A, B)) because that
8716 // may lead to additional simplifications.
8717 if (ICI->isEquality() && CI.getType() == ICI->getOperand(0)->getType()) {
8718 if (const IntegerType *ITy = dyn_cast<IntegerType>(CI.getType())) {
8719 uint32_t BitWidth = ITy->getBitWidth();
Nick Lewycky83e8ec72009-12-05 05:00:00 +00008720 Value *LHS = ICI->getOperand(0);
8721 Value *RHS = ICI->getOperand(1);
Nick Lewycky55bd8bd2009-11-23 03:17:33 +00008722
Nick Lewycky83e8ec72009-12-05 05:00:00 +00008723 APInt KnownZeroLHS(BitWidth, 0), KnownOneLHS(BitWidth, 0);
8724 APInt KnownZeroRHS(BitWidth, 0), KnownOneRHS(BitWidth, 0);
8725 APInt TypeMask(APInt::getAllOnesValue(BitWidth));
8726 ComputeMaskedBits(LHS, TypeMask, KnownZeroLHS, KnownOneLHS);
8727 ComputeMaskedBits(RHS, TypeMask, KnownZeroRHS, KnownOneRHS);
Nick Lewycky55bd8bd2009-11-23 03:17:33 +00008728
Nick Lewycky83e8ec72009-12-05 05:00:00 +00008729 if (KnownZeroLHS == KnownZeroRHS && KnownOneLHS == KnownOneRHS) {
8730 APInt KnownBits = KnownZeroLHS | KnownOneLHS;
8731 APInt UnknownBit = ~KnownBits;
8732 if (UnknownBit.countPopulation() == 1) {
Nick Lewycky55bd8bd2009-11-23 03:17:33 +00008733 if (!DoXform) return ICI;
8734
Nick Lewycky83e8ec72009-12-05 05:00:00 +00008735 Value *Result = Builder->CreateXor(LHS, RHS);
8736
8737 // Mask off any bits that are set and won't be shifted away.
8738 if (KnownOneLHS.uge(UnknownBit))
8739 Result = Builder->CreateAnd(Result,
8740 ConstantInt::get(ITy, UnknownBit));
8741
8742 // Shift the bit we're testing down to the lsb.
8743 Result = Builder->CreateLShr(
8744 Result, ConstantInt::get(ITy, UnknownBit.countTrailingZeros()));
8745
Nick Lewycky55bd8bd2009-11-23 03:17:33 +00008746 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
Nick Lewycky83e8ec72009-12-05 05:00:00 +00008747 Result = Builder->CreateXor(Result, ConstantInt::get(ITy, 1));
8748 Result->takeName(ICI);
8749 return ReplaceInstUsesWith(CI, Result);
Nick Lewycky55bd8bd2009-11-23 03:17:33 +00008750 }
8751 }
8752 }
8753 }
8754
Evan Chengb98a10e2008-03-24 00:21:34 +00008755 return 0;
8756}
8757
Chris Lattner8a9f5712007-04-11 06:57:46 +00008758Instruction *InstCombiner::visitZExt(ZExtInst &CI) {
Chris Lattnerdffbef02010-01-04 06:23:24 +00008759 // If one of the common conversion will work, do it.
Reid Spencer3da59db2006-11-27 01:05:10 +00008760 if (Instruction *Result = commonIntCastTransforms(CI))
8761 return Result;
8762
8763 Value *Src = CI.getOperand(0);
8764
Chris Lattnera84f47c2009-02-17 20:47:23 +00008765 // If this is a TRUNC followed by a ZEXT then we are dealing with integral
8766 // types and if the sizes are just right we can convert this into a logical
8767 // 'and' which will be much cheaper than the pair of casts.
8768 if (TruncInst *CSrc = dyn_cast<TruncInst>(Src)) { // A->B->C cast
8769 // Get the sizes of the types involved. We know that the intermediate type
8770 // will be smaller than A or C, but don't know the relation between A and C.
8771 Value *A = CSrc->getOperand(0);
Dan Gohman6de29f82009-06-15 22:12:54 +00008772 unsigned SrcSize = A->getType()->getScalarSizeInBits();
8773 unsigned MidSize = CSrc->getType()->getScalarSizeInBits();
8774 unsigned DstSize = CI.getType()->getScalarSizeInBits();
Chris Lattnera84f47c2009-02-17 20:47:23 +00008775 // If we're actually extending zero bits, then if
8776 // SrcSize < DstSize: zext(a & mask)
8777 // SrcSize == DstSize: a & mask
8778 // SrcSize > DstSize: trunc(a) & mask
8779 if (SrcSize < DstSize) {
8780 APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
Owen Andersoneed707b2009-07-24 23:12:02 +00008781 Constant *AndConst = ConstantInt::get(A->getType(), AndValue);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008782 Value *And = Builder->CreateAnd(A, AndConst, CSrc->getName()+".mask");
Chris Lattnera84f47c2009-02-17 20:47:23 +00008783 return new ZExtInst(And, CI.getType());
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008784 }
8785
8786 if (SrcSize == DstSize) {
Chris Lattnera84f47c2009-02-17 20:47:23 +00008787 APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
Owen Andersoneed707b2009-07-24 23:12:02 +00008788 return BinaryOperator::CreateAnd(A, ConstantInt::get(A->getType(),
Dan Gohman6de29f82009-06-15 22:12:54 +00008789 AndValue));
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008790 }
8791 if (SrcSize > DstSize) {
8792 Value *Trunc = Builder->CreateTrunc(A, CI.getType(), "tmp");
Chris Lattnera84f47c2009-02-17 20:47:23 +00008793 APInt AndValue(APInt::getLowBitsSet(DstSize, MidSize));
Owen Andersond672ecb2009-07-03 00:17:18 +00008794 return BinaryOperator::CreateAnd(Trunc,
Owen Andersoneed707b2009-07-24 23:12:02 +00008795 ConstantInt::get(Trunc->getType(),
Dan Gohman6de29f82009-06-15 22:12:54 +00008796 AndValue));
Reid Spencer3da59db2006-11-27 01:05:10 +00008797 }
8798 }
8799
Evan Chengb98a10e2008-03-24 00:21:34 +00008800 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src))
8801 return transformZExtICmp(ICI, CI);
Chris Lattnera2e2c9b2007-04-11 06:53:04 +00008802
Evan Chengb98a10e2008-03-24 00:21:34 +00008803 BinaryOperator *SrcI = dyn_cast<BinaryOperator>(Src);
8804 if (SrcI && SrcI->getOpcode() == Instruction::Or) {
8805 // zext (or icmp, icmp) --> or (zext icmp), (zext icmp) if at least one
8806 // of the (zext icmp) will be transformed.
8807 ICmpInst *LHS = dyn_cast<ICmpInst>(SrcI->getOperand(0));
8808 ICmpInst *RHS = dyn_cast<ICmpInst>(SrcI->getOperand(1));
8809 if (LHS && RHS && LHS->hasOneUse() && RHS->hasOneUse() &&
8810 (transformZExtICmp(LHS, CI, false) ||
8811 transformZExtICmp(RHS, CI, false))) {
Chris Lattner2345d1d2009-08-30 20:01:10 +00008812 Value *LCast = Builder->CreateZExt(LHS, CI.getType(), LHS->getName());
8813 Value *RCast = Builder->CreateZExt(RHS, CI.getType(), RHS->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008814 return BinaryOperator::Create(Instruction::Or, LCast, RCast);
Chris Lattner66bc3252007-04-11 05:45:39 +00008815 }
Evan Chengb98a10e2008-03-24 00:21:34 +00008816 }
8817
Dan Gohmanfd3daa72009-06-18 16:30:21 +00008818 // zext(trunc(t) & C) -> (t & zext(C)).
Dan Gohmana392c782009-06-17 23:17:05 +00008819 if (SrcI && SrcI->getOpcode() == Instruction::And && SrcI->hasOneUse())
8820 if (ConstantInt *C = dyn_cast<ConstantInt>(SrcI->getOperand(1)))
8821 if (TruncInst *TI = dyn_cast<TruncInst>(SrcI->getOperand(0))) {
8822 Value *TI0 = TI->getOperand(0);
Dan Gohmanfd3daa72009-06-18 16:30:21 +00008823 if (TI0->getType() == CI.getType())
8824 return
8825 BinaryOperator::CreateAnd(TI0,
Owen Andersonbaf3c402009-07-29 18:55:55 +00008826 ConstantExpr::getZExt(C, CI.getType()));
Dan Gohmana392c782009-06-17 23:17:05 +00008827 }
8828
Dan Gohmanfd3daa72009-06-18 16:30:21 +00008829 // zext((trunc(t) & C) ^ C) -> ((t & zext(C)) ^ zext(C)).
8830 if (SrcI && SrcI->getOpcode() == Instruction::Xor && SrcI->hasOneUse())
8831 if (ConstantInt *C = dyn_cast<ConstantInt>(SrcI->getOperand(1)))
8832 if (BinaryOperator *And = dyn_cast<BinaryOperator>(SrcI->getOperand(0)))
8833 if (And->getOpcode() == Instruction::And && And->hasOneUse() &&
8834 And->getOperand(1) == C)
8835 if (TruncInst *TI = dyn_cast<TruncInst>(And->getOperand(0))) {
8836 Value *TI0 = TI->getOperand(0);
8837 if (TI0->getType() == CI.getType()) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00008838 Constant *ZC = ConstantExpr::getZExt(C, CI.getType());
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008839 Value *NewAnd = Builder->CreateAnd(TI0, ZC, "tmp");
Dan Gohmanfd3daa72009-06-18 16:30:21 +00008840 return BinaryOperator::CreateXor(NewAnd, ZC);
8841 }
8842 }
8843
Reid Spencer3da59db2006-11-27 01:05:10 +00008844 return 0;
8845}
8846
Chris Lattner8a9f5712007-04-11 06:57:46 +00008847Instruction *InstCombiner::visitSExt(SExtInst &CI) {
Chris Lattnerba417832007-04-11 06:12:58 +00008848 if (Instruction *I = commonIntCastTransforms(CI))
8849 return I;
8850
Chris Lattner8a9f5712007-04-11 06:57:46 +00008851 Value *Src = CI.getOperand(0);
8852
Dan Gohman1975d032008-10-30 20:40:10 +00008853 // Canonicalize sign-extend from i1 to a select.
Chris Lattner4de84762010-01-04 07:02:48 +00008854 if (Src->getType() == Type::getInt1Ty(CI.getContext()))
Dan Gohman1975d032008-10-30 20:40:10 +00008855 return SelectInst::Create(Src,
Owen Andersona7235ea2009-07-31 20:28:14 +00008856 Constant::getAllOnesValue(CI.getType()),
8857 Constant::getNullValue(CI.getType()));
Dan Gohmanf35c8822008-05-20 21:01:12 +00008858
8859 // See if the value being truncated is already sign extended. If so, just
8860 // eliminate the trunc/sext pair.
Dan Gohmanca178902009-07-17 20:47:02 +00008861 if (Operator::getOpcode(Src) == Instruction::Trunc) {
Dan Gohmanf35c8822008-05-20 21:01:12 +00008862 Value *Op = cast<User>(Src)->getOperand(0);
Dan Gohman6de29f82009-06-15 22:12:54 +00008863 unsigned OpBits = Op->getType()->getScalarSizeInBits();
8864 unsigned MidBits = Src->getType()->getScalarSizeInBits();
8865 unsigned DestBits = CI.getType()->getScalarSizeInBits();
Dan Gohmanf35c8822008-05-20 21:01:12 +00008866 unsigned NumSignBits = ComputeNumSignBits(Op);
8867
8868 if (OpBits == DestBits) {
8869 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign
8870 // bits, it is already ready.
8871 if (NumSignBits > DestBits-MidBits)
8872 return ReplaceInstUsesWith(CI, Op);
8873 } else if (OpBits < DestBits) {
8874 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign
8875 // bits, just sext from i32.
8876 if (NumSignBits > OpBits-MidBits)
8877 return new SExtInst(Op, CI.getType(), "tmp");
8878 } else {
8879 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign
8880 // bits, just truncate to i32.
8881 if (NumSignBits > OpBits-MidBits)
8882 return new TruncInst(Op, CI.getType(), "tmp");
8883 }
8884 }
Chris Lattner46bbad22008-08-06 07:35:52 +00008885
8886 // If the input is a shl/ashr pair of a same constant, then this is a sign
8887 // extension from a smaller value. If we could trust arbitrary bitwidth
8888 // integers, we could turn this into a truncate to the smaller bit and then
8889 // use a sext for the whole extension. Since we don't, look deeper and check
8890 // for a truncate. If the source and dest are the same type, eliminate the
8891 // trunc and extend and just do shifts. For example, turn:
8892 // %a = trunc i32 %i to i8
8893 // %b = shl i8 %a, 6
8894 // %c = ashr i8 %b, 6
8895 // %d = sext i8 %c to i32
8896 // into:
8897 // %a = shl i32 %i, 30
8898 // %d = ashr i32 %a, 30
8899 Value *A = 0;
8900 ConstantInt *BA = 0, *CA = 0;
8901 if (match(Src, m_AShr(m_Shl(m_Value(A), m_ConstantInt(BA)),
Dan Gohman4ae51262009-08-12 16:23:25 +00008902 m_ConstantInt(CA))) &&
Chris Lattner46bbad22008-08-06 07:35:52 +00008903 BA == CA && isa<TruncInst>(A)) {
8904 Value *I = cast<TruncInst>(A)->getOperand(0);
8905 if (I->getType() == CI.getType()) {
Dan Gohman6de29f82009-06-15 22:12:54 +00008906 unsigned MidSize = Src->getType()->getScalarSizeInBits();
8907 unsigned SrcDstSize = CI.getType()->getScalarSizeInBits();
Chris Lattner46bbad22008-08-06 07:35:52 +00008908 unsigned ShAmt = CA->getZExtValue()+SrcDstSize-MidSize;
Owen Andersoneed707b2009-07-24 23:12:02 +00008909 Constant *ShAmtV = ConstantInt::get(CI.getType(), ShAmt);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008910 I = Builder->CreateShl(I, ShAmtV, CI.getName());
Chris Lattner46bbad22008-08-06 07:35:52 +00008911 return BinaryOperator::CreateAShr(I, ShAmtV);
8912 }
8913 }
8914
Chris Lattnerba417832007-04-11 06:12:58 +00008915 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00008916}
8917
Chris Lattnerb7530652008-01-27 05:29:54 +00008918/// FitsInFPType - Return a Constant* for the specified FP constant if it fits
8919/// in the specified FP type without changing its value.
Chris Lattner4de84762010-01-04 07:02:48 +00008920static Constant *FitsInFPType(ConstantFP *CFP, const fltSemantics &Sem) {
Dale Johannesen23a98552008-10-09 23:00:39 +00008921 bool losesInfo;
Chris Lattnerb7530652008-01-27 05:29:54 +00008922 APFloat F = CFP->getValueAPF();
Dale Johannesen23a98552008-10-09 23:00:39 +00008923 (void)F.convert(Sem, APFloat::rmNearestTiesToEven, &losesInfo);
8924 if (!losesInfo)
Chris Lattner4de84762010-01-04 07:02:48 +00008925 return ConstantFP::get(CFP->getContext(), F);
Chris Lattnerb7530652008-01-27 05:29:54 +00008926 return 0;
8927}
8928
8929/// LookThroughFPExtensions - If this is an fp extension instruction, look
8930/// through it until we get the source value.
Chris Lattner4de84762010-01-04 07:02:48 +00008931static Value *LookThroughFPExtensions(Value *V) {
Chris Lattnerb7530652008-01-27 05:29:54 +00008932 if (Instruction *I = dyn_cast<Instruction>(V))
8933 if (I->getOpcode() == Instruction::FPExt)
Chris Lattner4de84762010-01-04 07:02:48 +00008934 return LookThroughFPExtensions(I->getOperand(0));
Chris Lattnerb7530652008-01-27 05:29:54 +00008935
8936 // If this value is a constant, return the constant in the smallest FP type
8937 // that can accurately represent it. This allows us to turn
8938 // (float)((double)X+2.0) into x+2.0f.
8939 if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
Chris Lattner4de84762010-01-04 07:02:48 +00008940 if (CFP->getType() == Type::getPPC_FP128Ty(V->getContext()))
Chris Lattnerb7530652008-01-27 05:29:54 +00008941 return V; // No constant folding of this.
8942 // See if the value can be truncated to float and then reextended.
Chris Lattner4de84762010-01-04 07:02:48 +00008943 if (Value *V = FitsInFPType(CFP, APFloat::IEEEsingle))
Chris Lattnerb7530652008-01-27 05:29:54 +00008944 return V;
Chris Lattner4de84762010-01-04 07:02:48 +00008945 if (CFP->getType() == Type::getDoubleTy(V->getContext()))
Chris Lattnerb7530652008-01-27 05:29:54 +00008946 return V; // Won't shrink.
Chris Lattner4de84762010-01-04 07:02:48 +00008947 if (Value *V = FitsInFPType(CFP, APFloat::IEEEdouble))
Chris Lattnerb7530652008-01-27 05:29:54 +00008948 return V;
8949 // Don't try to shrink to various long double types.
8950 }
8951
8952 return V;
8953}
8954
8955Instruction *InstCombiner::visitFPTrunc(FPTruncInst &CI) {
8956 if (Instruction *I = commonCastTransforms(CI))
8957 return I;
8958
Dan Gohmanae3a0be2009-06-04 22:49:04 +00008959 // If we have fptrunc(fadd (fpextend x), (fpextend y)), where x and y are
Chris Lattnerb7530652008-01-27 05:29:54 +00008960 // smaller than the destination type, we can eliminate the truncate by doing
Dan Gohmanae3a0be2009-06-04 22:49:04 +00008961 // the add as the smaller type. This applies to fadd/fsub/fmul/fdiv as well as
Chris Lattnerb7530652008-01-27 05:29:54 +00008962 // many builtins (sqrt, etc).
8963 BinaryOperator *OpI = dyn_cast<BinaryOperator>(CI.getOperand(0));
8964 if (OpI && OpI->hasOneUse()) {
8965 switch (OpI->getOpcode()) {
8966 default: break;
Dan Gohmanae3a0be2009-06-04 22:49:04 +00008967 case Instruction::FAdd:
8968 case Instruction::FSub:
8969 case Instruction::FMul:
Chris Lattnerb7530652008-01-27 05:29:54 +00008970 case Instruction::FDiv:
8971 case Instruction::FRem:
8972 const Type *SrcTy = OpI->getType();
Chris Lattner4de84762010-01-04 07:02:48 +00008973 Value *LHSTrunc = LookThroughFPExtensions(OpI->getOperand(0));
8974 Value *RHSTrunc = LookThroughFPExtensions(OpI->getOperand(1));
Chris Lattnerb7530652008-01-27 05:29:54 +00008975 if (LHSTrunc->getType() != SrcTy &&
8976 RHSTrunc->getType() != SrcTy) {
Dan Gohman6de29f82009-06-15 22:12:54 +00008977 unsigned DstSize = CI.getType()->getScalarSizeInBits();
Chris Lattnerb7530652008-01-27 05:29:54 +00008978 // If the source types were both smaller than the destination type of
8979 // the cast, do this xform.
Dan Gohman6de29f82009-06-15 22:12:54 +00008980 if (LHSTrunc->getType()->getScalarSizeInBits() <= DstSize &&
8981 RHSTrunc->getType()->getScalarSizeInBits() <= DstSize) {
Chris Lattner2345d1d2009-08-30 20:01:10 +00008982 LHSTrunc = Builder->CreateFPExt(LHSTrunc, CI.getType());
8983 RHSTrunc = Builder->CreateFPExt(RHSTrunc, CI.getType());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008984 return BinaryOperator::Create(OpI->getOpcode(), LHSTrunc, RHSTrunc);
Chris Lattnerb7530652008-01-27 05:29:54 +00008985 }
8986 }
8987 break;
8988 }
8989 }
8990 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00008991}
8992
8993Instruction *InstCombiner::visitFPExt(CastInst &CI) {
8994 return commonCastTransforms(CI);
8995}
8996
Chris Lattner0c7a9a02008-05-19 20:25:04 +00008997Instruction *InstCombiner::visitFPToUI(FPToUIInst &FI) {
Chris Lattner5af5f462008-08-06 05:13:06 +00008998 Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
8999 if (OpI == 0)
9000 return commonCastTransforms(FI);
9001
9002 // fptoui(uitofp(X)) --> X
9003 // fptoui(sitofp(X)) --> X
9004 // This is safe if the intermediate type has enough bits in its mantissa to
9005 // accurately represent all values of X. For example, do not do this with
9006 // i64->float->i64. This is also safe for sitofp case, because any negative
9007 // 'X' value would cause an undefined result for the fptoui.
9008 if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
9009 OpI->getOperand(0)->getType() == FI.getType() &&
Dan Gohman6de29f82009-06-15 22:12:54 +00009010 (int)FI.getType()->getScalarSizeInBits() < /*extra bit for sign */
Chris Lattner5af5f462008-08-06 05:13:06 +00009011 OpI->getType()->getFPMantissaWidth())
9012 return ReplaceInstUsesWith(FI, OpI->getOperand(0));
Chris Lattner0c7a9a02008-05-19 20:25:04 +00009013
9014 return commonCastTransforms(FI);
Reid Spencer3da59db2006-11-27 01:05:10 +00009015}
9016
Chris Lattner0c7a9a02008-05-19 20:25:04 +00009017Instruction *InstCombiner::visitFPToSI(FPToSIInst &FI) {
Chris Lattner5af5f462008-08-06 05:13:06 +00009018 Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
9019 if (OpI == 0)
9020 return commonCastTransforms(FI);
9021
9022 // fptosi(sitofp(X)) --> X
9023 // fptosi(uitofp(X)) --> X
9024 // This is safe if the intermediate type has enough bits in its mantissa to
9025 // accurately represent all values of X. For example, do not do this with
9026 // i64->float->i64. This is also safe for sitofp case, because any negative
9027 // 'X' value would cause an undefined result for the fptoui.
9028 if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
9029 OpI->getOperand(0)->getType() == FI.getType() &&
Dan Gohman6de29f82009-06-15 22:12:54 +00009030 (int)FI.getType()->getScalarSizeInBits() <=
Chris Lattner5af5f462008-08-06 05:13:06 +00009031 OpI->getType()->getFPMantissaWidth())
9032 return ReplaceInstUsesWith(FI, OpI->getOperand(0));
Chris Lattner0c7a9a02008-05-19 20:25:04 +00009033
9034 return commonCastTransforms(FI);
Reid Spencer3da59db2006-11-27 01:05:10 +00009035}
9036
9037Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
9038 return commonCastTransforms(CI);
9039}
9040
9041Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
9042 return commonCastTransforms(CI);
9043}
9044
Chris Lattnera0e69692009-03-24 18:35:40 +00009045Instruction *InstCombiner::visitPtrToInt(PtrToIntInst &CI) {
9046 // If the destination integer type is smaller than the intptr_t type for
9047 // this target, do a ptrtoint to intptr_t then do a trunc. This allows the
9048 // trunc to be exposed to other transforms. Don't do this for extending
9049 // ptrtoint's, because we don't know if the target sign or zero extends its
9050 // pointers.
Dan Gohmance9fe9f2009-07-21 23:21:54 +00009051 if (TD &&
9052 CI.getType()->getScalarSizeInBits() < TD->getPointerSizeInBits()) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +00009053 Value *P = Builder->CreatePtrToInt(CI.getOperand(0),
9054 TD->getIntPtrType(CI.getContext()),
9055 "tmp");
Chris Lattnera0e69692009-03-24 18:35:40 +00009056 return new TruncInst(P, CI.getType());
9057 }
9058
Chris Lattnerd3e28342007-04-27 17:44:50 +00009059 return commonPointerCastTransforms(CI);
Reid Spencer3da59db2006-11-27 01:05:10 +00009060}
9061
Chris Lattnerf9d9e452008-01-08 07:23:51 +00009062Instruction *InstCombiner::visitIntToPtr(IntToPtrInst &CI) {
Chris Lattnera0e69692009-03-24 18:35:40 +00009063 // If the source integer type is larger than the intptr_t type for
9064 // this target, do a trunc to the intptr_t type, then inttoptr of it. This
9065 // allows the trunc to be exposed to other transforms. Don't do this for
9066 // extending inttoptr's, because we don't know if the target sign or zero
9067 // extends to pointers.
Chris Lattnerf925cbd2009-08-30 18:50:58 +00009068 if (TD && CI.getOperand(0)->getType()->getScalarSizeInBits() >
Chris Lattnera0e69692009-03-24 18:35:40 +00009069 TD->getPointerSizeInBits()) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +00009070 Value *P = Builder->CreateTrunc(CI.getOperand(0),
9071 TD->getIntPtrType(CI.getContext()), "tmp");
Chris Lattnera0e69692009-03-24 18:35:40 +00009072 return new IntToPtrInst(P, CI.getType());
9073 }
9074
Chris Lattnerf9d9e452008-01-08 07:23:51 +00009075 if (Instruction *I = commonCastTransforms(CI))
9076 return I;
Chris Lattnerf9d9e452008-01-08 07:23:51 +00009077
Chris Lattnerf9d9e452008-01-08 07:23:51 +00009078 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00009079}
9080
Chris Lattnerd3e28342007-04-27 17:44:50 +00009081Instruction *InstCombiner::visitBitCast(BitCastInst &CI) {
Reid Spencer3da59db2006-11-27 01:05:10 +00009082 // If the operands are integer typed then apply the integer transforms,
9083 // otherwise just apply the common ones.
9084 Value *Src = CI.getOperand(0);
9085 const Type *SrcTy = Src->getType();
9086 const Type *DestTy = CI.getType();
9087
Eli Friedman7e25d452009-07-13 20:53:00 +00009088 if (isa<PointerType>(SrcTy)) {
Chris Lattnerd3e28342007-04-27 17:44:50 +00009089 if (Instruction *I = commonPointerCastTransforms(CI))
9090 return I;
Reid Spencer3da59db2006-11-27 01:05:10 +00009091 } else {
9092 if (Instruction *Result = commonCastTransforms(CI))
9093 return Result;
9094 }
9095
9096
9097 // Get rid of casts from one type to the same type. These are useless and can
9098 // be replaced by the operand.
9099 if (DestTy == Src->getType())
9100 return ReplaceInstUsesWith(CI, Src);
9101
Reid Spencer3da59db2006-11-27 01:05:10 +00009102 if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
Chris Lattnerd3e28342007-04-27 17:44:50 +00009103 const PointerType *SrcPTy = cast<PointerType>(SrcTy);
9104 const Type *DstElTy = DstPTy->getElementType();
9105 const Type *SrcElTy = SrcPTy->getElementType();
9106
Nate Begeman83ad90a2008-03-31 00:22:16 +00009107 // If the address spaces don't match, don't eliminate the bitcast, which is
9108 // required for changing types.
9109 if (SrcPTy->getAddressSpace() != DstPTy->getAddressSpace())
9110 return 0;
9111
Victor Hernandez83d63912009-09-18 22:35:49 +00009112 // If we are casting a alloca to a pointer to a type of the same
Chris Lattnerd3e28342007-04-27 17:44:50 +00009113 // size, rewrite the allocation instruction to allocate the "right" type.
Victor Hernandez83d63912009-09-18 22:35:49 +00009114 // There is no need to modify malloc calls because it is their bitcast that
9115 // needs to be cleaned up.
Victor Hernandez7b929da2009-10-23 21:09:37 +00009116 if (AllocaInst *AI = dyn_cast<AllocaInst>(Src))
Chris Lattnerd3e28342007-04-27 17:44:50 +00009117 if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
9118 return V;
9119
Chris Lattnerd717c182007-05-05 22:32:24 +00009120 // If the source and destination are pointers, and this cast is equivalent
9121 // to a getelementptr X, 0, 0, 0... turn it into the appropriate gep.
Chris Lattnerd3e28342007-04-27 17:44:50 +00009122 // This can enhance SROA and other transforms that want type-safe pointers.
Chris Lattner4de84762010-01-04 07:02:48 +00009123 Constant *ZeroUInt =
9124 Constant::getNullValue(Type::getInt32Ty(CI.getContext()));
Chris Lattnerd3e28342007-04-27 17:44:50 +00009125 unsigned NumZeros = 0;
9126 while (SrcElTy != DstElTy &&
9127 isa<CompositeType>(SrcElTy) && !isa<PointerType>(SrcElTy) &&
9128 SrcElTy->getNumContainedTypes() /* not "{}" */) {
9129 SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
9130 ++NumZeros;
9131 }
Chris Lattner4e998b22004-09-29 05:07:12 +00009132
Chris Lattnerd3e28342007-04-27 17:44:50 +00009133 // If we found a path from the src to dest, create the getelementptr now.
9134 if (SrcElTy == DstElTy) {
9135 SmallVector<Value*, 8> Idxs(NumZeros+1, ZeroUInt);
Chris Lattner4de84762010-01-04 07:02:48 +00009136 return GetElementPtrInst::CreateInBounds(Src, Idxs.begin(), Idxs.end(),"",
Dan Gohmanf8dbee72009-09-07 23:54:19 +00009137 ((Instruction*) NULL));
Chris Lattner9fb92132006-04-12 18:09:35 +00009138 }
Reid Spencer3da59db2006-11-27 01:05:10 +00009139 }
Chris Lattner24c8e382003-07-24 17:35:25 +00009140
Eli Friedman2451a642009-07-18 23:06:53 +00009141 if (const VectorType *DestVTy = dyn_cast<VectorType>(DestTy)) {
9142 if (DestVTy->getNumElements() == 1) {
9143 if (!isa<VectorType>(SrcTy)) {
Chris Lattner2345d1d2009-08-30 20:01:10 +00009144 Value *Elem = Builder->CreateBitCast(Src, DestVTy->getElementType());
Owen Anderson9e9a0d52009-07-30 23:03:37 +00009145 return InsertElementInst::Create(UndefValue::get(DestTy), Elem,
Chris Lattner4de84762010-01-04 07:02:48 +00009146 Constant::getNullValue(Type::getInt32Ty(CI.getContext())));
Eli Friedman2451a642009-07-18 23:06:53 +00009147 }
9148 // FIXME: Canonicalize bitcast(insertelement) -> insertelement(bitcast)
9149 }
9150 }
9151
9152 if (const VectorType *SrcVTy = dyn_cast<VectorType>(SrcTy)) {
9153 if (SrcVTy->getNumElements() == 1) {
9154 if (!isa<VectorType>(DestTy)) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +00009155 Value *Elem =
9156 Builder->CreateExtractElement(Src,
Chris Lattner4de84762010-01-04 07:02:48 +00009157 Constant::getNullValue(Type::getInt32Ty(CI.getContext())));
Eli Friedman2451a642009-07-18 23:06:53 +00009158 return CastInst::Create(Instruction::BitCast, Elem, DestTy);
9159 }
9160 }
9161 }
9162
Reid Spencer3da59db2006-11-27 01:05:10 +00009163 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
9164 if (SVI->hasOneUse()) {
9165 // Okay, we have (bitconvert (shuffle ..)). Check to see if this is
9166 // a bitconvert to a vector with the same # elts.
Reid Spencer9d6565a2007-02-15 02:26:10 +00009167 if (isa<VectorType>(DestTy) &&
Mon P Wangaeb06d22008-11-10 04:46:22 +00009168 cast<VectorType>(DestTy)->getNumElements() ==
9169 SVI->getType()->getNumElements() &&
9170 SVI->getType()->getNumElements() ==
9171 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements()) {
Reid Spencer3da59db2006-11-27 01:05:10 +00009172 CastInst *Tmp;
9173 // If either of the operands is a cast from CI.getType(), then
9174 // evaluating the shuffle in the casted destination's type will allow
9175 // us to eliminate at least one cast.
9176 if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) &&
9177 Tmp->getOperand(0)->getType() == DestTy) ||
9178 ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) &&
9179 Tmp->getOperand(0)->getType() == DestTy)) {
Chris Lattner2345d1d2009-08-30 20:01:10 +00009180 Value *LHS = Builder->CreateBitCast(SVI->getOperand(0), DestTy);
9181 Value *RHS = Builder->CreateBitCast(SVI->getOperand(1), DestTy);
Reid Spencer3da59db2006-11-27 01:05:10 +00009182 // Return a new shuffle vector. Use the same element ID's, as we
9183 // know the vector types match #elts.
9184 return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
Chris Lattner01575b72006-05-25 23:24:33 +00009185 }
9186 }
9187 }
9188 }
Chris Lattnerdd841ae2002-04-18 17:39:14 +00009189 return 0;
Chris Lattner8a2a3112001-12-14 16:52:21 +00009190}
9191
Chris Lattnere576b912004-04-09 23:46:01 +00009192/// GetSelectFoldableOperands - We want to turn code that looks like this:
9193/// %C = or %A, %B
9194/// %D = select %cond, %C, %A
9195/// into:
9196/// %C = select %cond, %B, 0
9197/// %D = or %A, %C
9198///
9199/// Assuming that the specified instruction is an operand to the select, return
9200/// a bitmask indicating which operands of this instruction are foldable if they
9201/// equal the other incoming value of the select.
9202///
9203static unsigned GetSelectFoldableOperands(Instruction *I) {
9204 switch (I->getOpcode()) {
9205 case Instruction::Add:
9206 case Instruction::Mul:
9207 case Instruction::And:
9208 case Instruction::Or:
9209 case Instruction::Xor:
9210 return 3; // Can fold through either operand.
9211 case Instruction::Sub: // Can only fold on the amount subtracted.
9212 case Instruction::Shl: // Can only fold on the shift amount.
Reid Spencer3822ff52006-11-08 06:47:33 +00009213 case Instruction::LShr:
9214 case Instruction::AShr:
Misha Brukmanfd939082005-04-21 23:48:37 +00009215 return 1;
Chris Lattnere576b912004-04-09 23:46:01 +00009216 default:
9217 return 0; // Cannot fold
9218 }
9219}
9220
9221/// GetSelectFoldableConstant - For the same transformation as the previous
9222/// function, return the identity constant that goes into the select.
Chris Lattner4de84762010-01-04 07:02:48 +00009223static Constant *GetSelectFoldableConstant(Instruction *I) {
Chris Lattnere576b912004-04-09 23:46:01 +00009224 switch (I->getOpcode()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00009225 default: llvm_unreachable("This cannot happen!");
Chris Lattnere576b912004-04-09 23:46:01 +00009226 case Instruction::Add:
9227 case Instruction::Sub:
9228 case Instruction::Or:
9229 case Instruction::Xor:
Chris Lattnere576b912004-04-09 23:46:01 +00009230 case Instruction::Shl:
Reid Spencer3822ff52006-11-08 06:47:33 +00009231 case Instruction::LShr:
9232 case Instruction::AShr:
Owen Andersona7235ea2009-07-31 20:28:14 +00009233 return Constant::getNullValue(I->getType());
Chris Lattnere576b912004-04-09 23:46:01 +00009234 case Instruction::And:
Owen Andersona7235ea2009-07-31 20:28:14 +00009235 return Constant::getAllOnesValue(I->getType());
Chris Lattnere576b912004-04-09 23:46:01 +00009236 case Instruction::Mul:
Owen Andersoneed707b2009-07-24 23:12:02 +00009237 return ConstantInt::get(I->getType(), 1);
Chris Lattnere576b912004-04-09 23:46:01 +00009238 }
9239}
9240
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009241/// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
9242/// have the same opcode and only one use each. Try to simplify this.
9243Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
9244 Instruction *FI) {
9245 if (TI->getNumOperands() == 1) {
9246 // If this is a non-volatile load or a cast from the same type,
9247 // merge.
Reid Spencer3da59db2006-11-27 01:05:10 +00009248 if (TI->isCast()) {
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009249 if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
9250 return 0;
9251 } else {
9252 return 0; // unknown unary op.
9253 }
Misha Brukmanfd939082005-04-21 23:48:37 +00009254
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009255 // Fold this by inserting a select from the input values.
Gabor Greif051a9502008-04-06 20:25:17 +00009256 SelectInst *NewSI = SelectInst::Create(SI.getCondition(), TI->getOperand(0),
Eric Christophera66297a2009-07-25 02:45:27 +00009257 FI->getOperand(0), SI.getName()+".v");
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009258 InsertNewInstBefore(NewSI, SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009259 return CastInst::Create(Instruction::CastOps(TI->getOpcode()), NewSI,
Reid Spencer3da59db2006-11-27 01:05:10 +00009260 TI->getType());
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009261 }
9262
Reid Spencer832254e2007-02-02 02:16:23 +00009263 // Only handle binary operators here.
9264 if (!isa<BinaryOperator>(TI))
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009265 return 0;
9266
9267 // Figure out if the operations have any operands in common.
9268 Value *MatchOp, *OtherOpT, *OtherOpF;
9269 bool MatchIsOpZero;
9270 if (TI->getOperand(0) == FI->getOperand(0)) {
9271 MatchOp = TI->getOperand(0);
9272 OtherOpT = TI->getOperand(1);
9273 OtherOpF = FI->getOperand(1);
9274 MatchIsOpZero = true;
9275 } else if (TI->getOperand(1) == FI->getOperand(1)) {
9276 MatchOp = TI->getOperand(1);
9277 OtherOpT = TI->getOperand(0);
9278 OtherOpF = FI->getOperand(0);
9279 MatchIsOpZero = false;
9280 } else if (!TI->isCommutative()) {
9281 return 0;
9282 } else if (TI->getOperand(0) == FI->getOperand(1)) {
9283 MatchOp = TI->getOperand(0);
9284 OtherOpT = TI->getOperand(1);
9285 OtherOpF = FI->getOperand(0);
9286 MatchIsOpZero = true;
9287 } else if (TI->getOperand(1) == FI->getOperand(0)) {
9288 MatchOp = TI->getOperand(1);
9289 OtherOpT = TI->getOperand(0);
9290 OtherOpF = FI->getOperand(1);
9291 MatchIsOpZero = true;
9292 } else {
9293 return 0;
9294 }
9295
9296 // If we reach here, they do have operations in common.
Gabor Greif051a9502008-04-06 20:25:17 +00009297 SelectInst *NewSI = SelectInst::Create(SI.getCondition(), OtherOpT,
9298 OtherOpF, SI.getName()+".v");
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009299 InsertNewInstBefore(NewSI, SI);
9300
9301 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
9302 if (MatchIsOpZero)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009303 return BinaryOperator::Create(BO->getOpcode(), MatchOp, NewSI);
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009304 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009305 return BinaryOperator::Create(BO->getOpcode(), NewSI, MatchOp);
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009306 }
Torok Edwinc23197a2009-07-14 16:55:14 +00009307 llvm_unreachable("Shouldn't get here");
Reid Spencera07cb7d2007-02-02 14:41:37 +00009308 return 0;
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009309}
9310
Evan Chengde621922009-03-31 20:42:45 +00009311static bool isSelect01(Constant *C1, Constant *C2) {
9312 ConstantInt *C1I = dyn_cast<ConstantInt>(C1);
9313 if (!C1I)
9314 return false;
9315 ConstantInt *C2I = dyn_cast<ConstantInt>(C2);
9316 if (!C2I)
9317 return false;
9318 return (C1I->isZero() || C1I->isOne()) && (C2I->isZero() || C2I->isOne());
9319}
9320
9321/// FoldSelectIntoOp - Try fold the select into one of the operands to
9322/// facilitate further optimization.
9323Instruction *InstCombiner::FoldSelectIntoOp(SelectInst &SI, Value *TrueVal,
9324 Value *FalseVal) {
9325 // See the comment above GetSelectFoldableOperands for a description of the
9326 // transformation we are doing here.
9327 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal)) {
9328 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
9329 !isa<Constant>(FalseVal)) {
9330 if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
9331 unsigned OpToFold = 0;
9332 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
9333 OpToFold = 1;
9334 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
9335 OpToFold = 2;
9336 }
9337
9338 if (OpToFold) {
Chris Lattner4de84762010-01-04 07:02:48 +00009339 Constant *C = GetSelectFoldableConstant(TVI);
Evan Chengde621922009-03-31 20:42:45 +00009340 Value *OOp = TVI->getOperand(2-OpToFold);
9341 // Avoid creating select between 2 constants unless it's selecting
9342 // between 0 and 1.
9343 if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
9344 Instruction *NewSel = SelectInst::Create(SI.getCondition(), OOp, C);
9345 InsertNewInstBefore(NewSel, SI);
9346 NewSel->takeName(TVI);
9347 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
9348 return BinaryOperator::Create(BO->getOpcode(), FalseVal, NewSel);
Torok Edwinc23197a2009-07-14 16:55:14 +00009349 llvm_unreachable("Unknown instruction!!");
Evan Chengde621922009-03-31 20:42:45 +00009350 }
9351 }
9352 }
9353 }
9354 }
9355
9356 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal)) {
9357 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
9358 !isa<Constant>(TrueVal)) {
9359 if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
9360 unsigned OpToFold = 0;
9361 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
9362 OpToFold = 1;
9363 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
9364 OpToFold = 2;
9365 }
9366
9367 if (OpToFold) {
Chris Lattner4de84762010-01-04 07:02:48 +00009368 Constant *C = GetSelectFoldableConstant(FVI);
Evan Chengde621922009-03-31 20:42:45 +00009369 Value *OOp = FVI->getOperand(2-OpToFold);
9370 // Avoid creating select between 2 constants unless it's selecting
9371 // between 0 and 1.
9372 if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
9373 Instruction *NewSel = SelectInst::Create(SI.getCondition(), C, OOp);
9374 InsertNewInstBefore(NewSel, SI);
9375 NewSel->takeName(FVI);
9376 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
9377 return BinaryOperator::Create(BO->getOpcode(), TrueVal, NewSel);
Torok Edwinc23197a2009-07-14 16:55:14 +00009378 llvm_unreachable("Unknown instruction!!");
Evan Chengde621922009-03-31 20:42:45 +00009379 }
9380 }
9381 }
9382 }
9383 }
9384
9385 return 0;
9386}
9387
Dan Gohman81b28ce2008-09-16 18:46:06 +00009388/// visitSelectInstWithICmp - Visit a SelectInst that has an
9389/// ICmpInst as its first operand.
9390///
9391Instruction *InstCombiner::visitSelectInstWithICmp(SelectInst &SI,
9392 ICmpInst *ICI) {
9393 bool Changed = false;
9394 ICmpInst::Predicate Pred = ICI->getPredicate();
9395 Value *CmpLHS = ICI->getOperand(0);
9396 Value *CmpRHS = ICI->getOperand(1);
9397 Value *TrueVal = SI.getTrueValue();
9398 Value *FalseVal = SI.getFalseValue();
9399
9400 // Check cases where the comparison is with a constant that
9401 // can be adjusted to fit the min/max idiom. We may edit ICI in
9402 // place here, so make sure the select is the only user.
9403 if (ICI->hasOneUse())
Dan Gohman1975d032008-10-30 20:40:10 +00009404 if (ConstantInt *CI = dyn_cast<ConstantInt>(CmpRHS)) {
Dan Gohman81b28ce2008-09-16 18:46:06 +00009405 switch (Pred) {
9406 default: break;
9407 case ICmpInst::ICMP_ULT:
9408 case ICmpInst::ICMP_SLT: {
9409 // X < MIN ? T : F --> F
9410 if (CI->isMinValue(Pred == ICmpInst::ICMP_SLT))
9411 return ReplaceInstUsesWith(SI, FalseVal);
9412 // X < C ? X : C-1 --> X > C-1 ? C-1 : X
Dan Gohman186a6362009-08-12 16:04:34 +00009413 Constant *AdjustedRHS = SubOne(CI);
Dan Gohman81b28ce2008-09-16 18:46:06 +00009414 if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
9415 (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
9416 Pred = ICmpInst::getSwappedPredicate(Pred);
9417 CmpRHS = AdjustedRHS;
9418 std::swap(FalseVal, TrueVal);
9419 ICI->setPredicate(Pred);
9420 ICI->setOperand(1, CmpRHS);
9421 SI.setOperand(1, TrueVal);
9422 SI.setOperand(2, FalseVal);
9423 Changed = true;
9424 }
9425 break;
9426 }
9427 case ICmpInst::ICMP_UGT:
9428 case ICmpInst::ICMP_SGT: {
9429 // X > MAX ? T : F --> F
9430 if (CI->isMaxValue(Pred == ICmpInst::ICMP_SGT))
9431 return ReplaceInstUsesWith(SI, FalseVal);
9432 // X > C ? X : C+1 --> X < C+1 ? C+1 : X
Dan Gohman186a6362009-08-12 16:04:34 +00009433 Constant *AdjustedRHS = AddOne(CI);
Dan Gohman81b28ce2008-09-16 18:46:06 +00009434 if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
9435 (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
9436 Pred = ICmpInst::getSwappedPredicate(Pred);
9437 CmpRHS = AdjustedRHS;
9438 std::swap(FalseVal, TrueVal);
9439 ICI->setPredicate(Pred);
9440 ICI->setOperand(1, CmpRHS);
9441 SI.setOperand(1, TrueVal);
9442 SI.setOperand(2, FalseVal);
9443 Changed = true;
9444 }
9445 break;
9446 }
9447 }
9448
Dan Gohman1975d032008-10-30 20:40:10 +00009449 // (x <s 0) ? -1 : 0 -> ashr x, 31 -> all ones if signed
9450 // (x >s -1) ? -1 : 0 -> ashr x, 31 -> all ones if not signed
Chris Lattnercb504b92008-11-16 05:38:51 +00009451 CmpInst::Predicate Pred = CmpInst::BAD_ICMP_PREDICATE;
Dan Gohman4ae51262009-08-12 16:23:25 +00009452 if (match(TrueVal, m_ConstantInt<-1>()) &&
9453 match(FalseVal, m_ConstantInt<0>()))
Chris Lattnercb504b92008-11-16 05:38:51 +00009454 Pred = ICI->getPredicate();
Dan Gohman4ae51262009-08-12 16:23:25 +00009455 else if (match(TrueVal, m_ConstantInt<0>()) &&
9456 match(FalseVal, m_ConstantInt<-1>()))
Chris Lattnercb504b92008-11-16 05:38:51 +00009457 Pred = CmpInst::getInversePredicate(ICI->getPredicate());
9458
Dan Gohman1975d032008-10-30 20:40:10 +00009459 if (Pred != CmpInst::BAD_ICMP_PREDICATE) {
9460 // If we are just checking for a icmp eq of a single bit and zext'ing it
9461 // to an integer, then shift the bit to the appropriate place and then
9462 // cast to integer to avoid the comparison.
9463 const APInt &Op1CV = CI->getValue();
9464
9465 // sext (x <s 0) to i32 --> x>>s31 true if signbit set.
9466 // sext (x >s -1) to i32 --> (x>>s31)^-1 true if signbit clear.
9467 if ((Pred == ICmpInst::ICMP_SLT && Op1CV == 0) ||
Chris Lattnercb504b92008-11-16 05:38:51 +00009468 (Pred == ICmpInst::ICMP_SGT && Op1CV.isAllOnesValue())) {
Dan Gohman1975d032008-10-30 20:40:10 +00009469 Value *In = ICI->getOperand(0);
Owen Andersoneed707b2009-07-24 23:12:02 +00009470 Value *Sh = ConstantInt::get(In->getType(),
Dan Gohman6de29f82009-06-15 22:12:54 +00009471 In->getType()->getScalarSizeInBits()-1);
Dan Gohman1975d032008-10-30 20:40:10 +00009472 In = InsertNewInstBefore(BinaryOperator::CreateAShr(In, Sh,
Eric Christophera66297a2009-07-25 02:45:27 +00009473 In->getName()+".lobit"),
Dan Gohman1975d032008-10-30 20:40:10 +00009474 *ICI);
Dan Gohman21440ac2008-11-02 00:17:33 +00009475 if (In->getType() != SI.getType())
9476 In = CastInst::CreateIntegerCast(In, SI.getType(),
Dan Gohman1975d032008-10-30 20:40:10 +00009477 true/*SExt*/, "tmp", ICI);
9478
9479 if (Pred == ICmpInst::ICMP_SGT)
Dan Gohman4ae51262009-08-12 16:23:25 +00009480 In = InsertNewInstBefore(BinaryOperator::CreateNot(In,
Dan Gohman1975d032008-10-30 20:40:10 +00009481 In->getName()+".not"), *ICI);
9482
9483 return ReplaceInstUsesWith(SI, In);
9484 }
9485 }
9486 }
9487
Dan Gohman81b28ce2008-09-16 18:46:06 +00009488 if (CmpLHS == TrueVal && CmpRHS == FalseVal) {
9489 // Transform (X == Y) ? X : Y -> Y
9490 if (Pred == ICmpInst::ICMP_EQ)
9491 return ReplaceInstUsesWith(SI, FalseVal);
9492 // Transform (X != Y) ? X : Y -> X
9493 if (Pred == ICmpInst::ICMP_NE)
9494 return ReplaceInstUsesWith(SI, TrueVal);
9495 /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
9496
9497 } else if (CmpLHS == FalseVal && CmpRHS == TrueVal) {
9498 // Transform (X == Y) ? Y : X -> X
9499 if (Pred == ICmpInst::ICMP_EQ)
9500 return ReplaceInstUsesWith(SI, FalseVal);
9501 // Transform (X != Y) ? Y : X -> Y
9502 if (Pred == ICmpInst::ICMP_NE)
9503 return ReplaceInstUsesWith(SI, TrueVal);
9504 /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
9505 }
Dan Gohman81b28ce2008-09-16 18:46:06 +00009506 return Changed ? &SI : 0;
9507}
9508
Chris Lattnerc6df8f42009-09-27 20:18:49 +00009509
Chris Lattner7f239582009-10-22 00:17:26 +00009510/// CanSelectOperandBeMappingIntoPredBlock - SI is a select whose condition is a
9511/// PHI node (but the two may be in different blocks). See if the true/false
9512/// values (V) are live in all of the predecessor blocks of the PHI. For
9513/// example, cases like this cannot be mapped:
9514///
9515/// X = phi [ C1, BB1], [C2, BB2]
9516/// Y = add
9517/// Z = select X, Y, 0
9518///
9519/// because Y is not live in BB1/BB2.
9520///
9521static bool CanSelectOperandBeMappingIntoPredBlock(const Value *V,
9522 const SelectInst &SI) {
9523 // If the value is a non-instruction value like a constant or argument, it
9524 // can always be mapped.
9525 const Instruction *I = dyn_cast<Instruction>(V);
9526 if (I == 0) return true;
9527
9528 // If V is a PHI node defined in the same block as the condition PHI, we can
9529 // map the arguments.
9530 const PHINode *CondPHI = cast<PHINode>(SI.getCondition());
9531
9532 if (const PHINode *VP = dyn_cast<PHINode>(I))
9533 if (VP->getParent() == CondPHI->getParent())
9534 return true;
9535
9536 // Otherwise, if the PHI and select are defined in the same block and if V is
9537 // defined in a different block, then we can transform it.
9538 if (SI.getParent() == CondPHI->getParent() &&
9539 I->getParent() != CondPHI->getParent())
9540 return true;
9541
9542 // Otherwise we have a 'hard' case and we can't tell without doing more
9543 // detailed dominator based analysis, punt.
9544 return false;
9545}
Chris Lattnerc6df8f42009-09-27 20:18:49 +00009546
Chris Lattnerb109b5c2009-12-21 06:03:05 +00009547/// FoldSPFofSPF - We have an SPF (e.g. a min or max) of an SPF of the form:
9548/// SPF2(SPF1(A, B), C)
9549Instruction *InstCombiner::FoldSPFofSPF(Instruction *Inner,
9550 SelectPatternFlavor SPF1,
9551 Value *A, Value *B,
9552 Instruction &Outer,
9553 SelectPatternFlavor SPF2, Value *C) {
9554 if (C == A || C == B) {
9555 // MAX(MAX(A, B), B) -> MAX(A, B)
9556 // MIN(MIN(a, b), a) -> MIN(a, b)
9557 if (SPF1 == SPF2)
9558 return ReplaceInstUsesWith(Outer, Inner);
9559
9560 // MAX(MIN(a, b), a) -> a
9561 // MIN(MAX(a, b), a) -> a
Daniel Dunbareddfaaf2009-12-21 23:27:57 +00009562 if ((SPF1 == SPF_SMIN && SPF2 == SPF_SMAX) ||
9563 (SPF1 == SPF_SMAX && SPF2 == SPF_SMIN) ||
9564 (SPF1 == SPF_UMIN && SPF2 == SPF_UMAX) ||
9565 (SPF1 == SPF_UMAX && SPF2 == SPF_UMIN))
Chris Lattnerb109b5c2009-12-21 06:03:05 +00009566 return ReplaceInstUsesWith(Outer, C);
9567 }
9568
9569 // TODO: MIN(MIN(A, 23), 97)
9570 return 0;
9571}
9572
9573
9574
9575
Chris Lattner3d69f462004-03-12 05:52:32 +00009576Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
Chris Lattnerc32b30a2004-03-30 19:37:13 +00009577 Value *CondVal = SI.getCondition();
9578 Value *TrueVal = SI.getTrueValue();
9579 Value *FalseVal = SI.getFalseValue();
9580
9581 // select true, X, Y -> X
9582 // select false, X, Y -> Y
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00009583 if (ConstantInt *C = dyn_cast<ConstantInt>(CondVal))
Reid Spencer579dca12007-01-12 04:24:46 +00009584 return ReplaceInstUsesWith(SI, C->getZExtValue() ? TrueVal : FalseVal);
Chris Lattnerc32b30a2004-03-30 19:37:13 +00009585
9586 // select C, X, X -> X
9587 if (TrueVal == FalseVal)
9588 return ReplaceInstUsesWith(SI, TrueVal);
9589
Chris Lattnere87597f2004-10-16 18:11:37 +00009590 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
9591 return ReplaceInstUsesWith(SI, FalseVal);
9592 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
9593 return ReplaceInstUsesWith(SI, TrueVal);
9594 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
9595 if (isa<Constant>(TrueVal))
9596 return ReplaceInstUsesWith(SI, TrueVal);
9597 else
9598 return ReplaceInstUsesWith(SI, FalseVal);
9599 }
9600
Chris Lattner4de84762010-01-04 07:02:48 +00009601 if (SI.getType() == Type::getInt1Ty(SI.getContext())) {
Reid Spencera54b7cb2007-01-12 07:05:14 +00009602 if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) {
Reid Spencer579dca12007-01-12 04:24:46 +00009603 if (C->getZExtValue()) {
Chris Lattner0c199a72004-04-08 04:43:23 +00009604 // Change: A = select B, true, C --> A = or B, C
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009605 return BinaryOperator::CreateOr(CondVal, FalseVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00009606 } else {
9607 // Change: A = select B, false, C --> A = and !B, C
9608 Value *NotCond =
Dan Gohman4ae51262009-08-12 16:23:25 +00009609 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Chris Lattner0c199a72004-04-08 04:43:23 +00009610 "not."+CondVal->getName()), SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009611 return BinaryOperator::CreateAnd(NotCond, FalseVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00009612 }
Reid Spencera54b7cb2007-01-12 07:05:14 +00009613 } else if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) {
Reid Spencer579dca12007-01-12 04:24:46 +00009614 if (C->getZExtValue() == false) {
Chris Lattner0c199a72004-04-08 04:43:23 +00009615 // Change: A = select B, C, false --> A = and B, C
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009616 return BinaryOperator::CreateAnd(CondVal, TrueVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00009617 } else {
9618 // Change: A = select B, C, true --> A = or !B, C
9619 Value *NotCond =
Dan Gohman4ae51262009-08-12 16:23:25 +00009620 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Chris Lattner0c199a72004-04-08 04:43:23 +00009621 "not."+CondVal->getName()), SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009622 return BinaryOperator::CreateOr(NotCond, TrueVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00009623 }
9624 }
Chris Lattnercfa59752007-11-25 21:27:53 +00009625
9626 // select a, b, a -> a&b
9627 // select a, a, b -> a|b
9628 if (CondVal == TrueVal)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009629 return BinaryOperator::CreateOr(CondVal, FalseVal);
Chris Lattnercfa59752007-11-25 21:27:53 +00009630 else if (CondVal == FalseVal)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009631 return BinaryOperator::CreateAnd(CondVal, TrueVal);
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00009632 }
Chris Lattner0c199a72004-04-08 04:43:23 +00009633
Chris Lattner2eefe512004-04-09 19:05:30 +00009634 // Selecting between two integer constants?
9635 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
9636 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
Chris Lattnerba417832007-04-11 06:12:58 +00009637 // select C, 1, 0 -> zext C to int
Reid Spencer2ec619a2007-03-23 21:24:59 +00009638 if (FalseValC->isZero() && TrueValC->getValue() == 1) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009639 return CastInst::Create(Instruction::ZExt, CondVal, SI.getType());
Reid Spencer2ec619a2007-03-23 21:24:59 +00009640 } else if (TrueValC->isZero() && FalseValC->getValue() == 1) {
Chris Lattnerba417832007-04-11 06:12:58 +00009641 // select C, 0, 1 -> zext !C to int
Chris Lattner2eefe512004-04-09 19:05:30 +00009642 Value *NotCond =
Dan Gohman4ae51262009-08-12 16:23:25 +00009643 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Chris Lattner82e14fe2004-04-09 18:19:44 +00009644 "not."+CondVal->getName()), SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009645 return CastInst::Create(Instruction::ZExt, NotCond, SI.getType());
Chris Lattner82e14fe2004-04-09 18:19:44 +00009646 }
Chris Lattner457dd822004-06-09 07:59:58 +00009647
Reid Spencere4d87aa2006-12-23 06:05:41 +00009648 if (ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition())) {
Chris Lattnerb8456462006-09-20 04:44:59 +00009649 // If one of the constants is zero (we know they can't both be) and we
Chris Lattnerba417832007-04-11 06:12:58 +00009650 // have an icmp instruction with zero, and we have an 'and' with the
Chris Lattnerb8456462006-09-20 04:44:59 +00009651 // non-constant value, eliminate this whole mess. This corresponds to
9652 // cases like this: ((X & 27) ? 27 : 0)
Reid Spencer2ec619a2007-03-23 21:24:59 +00009653 if (TrueValC->isZero() || FalseValC->isZero())
Chris Lattner65b72ba2006-09-18 04:22:48 +00009654 if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
Chris Lattner457dd822004-06-09 07:59:58 +00009655 cast<Constant>(IC->getOperand(1))->isNullValue())
9656 if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
9657 if (ICA->getOpcode() == Instruction::And &&
Misha Brukmanfd939082005-04-21 23:48:37 +00009658 isa<ConstantInt>(ICA->getOperand(1)) &&
9659 (ICA->getOperand(1) == TrueValC ||
9660 ICA->getOperand(1) == FalseValC) &&
Chris Lattner457dd822004-06-09 07:59:58 +00009661 isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
9662 // Okay, now we know that everything is set up, we just don't
Reid Spencere4d87aa2006-12-23 06:05:41 +00009663 // know whether we have a icmp_ne or icmp_eq and whether the
9664 // true or false val is the zero.
Reid Spencer2ec619a2007-03-23 21:24:59 +00009665 bool ShouldNotVal = !TrueValC->isZero();
Reid Spencere4d87aa2006-12-23 06:05:41 +00009666 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
Chris Lattner457dd822004-06-09 07:59:58 +00009667 Value *V = ICA;
9668 if (ShouldNotVal)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009669 V = InsertNewInstBefore(BinaryOperator::Create(
Chris Lattner457dd822004-06-09 07:59:58 +00009670 Instruction::Xor, V, ICA->getOperand(1)), SI);
9671 return ReplaceInstUsesWith(SI, V);
9672 }
Chris Lattnerb8456462006-09-20 04:44:59 +00009673 }
Chris Lattnerc32b30a2004-03-30 19:37:13 +00009674 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00009675
9676 // See if we are selecting two values based on a comparison of the two values.
Reid Spencere4d87aa2006-12-23 06:05:41 +00009677 if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
9678 if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
Chris Lattnerd76956d2004-04-10 22:21:27 +00009679 // Transform (X == Y) ? X : Y -> Y
Dale Johannesen5a2174f2007-10-03 17:45:27 +00009680 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
9681 // This is not safe in general for floating point:
9682 // consider X== -0, Y== +0.
9683 // It becomes safe if either operand is a nonzero constant.
9684 ConstantFP *CFPt, *CFPf;
9685 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
9686 !CFPt->getValueAPF().isZero()) ||
9687 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
9688 !CFPf->getValueAPF().isZero()))
Chris Lattnerd76956d2004-04-10 22:21:27 +00009689 return ReplaceInstUsesWith(SI, FalseVal);
Dale Johannesen5a2174f2007-10-03 17:45:27 +00009690 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00009691 // Transform (X != Y) ? X : Y -> X
Reid Spencere4d87aa2006-12-23 06:05:41 +00009692 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
Chris Lattnerd76956d2004-04-10 22:21:27 +00009693 return ReplaceInstUsesWith(SI, TrueVal);
Dan Gohman81b28ce2008-09-16 18:46:06 +00009694 // NOTE: if we wanted to, this is where to detect MIN/MAX
Chris Lattnerd76956d2004-04-10 22:21:27 +00009695
Reid Spencere4d87aa2006-12-23 06:05:41 +00009696 } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
Chris Lattnerd76956d2004-04-10 22:21:27 +00009697 // Transform (X == Y) ? Y : X -> X
Dale Johannesen5a2174f2007-10-03 17:45:27 +00009698 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
9699 // This is not safe in general for floating point:
9700 // consider X== -0, Y== +0.
9701 // It becomes safe if either operand is a nonzero constant.
9702 ConstantFP *CFPt, *CFPf;
9703 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
9704 !CFPt->getValueAPF().isZero()) ||
9705 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
9706 !CFPf->getValueAPF().isZero()))
9707 return ReplaceInstUsesWith(SI, FalseVal);
9708 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00009709 // Transform (X != Y) ? Y : X -> Y
Reid Spencere4d87aa2006-12-23 06:05:41 +00009710 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
9711 return ReplaceInstUsesWith(SI, TrueVal);
Dan Gohman81b28ce2008-09-16 18:46:06 +00009712 // NOTE: if we wanted to, this is where to detect MIN/MAX
Reid Spencere4d87aa2006-12-23 06:05:41 +00009713 }
Dan Gohman81b28ce2008-09-16 18:46:06 +00009714 // NOTE: if we wanted to, this is where to detect ABS
Reid Spencere4d87aa2006-12-23 06:05:41 +00009715 }
9716
9717 // See if we are selecting two values based on a comparison of the two values.
Dan Gohman81b28ce2008-09-16 18:46:06 +00009718 if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal))
9719 if (Instruction *Result = visitSelectInstWithICmp(SI, ICI))
9720 return Result;
Misha Brukmanfd939082005-04-21 23:48:37 +00009721
Chris Lattner87875da2005-01-13 22:52:24 +00009722 if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
9723 if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
9724 if (TI->hasOneUse() && FI->hasOneUse()) {
Chris Lattner87875da2005-01-13 22:52:24 +00009725 Instruction *AddOp = 0, *SubOp = 0;
9726
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009727 // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
9728 if (TI->getOpcode() == FI->getOpcode())
9729 if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
9730 return IV;
9731
9732 // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))). This is
9733 // even legal for FP.
Dan Gohmanae3a0be2009-06-04 22:49:04 +00009734 if ((TI->getOpcode() == Instruction::Sub &&
9735 FI->getOpcode() == Instruction::Add) ||
9736 (TI->getOpcode() == Instruction::FSub &&
9737 FI->getOpcode() == Instruction::FAdd)) {
Chris Lattner87875da2005-01-13 22:52:24 +00009738 AddOp = FI; SubOp = TI;
Dan Gohmanae3a0be2009-06-04 22:49:04 +00009739 } else if ((FI->getOpcode() == Instruction::Sub &&
9740 TI->getOpcode() == Instruction::Add) ||
9741 (FI->getOpcode() == Instruction::FSub &&
9742 TI->getOpcode() == Instruction::FAdd)) {
Chris Lattner87875da2005-01-13 22:52:24 +00009743 AddOp = TI; SubOp = FI;
9744 }
9745
9746 if (AddOp) {
9747 Value *OtherAddOp = 0;
9748 if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
9749 OtherAddOp = AddOp->getOperand(1);
9750 } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
9751 OtherAddOp = AddOp->getOperand(0);
9752 }
9753
9754 if (OtherAddOp) {
Chris Lattner97f37a42006-02-24 18:05:58 +00009755 // So at this point we know we have (Y -> OtherAddOp):
9756 // select C, (add X, Y), (sub X, Z)
9757 Value *NegVal; // Compute -Z
9758 if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00009759 NegVal = ConstantExpr::getNeg(C);
Chris Lattner97f37a42006-02-24 18:05:58 +00009760 } else {
9761 NegVal = InsertNewInstBefore(
Dan Gohman4ae51262009-08-12 16:23:25 +00009762 BinaryOperator::CreateNeg(SubOp->getOperand(1),
Owen Anderson0a5372e2009-07-13 04:09:18 +00009763 "tmp"), SI);
Chris Lattner87875da2005-01-13 22:52:24 +00009764 }
Chris Lattner97f37a42006-02-24 18:05:58 +00009765
9766 Value *NewTrueOp = OtherAddOp;
9767 Value *NewFalseOp = NegVal;
9768 if (AddOp != TI)
9769 std::swap(NewTrueOp, NewFalseOp);
9770 Instruction *NewSel =
Gabor Greifb1dbcd82008-05-15 10:04:30 +00009771 SelectInst::Create(CondVal, NewTrueOp,
9772 NewFalseOp, SI.getName() + ".p");
Chris Lattner97f37a42006-02-24 18:05:58 +00009773
9774 NewSel = InsertNewInstBefore(NewSel, SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009775 return BinaryOperator::CreateAdd(SubOp->getOperand(0), NewSel);
Chris Lattner87875da2005-01-13 22:52:24 +00009776 }
9777 }
9778 }
Misha Brukmanfd939082005-04-21 23:48:37 +00009779
Chris Lattnere576b912004-04-09 23:46:01 +00009780 // See if we can fold the select into one of our operands.
Chris Lattner42a75512007-01-15 02:27:26 +00009781 if (SI.getType()->isInteger()) {
Chris Lattnerb109b5c2009-12-21 06:03:05 +00009782 if (Instruction *FoldI = FoldSelectIntoOp(SI, TrueVal, FalseVal))
Evan Chengde621922009-03-31 20:42:45 +00009783 return FoldI;
Chris Lattnerb109b5c2009-12-21 06:03:05 +00009784
9785 // MAX(MAX(a, b), a) -> MAX(a, b)
9786 // MIN(MIN(a, b), a) -> MIN(a, b)
9787 // MAX(MIN(a, b), a) -> a
9788 // MIN(MAX(a, b), a) -> a
9789 Value *LHS, *RHS, *LHS2, *RHS2;
9790 if (SelectPatternFlavor SPF = MatchSelectPattern(&SI, LHS, RHS)) {
9791 if (SelectPatternFlavor SPF2 = MatchSelectPattern(LHS, LHS2, RHS2))
9792 if (Instruction *R = FoldSPFofSPF(cast<Instruction>(LHS),SPF2,LHS2,RHS2,
9793 SI, SPF, RHS))
9794 return R;
9795 if (SelectPatternFlavor SPF2 = MatchSelectPattern(RHS, LHS2, RHS2))
9796 if (Instruction *R = FoldSPFofSPF(cast<Instruction>(RHS),SPF2,LHS2,RHS2,
9797 SI, SPF, LHS))
9798 return R;
9799 }
9800
9801 // TODO.
9802 // ABS(-X) -> ABS(X)
9803 // ABS(ABS(X)) -> ABS(X)
Chris Lattnere576b912004-04-09 23:46:01 +00009804 }
Chris Lattnera1df33c2005-04-24 07:30:14 +00009805
Chris Lattner7f239582009-10-22 00:17:26 +00009806 // See if we can fold the select into a phi node if the condition is a select.
9807 if (isa<PHINode>(SI.getCondition()))
9808 // The true/false values have to be live in the PHI predecessor's blocks.
9809 if (CanSelectOperandBeMappingIntoPredBlock(TrueVal, SI) &&
9810 CanSelectOperandBeMappingIntoPredBlock(FalseVal, SI))
9811 if (Instruction *NV = FoldOpIntoPhi(SI))
9812 return NV;
Chris Lattner5d1704d2009-09-27 19:57:57 +00009813
Chris Lattnera1df33c2005-04-24 07:30:14 +00009814 if (BinaryOperator::isNot(CondVal)) {
9815 SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
9816 SI.setOperand(1, FalseVal);
9817 SI.setOperand(2, TrueVal);
9818 return &SI;
9819 }
9820
Chris Lattner3d69f462004-03-12 05:52:32 +00009821 return 0;
9822}
9823
Dan Gohmaneee962e2008-04-10 18:43:06 +00009824/// EnforceKnownAlignment - If the specified pointer points to an object that
9825/// we control, modify the object's alignment to PrefAlign. This isn't
9826/// often possible though. If alignment is important, a more reliable approach
9827/// is to simply align all global variables and allocation instructions to
9828/// their preferred alignment from the beginning.
9829///
9830static unsigned EnforceKnownAlignment(Value *V,
9831 unsigned Align, unsigned PrefAlign) {
Chris Lattnerf2369f22007-08-09 19:05:49 +00009832
Dan Gohmaneee962e2008-04-10 18:43:06 +00009833 User *U = dyn_cast<User>(V);
9834 if (!U) return Align;
9835
Dan Gohmanca178902009-07-17 20:47:02 +00009836 switch (Operator::getOpcode(U)) {
Dan Gohmaneee962e2008-04-10 18:43:06 +00009837 default: break;
9838 case Instruction::BitCast:
9839 return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
9840 case Instruction::GetElementPtr: {
Chris Lattner95a959d2006-03-06 20:18:44 +00009841 // If all indexes are zero, it is just the alignment of the base pointer.
9842 bool AllZeroOperands = true;
Gabor Greif52ed3632008-06-12 21:51:29 +00009843 for (User::op_iterator i = U->op_begin() + 1, e = U->op_end(); i != e; ++i)
Gabor Greif177dd3f2008-06-12 21:37:33 +00009844 if (!isa<Constant>(*i) ||
9845 !cast<Constant>(*i)->isNullValue()) {
Chris Lattner95a959d2006-03-06 20:18:44 +00009846 AllZeroOperands = false;
9847 break;
9848 }
Chris Lattnerf2369f22007-08-09 19:05:49 +00009849
9850 if (AllZeroOperands) {
9851 // Treat this like a bitcast.
Dan Gohmaneee962e2008-04-10 18:43:06 +00009852 return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
Chris Lattnerf2369f22007-08-09 19:05:49 +00009853 }
Dan Gohmaneee962e2008-04-10 18:43:06 +00009854 break;
Chris Lattner95a959d2006-03-06 20:18:44 +00009855 }
Dan Gohmaneee962e2008-04-10 18:43:06 +00009856 }
9857
9858 if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
9859 // If there is a large requested alignment and we can, bump up the alignment
9860 // of the global.
9861 if (!GV->isDeclaration()) {
Dan Gohmanecd0fb52009-02-16 23:02:21 +00009862 if (GV->getAlignment() >= PrefAlign)
9863 Align = GV->getAlignment();
9864 else {
9865 GV->setAlignment(PrefAlign);
9866 Align = PrefAlign;
9867 }
Dan Gohmaneee962e2008-04-10 18:43:06 +00009868 }
Chris Lattner42ebefa2009-09-27 21:42:46 +00009869 } else if (AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
9870 // If there is a requested alignment and if this is an alloca, round up.
9871 if (AI->getAlignment() >= PrefAlign)
9872 Align = AI->getAlignment();
9873 else {
9874 AI->setAlignment(PrefAlign);
9875 Align = PrefAlign;
Dan Gohmaneee962e2008-04-10 18:43:06 +00009876 }
9877 }
9878
9879 return Align;
9880}
9881
9882/// GetOrEnforceKnownAlignment - If the specified pointer has an alignment that
9883/// we can determine, return it, otherwise return 0. If PrefAlign is specified,
9884/// and it is more than the alignment of the ultimate object, see if we can
9885/// increase the alignment of the ultimate object, making this check succeed.
9886unsigned InstCombiner::GetOrEnforceKnownAlignment(Value *V,
9887 unsigned PrefAlign) {
9888 unsigned BitWidth = TD ? TD->getTypeSizeInBits(V->getType()) :
9889 sizeof(PrefAlign) * CHAR_BIT;
9890 APInt Mask = APInt::getAllOnesValue(BitWidth);
9891 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
9892 ComputeMaskedBits(V, Mask, KnownZero, KnownOne);
9893 unsigned TrailZ = KnownZero.countTrailingOnes();
9894 unsigned Align = 1u << std::min(BitWidth - 1, TrailZ);
9895
9896 if (PrefAlign > Align)
9897 Align = EnforceKnownAlignment(V, Align, PrefAlign);
9898
9899 // We don't need to make any adjustment.
9900 return Align;
Chris Lattner95a959d2006-03-06 20:18:44 +00009901}
9902
Chris Lattnerf497b022008-01-13 23:50:23 +00009903Instruction *InstCombiner::SimplifyMemTransfer(MemIntrinsic *MI) {
Dan Gohmaneee962e2008-04-10 18:43:06 +00009904 unsigned DstAlign = GetOrEnforceKnownAlignment(MI->getOperand(1));
Dan Gohmanbc989d42009-02-22 18:06:32 +00009905 unsigned SrcAlign = GetOrEnforceKnownAlignment(MI->getOperand(2));
Chris Lattnerf497b022008-01-13 23:50:23 +00009906 unsigned MinAlign = std::min(DstAlign, SrcAlign);
Chris Lattnerdfe964c2009-03-08 03:59:00 +00009907 unsigned CopyAlign = MI->getAlignment();
Chris Lattnerf497b022008-01-13 23:50:23 +00009908
9909 if (CopyAlign < MinAlign) {
Owen Andersoneed707b2009-07-24 23:12:02 +00009910 MI->setAlignment(ConstantInt::get(MI->getAlignmentType(),
Owen Andersona547b472009-07-09 18:36:20 +00009911 MinAlign, false));
Chris Lattnerf497b022008-01-13 23:50:23 +00009912 return MI;
9913 }
9914
9915 // If MemCpyInst length is 1/2/4/8 bytes then replace memcpy with
9916 // load/store.
9917 ConstantInt *MemOpLength = dyn_cast<ConstantInt>(MI->getOperand(3));
9918 if (MemOpLength == 0) return 0;
9919
Chris Lattner37ac6082008-01-14 00:28:35 +00009920 // Source and destination pointer types are always "i8*" for intrinsic. See
9921 // if the size is something we can handle with a single primitive load/store.
9922 // A single load+store correctly handles overlapping memory in the memmove
9923 // case.
Chris Lattnerf497b022008-01-13 23:50:23 +00009924 unsigned Size = MemOpLength->getZExtValue();
Chris Lattner69ea9d22008-04-30 06:39:11 +00009925 if (Size == 0) return MI; // Delete this mem transfer.
9926
9927 if (Size > 8 || (Size&(Size-1)))
Chris Lattner37ac6082008-01-14 00:28:35 +00009928 return 0; // If not 1/2/4/8 bytes, exit.
Chris Lattnerf497b022008-01-13 23:50:23 +00009929
Chris Lattner37ac6082008-01-14 00:28:35 +00009930 // Use an integer load+store unless we can find something better.
Owen Andersond672ecb2009-07-03 00:17:18 +00009931 Type *NewPtrTy =
Chris Lattner4de84762010-01-04 07:02:48 +00009932 PointerType::getUnqual(IntegerType::get(MI->getContext(), Size<<3));
Chris Lattner37ac6082008-01-14 00:28:35 +00009933
9934 // Memcpy forces the use of i8* for the source and destination. That means
9935 // that if you're using memcpy to move one double around, you'll get a cast
9936 // from double* to i8*. We'd much rather use a double load+store rather than
9937 // an i64 load+store, here because this improves the odds that the source or
9938 // dest address will be promotable. See if we can find a better type than the
9939 // integer datatype.
9940 if (Value *Op = getBitCastOperand(MI->getOperand(1))) {
9941 const Type *SrcETy = cast<PointerType>(Op->getType())->getElementType();
Dan Gohmance9fe9f2009-07-21 23:21:54 +00009942 if (TD && SrcETy->isSized() && TD->getTypeStoreSize(SrcETy) == Size) {
Chris Lattner37ac6082008-01-14 00:28:35 +00009943 // The SrcETy might be something like {{{double}}} or [1 x double]. Rip
9944 // down through these levels if so.
Dan Gohman8f8e2692008-05-23 01:52:21 +00009945 while (!SrcETy->isSingleValueType()) {
Chris Lattner37ac6082008-01-14 00:28:35 +00009946 if (const StructType *STy = dyn_cast<StructType>(SrcETy)) {
9947 if (STy->getNumElements() == 1)
9948 SrcETy = STy->getElementType(0);
9949 else
9950 break;
9951 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcETy)) {
9952 if (ATy->getNumElements() == 1)
9953 SrcETy = ATy->getElementType();
9954 else
9955 break;
9956 } else
9957 break;
9958 }
9959
Dan Gohman8f8e2692008-05-23 01:52:21 +00009960 if (SrcETy->isSingleValueType())
Owen Andersondebcb012009-07-29 22:17:13 +00009961 NewPtrTy = PointerType::getUnqual(SrcETy);
Chris Lattner37ac6082008-01-14 00:28:35 +00009962 }
9963 }
9964
9965
Chris Lattnerf497b022008-01-13 23:50:23 +00009966 // If the memcpy/memmove provides better alignment info than we can
9967 // infer, use it.
9968 SrcAlign = std::max(SrcAlign, CopyAlign);
9969 DstAlign = std::max(DstAlign, CopyAlign);
9970
Chris Lattner08142f22009-08-30 19:47:22 +00009971 Value *Src = Builder->CreateBitCast(MI->getOperand(2), NewPtrTy);
9972 Value *Dest = Builder->CreateBitCast(MI->getOperand(1), NewPtrTy);
Chris Lattner37ac6082008-01-14 00:28:35 +00009973 Instruction *L = new LoadInst(Src, "tmp", false, SrcAlign);
9974 InsertNewInstBefore(L, *MI);
9975 InsertNewInstBefore(new StoreInst(L, Dest, false, DstAlign), *MI);
9976
9977 // Set the size of the copy to 0, it will be deleted on the next iteration.
Owen Andersona7235ea2009-07-31 20:28:14 +00009978 MI->setOperand(3, Constant::getNullValue(MemOpLength->getType()));
Chris Lattner37ac6082008-01-14 00:28:35 +00009979 return MI;
Chris Lattnerf497b022008-01-13 23:50:23 +00009980}
Chris Lattner3d69f462004-03-12 05:52:32 +00009981
Chris Lattner69ea9d22008-04-30 06:39:11 +00009982Instruction *InstCombiner::SimplifyMemSet(MemSetInst *MI) {
9983 unsigned Alignment = GetOrEnforceKnownAlignment(MI->getDest());
Chris Lattnerdfe964c2009-03-08 03:59:00 +00009984 if (MI->getAlignment() < Alignment) {
Owen Andersoneed707b2009-07-24 23:12:02 +00009985 MI->setAlignment(ConstantInt::get(MI->getAlignmentType(),
Owen Andersona547b472009-07-09 18:36:20 +00009986 Alignment, false));
Chris Lattner69ea9d22008-04-30 06:39:11 +00009987 return MI;
9988 }
9989
9990 // Extract the length and alignment and fill if they are constant.
9991 ConstantInt *LenC = dyn_cast<ConstantInt>(MI->getLength());
9992 ConstantInt *FillC = dyn_cast<ConstantInt>(MI->getValue());
Chris Lattner4de84762010-01-04 07:02:48 +00009993 if (!LenC || !FillC || FillC->getType() != Type::getInt8Ty(MI->getContext()))
Chris Lattner69ea9d22008-04-30 06:39:11 +00009994 return 0;
9995 uint64_t Len = LenC->getZExtValue();
Chris Lattnerdfe964c2009-03-08 03:59:00 +00009996 Alignment = MI->getAlignment();
Chris Lattner69ea9d22008-04-30 06:39:11 +00009997
9998 // If the length is zero, this is a no-op
9999 if (Len == 0) return MI; // memset(d,c,0,a) -> noop
10000
10001 // memset(s,c,n) -> store s, c (for n=1,2,4,8)
10002 if (Len <= 8 && isPowerOf2_32((uint32_t)Len)) {
Chris Lattner4de84762010-01-04 07:02:48 +000010003 const Type *ITy = IntegerType::get(MI->getContext(), Len*8); // n=1 -> i8.
Chris Lattner69ea9d22008-04-30 06:39:11 +000010004
10005 Value *Dest = MI->getDest();
Chris Lattner08142f22009-08-30 19:47:22 +000010006 Dest = Builder->CreateBitCast(Dest, PointerType::getUnqual(ITy));
Chris Lattner69ea9d22008-04-30 06:39:11 +000010007
10008 // Alignment 0 is identity for alignment 1 for memset, but not store.
10009 if (Alignment == 0) Alignment = 1;
10010
10011 // Extract the fill value and store.
10012 uint64_t Fill = FillC->getZExtValue()*0x0101010101010101ULL;
Owen Andersoneed707b2009-07-24 23:12:02 +000010013 InsertNewInstBefore(new StoreInst(ConstantInt::get(ITy, Fill),
Owen Andersond672ecb2009-07-03 00:17:18 +000010014 Dest, false, Alignment), *MI);
Chris Lattner69ea9d22008-04-30 06:39:11 +000010015
10016 // Set the size of the copy to 0, it will be deleted on the next iteration.
Owen Andersona7235ea2009-07-31 20:28:14 +000010017 MI->setLength(Constant::getNullValue(LenC->getType()));
Chris Lattner69ea9d22008-04-30 06:39:11 +000010018 return MI;
10019 }
10020
10021 return 0;
10022}
10023
10024
Chris Lattner8b0ea312006-01-13 20:11:04 +000010025/// visitCallInst - CallInst simplification. This mostly only handles folding
10026/// of intrinsic instructions. For normal calls, it allows visitCallSite to do
10027/// the heavy lifting.
10028///
Chris Lattner9fe38862003-06-19 17:00:31 +000010029Instruction *InstCombiner::visitCallInst(CallInst &CI) {
Victor Hernandez66284e02009-10-24 04:23:03 +000010030 if (isFreeCall(&CI))
10031 return visitFree(CI);
10032
Chris Lattneraab6ec42009-05-13 17:39:14 +000010033 // If the caller function is nounwind, mark the call as nounwind, even if the
10034 // callee isn't.
10035 if (CI.getParent()->getParent()->doesNotThrow() &&
10036 !CI.doesNotThrow()) {
10037 CI.setDoesNotThrow();
10038 return &CI;
10039 }
10040
Chris Lattner8b0ea312006-01-13 20:11:04 +000010041 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
10042 if (!II) return visitCallSite(&CI);
10043
Chris Lattner7bcc0e72004-02-28 05:22:00 +000010044 // Intrinsics cannot occur in an invoke, so handle them here instead of in
10045 // visitCallSite.
Chris Lattner8b0ea312006-01-13 20:11:04 +000010046 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
Chris Lattner35b9e482004-10-12 04:52:52 +000010047 bool Changed = false;
10048
10049 // memmove/cpy/set of zero bytes is a noop.
10050 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
10051 if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
10052
Chris Lattner35b9e482004-10-12 04:52:52 +000010053 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
Reid Spencerb83eb642006-10-20 07:07:24 +000010054 if (CI->getZExtValue() == 1) {
Chris Lattner35b9e482004-10-12 04:52:52 +000010055 // Replace the instruction with just byte operations. We would
10056 // transform other cases to loads/stores, but we don't know if
10057 // alignment is sufficient.
10058 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +000010059 }
10060
Chris Lattner35b9e482004-10-12 04:52:52 +000010061 // If we have a memmove and the source operation is a constant global,
10062 // then the source and dest pointers can't alias, so we can change this
10063 // into a call to memcpy.
Chris Lattnerf497b022008-01-13 23:50:23 +000010064 if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI)) {
Chris Lattner35b9e482004-10-12 04:52:52 +000010065 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
10066 if (GVSrc->isConstant()) {
10067 Module *M = CI.getParent()->getParent()->getParent();
Chris Lattner824b9582008-11-21 16:42:48 +000010068 Intrinsic::ID MemCpyID = Intrinsic::memcpy;
10069 const Type *Tys[1];
10070 Tys[0] = CI.getOperand(3)->getType();
10071 CI.setOperand(0,
10072 Intrinsic::getDeclaration(M, MemCpyID, Tys, 1));
Chris Lattner35b9e482004-10-12 04:52:52 +000010073 Changed = true;
10074 }
Eli Friedman0c826d92009-12-17 21:07:31 +000010075 }
Chris Lattnera935db82008-05-28 05:30:41 +000010076
Eli Friedman0c826d92009-12-17 21:07:31 +000010077 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(MI)) {
Chris Lattnera935db82008-05-28 05:30:41 +000010078 // memmove(x,x,size) -> noop.
Eli Friedman0c826d92009-12-17 21:07:31 +000010079 if (MTI->getSource() == MTI->getDest())
Chris Lattnera935db82008-05-28 05:30:41 +000010080 return EraseInstFromFunction(CI);
Chris Lattner95a959d2006-03-06 20:18:44 +000010081 }
Chris Lattner35b9e482004-10-12 04:52:52 +000010082
Chris Lattner95a959d2006-03-06 20:18:44 +000010083 // If we can determine a pointer alignment that is bigger than currently
10084 // set, update the alignment.
Chris Lattner3ce5e882009-03-08 03:37:16 +000010085 if (isa<MemTransferInst>(MI)) {
Chris Lattnerf497b022008-01-13 23:50:23 +000010086 if (Instruction *I = SimplifyMemTransfer(MI))
10087 return I;
Chris Lattner69ea9d22008-04-30 06:39:11 +000010088 } else if (MemSetInst *MSI = dyn_cast<MemSetInst>(MI)) {
10089 if (Instruction *I = SimplifyMemSet(MSI))
10090 return I;
Chris Lattner95a959d2006-03-06 20:18:44 +000010091 }
10092
Chris Lattner8b0ea312006-01-13 20:11:04 +000010093 if (Changed) return II;
Chris Lattner0521e3c2008-06-18 04:33:20 +000010094 }
10095
10096 switch (II->getIntrinsicID()) {
10097 default: break;
10098 case Intrinsic::bswap:
10099 // bswap(bswap(x)) -> x
10100 if (IntrinsicInst *Operand = dyn_cast<IntrinsicInst>(II->getOperand(1)))
10101 if (Operand->getIntrinsicID() == Intrinsic::bswap)
10102 return ReplaceInstUsesWith(CI, Operand->getOperand(1));
Chris Lattnere33d4132010-01-01 18:34:40 +000010103
10104 // bswap(trunc(bswap(x))) -> trunc(lshr(x, c))
10105 if (TruncInst *TI = dyn_cast<TruncInst>(II->getOperand(1))) {
10106 if (IntrinsicInst *Operand = dyn_cast<IntrinsicInst>(TI->getOperand(0)))
10107 if (Operand->getIntrinsicID() == Intrinsic::bswap) {
10108 unsigned C = Operand->getType()->getPrimitiveSizeInBits() -
10109 TI->getType()->getPrimitiveSizeInBits();
10110 Value *CV = ConstantInt::get(Operand->getType(), C);
10111 Value *V = Builder->CreateLShr(Operand->getOperand(1), CV);
10112 return new TruncInst(V, TI->getType());
10113 }
10114 }
10115
Chris Lattner0521e3c2008-06-18 04:33:20 +000010116 break;
Chris Lattnerd27f9112010-01-01 01:52:15 +000010117 case Intrinsic::powi:
10118 if (ConstantInt *Power = dyn_cast<ConstantInt>(II->getOperand(2))) {
10119 // powi(x, 0) -> 1.0
10120 if (Power->isZero())
10121 return ReplaceInstUsesWith(CI, ConstantFP::get(CI.getType(), 1.0));
10122 // powi(x, 1) -> x
10123 if (Power->isOne())
10124 return ReplaceInstUsesWith(CI, II->getOperand(1));
10125 // powi(x, -1) -> 1/x
Chris Lattnerf9ead872010-01-01 01:54:08 +000010126 if (Power->isAllOnesValue())
10127 return BinaryOperator::CreateFDiv(ConstantFP::get(CI.getType(), 1.0),
10128 II->getOperand(1));
Chris Lattnerd27f9112010-01-01 01:52:15 +000010129 }
10130 break;
10131
Chris Lattner2bbac752009-11-26 21:42:47 +000010132 case Intrinsic::uadd_with_overflow: {
10133 Value *LHS = II->getOperand(1), *RHS = II->getOperand(2);
10134 const IntegerType *IT = cast<IntegerType>(II->getOperand(1)->getType());
10135 uint32_t BitWidth = IT->getBitWidth();
10136 APInt Mask = APInt::getSignBit(BitWidth);
Chris Lattner998e25a2009-11-26 22:08:06 +000010137 APInt LHSKnownZero(BitWidth, 0);
10138 APInt LHSKnownOne(BitWidth, 0);
Chris Lattner2bbac752009-11-26 21:42:47 +000010139 ComputeMaskedBits(LHS, Mask, LHSKnownZero, LHSKnownOne);
10140 bool LHSKnownNegative = LHSKnownOne[BitWidth - 1];
10141 bool LHSKnownPositive = LHSKnownZero[BitWidth - 1];
10142
10143 if (LHSKnownNegative || LHSKnownPositive) {
Chris Lattner998e25a2009-11-26 22:08:06 +000010144 APInt RHSKnownZero(BitWidth, 0);
10145 APInt RHSKnownOne(BitWidth, 0);
Chris Lattner2bbac752009-11-26 21:42:47 +000010146 ComputeMaskedBits(RHS, Mask, RHSKnownZero, RHSKnownOne);
10147 bool RHSKnownNegative = RHSKnownOne[BitWidth - 1];
10148 bool RHSKnownPositive = RHSKnownZero[BitWidth - 1];
10149 if (LHSKnownNegative && RHSKnownNegative) {
10150 // The sign bit is set in both cases: this MUST overflow.
10151 // Create a simple add instruction, and insert it into the struct.
10152 Instruction *Add = BinaryOperator::CreateAdd(LHS, RHS, "", &CI);
10153 Worklist.Add(Add);
Chris Lattnercd188e92009-11-29 02:57:29 +000010154 Constant *V[] = {
Chris Lattner4de84762010-01-04 07:02:48 +000010155 UndefValue::get(LHS->getType()),ConstantInt::getTrue(II->getContext())
Chris Lattnercd188e92009-11-29 02:57:29 +000010156 };
Chris Lattner4de84762010-01-04 07:02:48 +000010157 Constant *Struct = ConstantStruct::get(II->getContext(), V, 2, false);
Chris Lattner2bbac752009-11-26 21:42:47 +000010158 return InsertValueInst::Create(Struct, Add, 0);
10159 }
10160
10161 if (LHSKnownPositive && RHSKnownPositive) {
10162 // The sign bit is clear in both cases: this CANNOT overflow.
10163 // Create a simple add instruction, and insert it into the struct.
10164 Instruction *Add = BinaryOperator::CreateNUWAdd(LHS, RHS, "", &CI);
10165 Worklist.Add(Add);
Chris Lattnercd188e92009-11-29 02:57:29 +000010166 Constant *V[] = {
Chris Lattner4de84762010-01-04 07:02:48 +000010167 UndefValue::get(LHS->getType()),
10168 ConstantInt::getFalse(II->getContext())
Chris Lattnercd188e92009-11-29 02:57:29 +000010169 };
Chris Lattner4de84762010-01-04 07:02:48 +000010170 Constant *Struct = ConstantStruct::get(II->getContext(), V, 2, false);
Chris Lattner2bbac752009-11-26 21:42:47 +000010171 return InsertValueInst::Create(Struct, Add, 0);
10172 }
10173 }
10174 }
10175 // FALL THROUGH uadd into sadd
10176 case Intrinsic::sadd_with_overflow:
10177 // Canonicalize constants into the RHS.
10178 if (isa<Constant>(II->getOperand(1)) &&
10179 !isa<Constant>(II->getOperand(2))) {
10180 Value *LHS = II->getOperand(1);
10181 II->setOperand(1, II->getOperand(2));
10182 II->setOperand(2, LHS);
10183 return II;
10184 }
10185
10186 // X + undef -> undef
10187 if (isa<UndefValue>(II->getOperand(2)))
10188 return ReplaceInstUsesWith(CI, UndefValue::get(II->getType()));
10189
10190 if (ConstantInt *RHS = dyn_cast<ConstantInt>(II->getOperand(2))) {
10191 // X + 0 -> {X, false}
10192 if (RHS->isZero()) {
10193 Constant *V[] = {
Chris Lattnercd188e92009-11-29 02:57:29 +000010194 UndefValue::get(II->getOperand(0)->getType()),
Chris Lattner4de84762010-01-04 07:02:48 +000010195 ConstantInt::getFalse(II->getContext())
Chris Lattner2bbac752009-11-26 21:42:47 +000010196 };
Chris Lattner4de84762010-01-04 07:02:48 +000010197 Constant *Struct = ConstantStruct::get(II->getContext(), V, 2, false);
Chris Lattner2bbac752009-11-26 21:42:47 +000010198 return InsertValueInst::Create(Struct, II->getOperand(1), 0);
10199 }
10200 }
10201 break;
10202 case Intrinsic::usub_with_overflow:
10203 case Intrinsic::ssub_with_overflow:
10204 // undef - X -> undef
10205 // X - undef -> undef
10206 if (isa<UndefValue>(II->getOperand(1)) ||
10207 isa<UndefValue>(II->getOperand(2)))
10208 return ReplaceInstUsesWith(CI, UndefValue::get(II->getType()));
10209
10210 if (ConstantInt *RHS = dyn_cast<ConstantInt>(II->getOperand(2))) {
10211 // X - 0 -> {X, false}
10212 if (RHS->isZero()) {
10213 Constant *V[] = {
Chris Lattnercd188e92009-11-29 02:57:29 +000010214 UndefValue::get(II->getOperand(1)->getType()),
Chris Lattner4de84762010-01-04 07:02:48 +000010215 ConstantInt::getFalse(II->getContext())
Chris Lattner2bbac752009-11-26 21:42:47 +000010216 };
Chris Lattner4de84762010-01-04 07:02:48 +000010217 Constant *Struct = ConstantStruct::get(II->getContext(), V, 2, false);
Chris Lattner2bbac752009-11-26 21:42:47 +000010218 return InsertValueInst::Create(Struct, II->getOperand(1), 0);
10219 }
10220 }
10221 break;
10222 case Intrinsic::umul_with_overflow:
10223 case Intrinsic::smul_with_overflow:
10224 // Canonicalize constants into the RHS.
10225 if (isa<Constant>(II->getOperand(1)) &&
10226 !isa<Constant>(II->getOperand(2))) {
10227 Value *LHS = II->getOperand(1);
10228 II->setOperand(1, II->getOperand(2));
10229 II->setOperand(2, LHS);
10230 return II;
10231 }
10232
10233 // X * undef -> undef
10234 if (isa<UndefValue>(II->getOperand(2)))
10235 return ReplaceInstUsesWith(CI, UndefValue::get(II->getType()));
10236
10237 if (ConstantInt *RHSI = dyn_cast<ConstantInt>(II->getOperand(2))) {
10238 // X*0 -> {0, false}
10239 if (RHSI->isZero())
10240 return ReplaceInstUsesWith(CI, Constant::getNullValue(II->getType()));
10241
10242 // X * 1 -> {X, false}
10243 if (RHSI->equalsInt(1)) {
Chris Lattnercd188e92009-11-29 02:57:29 +000010244 Constant *V[] = {
10245 UndefValue::get(II->getOperand(1)->getType()),
Chris Lattner4de84762010-01-04 07:02:48 +000010246 ConstantInt::getFalse(II->getContext())
Chris Lattnercd188e92009-11-29 02:57:29 +000010247 };
Chris Lattner4de84762010-01-04 07:02:48 +000010248 Constant *Struct = ConstantStruct::get(II->getContext(), V, 2, false);
Chris Lattnercd188e92009-11-29 02:57:29 +000010249 return InsertValueInst::Create(Struct, II->getOperand(1), 0);
Chris Lattner2bbac752009-11-26 21:42:47 +000010250 }
10251 }
10252 break;
Chris Lattner0521e3c2008-06-18 04:33:20 +000010253 case Intrinsic::ppc_altivec_lvx:
10254 case Intrinsic::ppc_altivec_lvxl:
10255 case Intrinsic::x86_sse_loadu_ps:
10256 case Intrinsic::x86_sse2_loadu_pd:
10257 case Intrinsic::x86_sse2_loadu_dq:
10258 // Turn PPC lvx -> load if the pointer is known aligned.
10259 // Turn X86 loadups -> load if the pointer is known aligned.
10260 if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
Chris Lattner08142f22009-08-30 19:47:22 +000010261 Value *Ptr = Builder->CreateBitCast(II->getOperand(1),
10262 PointerType::getUnqual(II->getType()));
Chris Lattner0521e3c2008-06-18 04:33:20 +000010263 return new LoadInst(Ptr);
Chris Lattner867b99f2006-10-05 06:55:50 +000010264 }
Chris Lattner0521e3c2008-06-18 04:33:20 +000010265 break;
10266 case Intrinsic::ppc_altivec_stvx:
10267 case Intrinsic::ppc_altivec_stvxl:
10268 // Turn stvx -> store if the pointer is known aligned.
10269 if (GetOrEnforceKnownAlignment(II->getOperand(2), 16) >= 16) {
10270 const Type *OpPtrTy =
Owen Andersondebcb012009-07-29 22:17:13 +000010271 PointerType::getUnqual(II->getOperand(1)->getType());
Chris Lattner08142f22009-08-30 19:47:22 +000010272 Value *Ptr = Builder->CreateBitCast(II->getOperand(2), OpPtrTy);
Chris Lattner0521e3c2008-06-18 04:33:20 +000010273 return new StoreInst(II->getOperand(1), Ptr);
10274 }
10275 break;
10276 case Intrinsic::x86_sse_storeu_ps:
10277 case Intrinsic::x86_sse2_storeu_pd:
10278 case Intrinsic::x86_sse2_storeu_dq:
Chris Lattner0521e3c2008-06-18 04:33:20 +000010279 // Turn X86 storeu -> store if the pointer is known aligned.
10280 if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
10281 const Type *OpPtrTy =
Owen Andersondebcb012009-07-29 22:17:13 +000010282 PointerType::getUnqual(II->getOperand(2)->getType());
Chris Lattner08142f22009-08-30 19:47:22 +000010283 Value *Ptr = Builder->CreateBitCast(II->getOperand(1), OpPtrTy);
Chris Lattner0521e3c2008-06-18 04:33:20 +000010284 return new StoreInst(II->getOperand(2), Ptr);
10285 }
10286 break;
10287
10288 case Intrinsic::x86_sse_cvttss2si: {
10289 // These intrinsics only demands the 0th element of its input vector. If
10290 // we can simplify the input based on that, do so now.
Evan Cheng388df622009-02-03 10:05:09 +000010291 unsigned VWidth =
10292 cast<VectorType>(II->getOperand(1)->getType())->getNumElements();
10293 APInt DemandedElts(VWidth, 1);
10294 APInt UndefElts(VWidth, 0);
10295 if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
Chris Lattner0521e3c2008-06-18 04:33:20 +000010296 UndefElts)) {
10297 II->setOperand(1, V);
10298 return II;
10299 }
10300 break;
10301 }
10302
10303 case Intrinsic::ppc_altivec_vperm:
10304 // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
10305 if (ConstantVector *Mask = dyn_cast<ConstantVector>(II->getOperand(3))) {
10306 assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
Chris Lattner867b99f2006-10-05 06:55:50 +000010307
Chris Lattner0521e3c2008-06-18 04:33:20 +000010308 // Check that all of the elements are integer constants or undefs.
10309 bool AllEltsOk = true;
10310 for (unsigned i = 0; i != 16; ++i) {
10311 if (!isa<ConstantInt>(Mask->getOperand(i)) &&
10312 !isa<UndefValue>(Mask->getOperand(i))) {
10313 AllEltsOk = false;
10314 break;
10315 }
10316 }
10317
10318 if (AllEltsOk) {
10319 // Cast the input vectors to byte vectors.
Chris Lattner08142f22009-08-30 19:47:22 +000010320 Value *Op0 = Builder->CreateBitCast(II->getOperand(1), Mask->getType());
10321 Value *Op1 = Builder->CreateBitCast(II->getOperand(2), Mask->getType());
Owen Anderson9e9a0d52009-07-30 23:03:37 +000010322 Value *Result = UndefValue::get(Op0->getType());
Chris Lattnere2ed0572006-04-06 19:19:17 +000010323
Chris Lattner0521e3c2008-06-18 04:33:20 +000010324 // Only extract each element once.
10325 Value *ExtractedElts[32];
10326 memset(ExtractedElts, 0, sizeof(ExtractedElts));
10327
Chris Lattnere2ed0572006-04-06 19:19:17 +000010328 for (unsigned i = 0; i != 16; ++i) {
Chris Lattner0521e3c2008-06-18 04:33:20 +000010329 if (isa<UndefValue>(Mask->getOperand(i)))
10330 continue;
10331 unsigned Idx=cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
10332 Idx &= 31; // Match the hardware behavior.
10333
10334 if (ExtractedElts[Idx] == 0) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +000010335 ExtractedElts[Idx] =
10336 Builder->CreateExtractElement(Idx < 16 ? Op0 : Op1,
Chris Lattner4de84762010-01-04 07:02:48 +000010337 ConstantInt::get(Type::getInt32Ty(II->getContext()),
10338 Idx&15, false), "tmp");
Chris Lattnere2ed0572006-04-06 19:19:17 +000010339 }
Chris Lattnere2ed0572006-04-06 19:19:17 +000010340
Chris Lattner0521e3c2008-06-18 04:33:20 +000010341 // Insert this value into the result vector.
Chris Lattnerf925cbd2009-08-30 18:50:58 +000010342 Result = Builder->CreateInsertElement(Result, ExtractedElts[Idx],
Chris Lattner4de84762010-01-04 07:02:48 +000010343 ConstantInt::get(Type::getInt32Ty(II->getContext()),
10344 i, false), "tmp");
Chris Lattnere2ed0572006-04-06 19:19:17 +000010345 }
Chris Lattner0521e3c2008-06-18 04:33:20 +000010346 return CastInst::Create(Instruction::BitCast, Result, CI.getType());
Chris Lattnere2ed0572006-04-06 19:19:17 +000010347 }
Chris Lattner0521e3c2008-06-18 04:33:20 +000010348 }
10349 break;
Chris Lattnere2ed0572006-04-06 19:19:17 +000010350
Chris Lattner0521e3c2008-06-18 04:33:20 +000010351 case Intrinsic::stackrestore: {
10352 // If the save is right next to the restore, remove the restore. This can
10353 // happen when variable allocas are DCE'd.
10354 if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
10355 if (SS->getIntrinsicID() == Intrinsic::stacksave) {
10356 BasicBlock::iterator BI = SS;
10357 if (&*++BI == II)
10358 return EraseInstFromFunction(CI);
Chris Lattnera728ddc2006-01-13 21:28:09 +000010359 }
Chris Lattner0521e3c2008-06-18 04:33:20 +000010360 }
10361
10362 // Scan down this block to see if there is another stack restore in the
10363 // same block without an intervening call/alloca.
10364 BasicBlock::iterator BI = II;
10365 TerminatorInst *TI = II->getParent()->getTerminator();
10366 bool CannotRemove = false;
10367 for (++BI; &*BI != TI; ++BI) {
Victor Hernandez83d63912009-09-18 22:35:49 +000010368 if (isa<AllocaInst>(BI) || isMalloc(BI)) {
Chris Lattner0521e3c2008-06-18 04:33:20 +000010369 CannotRemove = true;
10370 break;
10371 }
Chris Lattneraa0bf522008-06-25 05:59:28 +000010372 if (CallInst *BCI = dyn_cast<CallInst>(BI)) {
10373 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(BCI)) {
10374 // If there is a stackrestore below this one, remove this one.
10375 if (II->getIntrinsicID() == Intrinsic::stackrestore)
10376 return EraseInstFromFunction(CI);
10377 // Otherwise, ignore the intrinsic.
10378 } else {
10379 // If we found a non-intrinsic call, we can't remove the stack
10380 // restore.
Chris Lattnerbf1d8a72008-02-18 06:12:38 +000010381 CannotRemove = true;
10382 break;
10383 }
Chris Lattner0521e3c2008-06-18 04:33:20 +000010384 }
Chris Lattnera728ddc2006-01-13 21:28:09 +000010385 }
Chris Lattner0521e3c2008-06-18 04:33:20 +000010386
10387 // If the stack restore is in a return/unwind block and if there are no
10388 // allocas or calls between the restore and the return, nuke the restore.
10389 if (!CannotRemove && (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)))
10390 return EraseInstFromFunction(CI);
10391 break;
10392 }
Chris Lattner35b9e482004-10-12 04:52:52 +000010393 }
10394
Chris Lattner8b0ea312006-01-13 20:11:04 +000010395 return visitCallSite(II);
Chris Lattner9fe38862003-06-19 17:00:31 +000010396}
10397
10398// InvokeInst simplification
10399//
10400Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
Chris Lattnera44d8a22003-10-07 22:32:43 +000010401 return visitCallSite(&II);
Chris Lattner9fe38862003-06-19 17:00:31 +000010402}
10403
Dale Johannesenda30ccb2008-04-25 21:16:07 +000010404/// isSafeToEliminateVarargsCast - If this cast does not affect the value
10405/// passed through the varargs area, we can eliminate the use of the cast.
Dale Johannesen1f530a52008-04-23 18:34:37 +000010406static bool isSafeToEliminateVarargsCast(const CallSite CS,
10407 const CastInst * const CI,
10408 const TargetData * const TD,
10409 const int ix) {
10410 if (!CI->isLosslessCast())
10411 return false;
10412
10413 // The size of ByVal arguments is derived from the type, so we
10414 // can't change to a type with a different size. If the size were
10415 // passed explicitly we could avoid this check.
Devang Patel05988662008-09-25 21:00:45 +000010416 if (!CS.paramHasAttr(ix, Attribute::ByVal))
Dale Johannesen1f530a52008-04-23 18:34:37 +000010417 return true;
10418
10419 const Type* SrcTy =
10420 cast<PointerType>(CI->getOperand(0)->getType())->getElementType();
10421 const Type* DstTy = cast<PointerType>(CI->getType())->getElementType();
10422 if (!SrcTy->isSized() || !DstTy->isSized())
10423 return false;
Dan Gohmance9fe9f2009-07-21 23:21:54 +000010424 if (!TD || TD->getTypeAllocSize(SrcTy) != TD->getTypeAllocSize(DstTy))
Dale Johannesen1f530a52008-04-23 18:34:37 +000010425 return false;
10426 return true;
10427}
10428
Chris Lattnera44d8a22003-10-07 22:32:43 +000010429// visitCallSite - Improvements for call and invoke instructions.
10430//
10431Instruction *InstCombiner::visitCallSite(CallSite CS) {
Chris Lattner6c266db2003-10-07 22:54:13 +000010432 bool Changed = false;
10433
10434 // If the callee is a constexpr cast of a function, attempt to move the cast
10435 // to the arguments of the call/invoke.
Chris Lattnera44d8a22003-10-07 22:32:43 +000010436 if (transformConstExprCastCall(CS)) return 0;
10437
Chris Lattner6c266db2003-10-07 22:54:13 +000010438 Value *Callee = CS.getCalledValue();
Chris Lattnere87597f2004-10-16 18:11:37 +000010439
Chris Lattner08b22ec2005-05-13 07:09:09 +000010440 if (Function *CalleeF = dyn_cast<Function>(Callee))
10441 if (CalleeF->getCallingConv() != CS.getCallingConv()) {
10442 Instruction *OldCall = CS.getInstruction();
10443 // If the call and callee calling conventions don't match, this call must
10444 // be unreachable, as the call is undefined.
Chris Lattner4de84762010-01-04 07:02:48 +000010445 new StoreInst(ConstantInt::getTrue(Callee->getContext()),
10446 UndefValue::get(Type::getInt1PtrTy(Callee->getContext())),
Owen Andersond672ecb2009-07-03 00:17:18 +000010447 OldCall);
Devang Patel228ebd02009-10-13 22:56:32 +000010448 // If OldCall dues not return void then replaceAllUsesWith undef.
10449 // This allows ValueHandlers and custom metadata to adjust itself.
Devang Patel9674d152009-10-14 17:29:00 +000010450 if (!OldCall->getType()->isVoidTy())
Devang Patel228ebd02009-10-13 22:56:32 +000010451 OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
Chris Lattner08b22ec2005-05-13 07:09:09 +000010452 if (isa<CallInst>(OldCall)) // Not worth removing an invoke here.
10453 return EraseInstFromFunction(*OldCall);
10454 return 0;
10455 }
10456
Chris Lattner17be6352004-10-18 02:59:09 +000010457 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
10458 // This instruction is not reachable, just remove it. We insert a store to
10459 // undef so that we know that this code is not reachable, despite the fact
10460 // that we can't modify the CFG here.
Chris Lattner4de84762010-01-04 07:02:48 +000010461 new StoreInst(ConstantInt::getTrue(Callee->getContext()),
10462 UndefValue::get(Type::getInt1PtrTy(Callee->getContext())),
Chris Lattner17be6352004-10-18 02:59:09 +000010463 CS.getInstruction());
10464
Devang Patel228ebd02009-10-13 22:56:32 +000010465 // If CS dues not return void then replaceAllUsesWith undef.
10466 // This allows ValueHandlers and custom metadata to adjust itself.
Devang Patel9674d152009-10-14 17:29:00 +000010467 if (!CS.getInstruction()->getType()->isVoidTy())
Devang Patel228ebd02009-10-13 22:56:32 +000010468 CS.getInstruction()->
10469 replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
Chris Lattner17be6352004-10-18 02:59:09 +000010470
10471 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
10472 // Don't break the CFG, insert a dummy cond branch.
Gabor Greif051a9502008-04-06 20:25:17 +000010473 BranchInst::Create(II->getNormalDest(), II->getUnwindDest(),
Chris Lattner4de84762010-01-04 07:02:48 +000010474 ConstantInt::getTrue(Callee->getContext()), II);
Chris Lattnere87597f2004-10-16 18:11:37 +000010475 }
Chris Lattner17be6352004-10-18 02:59:09 +000010476 return EraseInstFromFunction(*CS.getInstruction());
10477 }
Chris Lattnere87597f2004-10-16 18:11:37 +000010478
Duncan Sandscdb6d922007-09-17 10:26:40 +000010479 if (BitCastInst *BC = dyn_cast<BitCastInst>(Callee))
10480 if (IntrinsicInst *In = dyn_cast<IntrinsicInst>(BC->getOperand(0)))
10481 if (In->getIntrinsicID() == Intrinsic::init_trampoline)
10482 return transformCallThroughTrampoline(CS);
10483
Chris Lattner6c266db2003-10-07 22:54:13 +000010484 const PointerType *PTy = cast<PointerType>(Callee->getType());
10485 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
10486 if (FTy->isVarArg()) {
Dale Johannesen63e7eb42008-04-23 01:03:05 +000010487 int ix = FTy->getNumParams() + (isa<InvokeInst>(Callee) ? 3 : 1);
Chris Lattner6c266db2003-10-07 22:54:13 +000010488 // See if we can optimize any arguments passed through the varargs area of
10489 // the call.
10490 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
Dale Johannesen1f530a52008-04-23 18:34:37 +000010491 E = CS.arg_end(); I != E; ++I, ++ix) {
10492 CastInst *CI = dyn_cast<CastInst>(*I);
10493 if (CI && isSafeToEliminateVarargsCast(CS, CI, TD, ix)) {
10494 *I = CI->getOperand(0);
10495 Changed = true;
Chris Lattner6c266db2003-10-07 22:54:13 +000010496 }
Dale Johannesen1f530a52008-04-23 18:34:37 +000010497 }
Chris Lattner6c266db2003-10-07 22:54:13 +000010498 }
Misha Brukmanfd939082005-04-21 23:48:37 +000010499
Duncan Sandsf0c33542007-12-19 21:13:37 +000010500 if (isa<InlineAsm>(Callee) && !CS.doesNotThrow()) {
Duncan Sandsece2c042007-12-16 15:51:49 +000010501 // Inline asm calls cannot throw - mark them 'nounwind'.
Duncan Sandsf0c33542007-12-19 21:13:37 +000010502 CS.setDoesNotThrow();
Duncan Sandsece2c042007-12-16 15:51:49 +000010503 Changed = true;
10504 }
10505
Chris Lattner6c266db2003-10-07 22:54:13 +000010506 return Changed ? CS.getInstruction() : 0;
Chris Lattnera44d8a22003-10-07 22:32:43 +000010507}
10508
Chris Lattner9fe38862003-06-19 17:00:31 +000010509// transformConstExprCastCall - If the callee is a constexpr cast of a function,
10510// attempt to move the cast to the arguments of the call/invoke.
10511//
10512bool InstCombiner::transformConstExprCastCall(CallSite CS) {
10513 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
10514 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
Reid Spencer3da59db2006-11-27 01:05:10 +000010515 if (CE->getOpcode() != Instruction::BitCast ||
10516 !isa<Function>(CE->getOperand(0)))
Chris Lattner9fe38862003-06-19 17:00:31 +000010517 return false;
Reid Spencer8863f182004-07-18 00:38:32 +000010518 Function *Callee = cast<Function>(CE->getOperand(0));
Chris Lattner9fe38862003-06-19 17:00:31 +000010519 Instruction *Caller = CS.getInstruction();
Devang Patel05988662008-09-25 21:00:45 +000010520 const AttrListPtr &CallerPAL = CS.getAttributes();
Chris Lattner9fe38862003-06-19 17:00:31 +000010521
10522 // Okay, this is a cast from a function to a different type. Unless doing so
10523 // would cause a type conversion of one of our arguments, change this call to
10524 // be a direct call with arguments casted to the appropriate types.
10525 //
10526 const FunctionType *FT = Callee->getFunctionType();
10527 const Type *OldRetTy = Caller->getType();
Duncan Sandsf413cdf2008-06-01 07:38:42 +000010528 const Type *NewRetTy = FT->getReturnType();
Chris Lattner9fe38862003-06-19 17:00:31 +000010529
Duncan Sandsf413cdf2008-06-01 07:38:42 +000010530 if (isa<StructType>(NewRetTy))
Devang Patel75e6f022008-03-11 18:04:06 +000010531 return false; // TODO: Handle multiple return values.
10532
Chris Lattnerf78616b2004-01-14 06:06:08 +000010533 // Check to see if we are changing the return type...
Duncan Sandsf413cdf2008-06-01 07:38:42 +000010534 if (OldRetTy != NewRetTy) {
Bill Wendlinga6c31122008-05-14 22:45:20 +000010535 if (Callee->isDeclaration() &&
Duncan Sandsf413cdf2008-06-01 07:38:42 +000010536 // Conversion is ok if changing from one pointer type to another or from
10537 // a pointer to an integer of the same size.
Dan Gohmance9fe9f2009-07-21 23:21:54 +000010538 !((isa<PointerType>(OldRetTy) || !TD ||
Owen Anderson1d0be152009-08-13 21:58:54 +000010539 OldRetTy == TD->getIntPtrType(Caller->getContext())) &&
Dan Gohmance9fe9f2009-07-21 23:21:54 +000010540 (isa<PointerType>(NewRetTy) || !TD ||
Owen Anderson1d0be152009-08-13 21:58:54 +000010541 NewRetTy == TD->getIntPtrType(Caller->getContext()))))
Chris Lattnerec479922007-01-06 02:09:32 +000010542 return false; // Cannot transform this return value.
Chris Lattnerf78616b2004-01-14 06:06:08 +000010543
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010544 if (!Caller->use_empty() &&
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010545 // void -> non-void is handled specially
Devang Patel9674d152009-10-14 17:29:00 +000010546 !NewRetTy->isVoidTy() && !CastInst::isCastable(NewRetTy, OldRetTy))
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010547 return false; // Cannot transform this return value.
10548
Chris Lattner58d74912008-03-12 17:45:29 +000010549 if (!CallerPAL.isEmpty() && !Caller->use_empty()) {
Devang Patel19c87462008-09-26 22:53:05 +000010550 Attributes RAttrs = CallerPAL.getRetAttributes();
Devang Patel05988662008-09-25 21:00:45 +000010551 if (RAttrs & Attribute::typeIncompatible(NewRetTy))
Duncan Sands6c3470e2008-01-07 17:16:06 +000010552 return false; // Attribute not compatible with transformed value.
10553 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010554
Chris Lattnerf78616b2004-01-14 06:06:08 +000010555 // If the callsite is an invoke instruction, and the return value is used by
10556 // a PHI node in a successor, we cannot change the return type of the call
10557 // because there is no place to put the cast instruction (without breaking
10558 // the critical edge). Bail out in this case.
10559 if (!Caller->use_empty())
10560 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
10561 for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
10562 UI != E; ++UI)
10563 if (PHINode *PN = dyn_cast<PHINode>(*UI))
10564 if (PN->getParent() == II->getNormalDest() ||
Chris Lattneraeb2a1d2004-02-08 21:44:31 +000010565 PN->getParent() == II->getUnwindDest())
Chris Lattnerf78616b2004-01-14 06:06:08 +000010566 return false;
10567 }
Chris Lattner9fe38862003-06-19 17:00:31 +000010568
10569 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
10570 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
Misha Brukmanfd939082005-04-21 23:48:37 +000010571
Chris Lattner9fe38862003-06-19 17:00:31 +000010572 CallSite::arg_iterator AI = CS.arg_begin();
10573 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
10574 const Type *ParamTy = FT->getParamType(i);
Andrew Lenharthb8e604c2006-06-28 01:01:52 +000010575 const Type *ActTy = (*AI)->getType();
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010576
10577 if (!CastInst::isCastable(ActTy, ParamTy))
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010578 return false; // Cannot transform this parameter value.
10579
Devang Patel19c87462008-09-26 22:53:05 +000010580 if (CallerPAL.getParamAttributes(i + 1)
10581 & Attribute::typeIncompatible(ParamTy))
Chris Lattner58d74912008-03-12 17:45:29 +000010582 return false; // Attribute not compatible with transformed value.
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010583
Duncan Sandsf413cdf2008-06-01 07:38:42 +000010584 // Converting from one pointer type to another or between a pointer and an
10585 // integer of the same size is safe even if we do not have a body.
Chris Lattnerec479922007-01-06 02:09:32 +000010586 bool isConvertible = ActTy == ParamTy ||
Owen Anderson1d0be152009-08-13 21:58:54 +000010587 (TD && ((isa<PointerType>(ParamTy) ||
10588 ParamTy == TD->getIntPtrType(Caller->getContext())) &&
10589 (isa<PointerType>(ActTy) ||
10590 ActTy == TD->getIntPtrType(Caller->getContext()))));
Reid Spencer5cbf9852007-01-30 20:08:39 +000010591 if (Callee->isDeclaration() && !isConvertible) return false;
Chris Lattner9fe38862003-06-19 17:00:31 +000010592 }
10593
10594 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
Reid Spencer5cbf9852007-01-30 20:08:39 +000010595 Callee->isDeclaration())
Chris Lattner58d74912008-03-12 17:45:29 +000010596 return false; // Do not delete arguments unless we have a function body.
Chris Lattner9fe38862003-06-19 17:00:31 +000010597
Chris Lattner58d74912008-03-12 17:45:29 +000010598 if (FT->getNumParams() < NumActualArgs && FT->isVarArg() &&
10599 !CallerPAL.isEmpty())
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010600 // In this case we have more arguments than the new function type, but we
Duncan Sandse1e520f2008-01-13 08:02:44 +000010601 // won't be dropping them. Check that these extra arguments have attributes
10602 // that are compatible with being a vararg call argument.
Chris Lattner58d74912008-03-12 17:45:29 +000010603 for (unsigned i = CallerPAL.getNumSlots(); i; --i) {
10604 if (CallerPAL.getSlot(i - 1).Index <= FT->getNumParams())
Duncan Sandse1e520f2008-01-13 08:02:44 +000010605 break;
Devang Pateleaf42ab2008-09-23 23:03:40 +000010606 Attributes PAttrs = CallerPAL.getSlot(i - 1).Attrs;
Devang Patel05988662008-09-25 21:00:45 +000010607 if (PAttrs & Attribute::VarArgsIncompatible)
Duncan Sandse1e520f2008-01-13 08:02:44 +000010608 return false;
10609 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010610
Chris Lattner9fe38862003-06-19 17:00:31 +000010611 // Okay, we decided that this is a safe thing to do: go ahead and start
10612 // inserting cast instructions as necessary...
10613 std::vector<Value*> Args;
10614 Args.reserve(NumActualArgs);
Devang Patel05988662008-09-25 21:00:45 +000010615 SmallVector<AttributeWithIndex, 8> attrVec;
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010616 attrVec.reserve(NumCommonArgs);
10617
10618 // Get any return attributes.
Devang Patel19c87462008-09-26 22:53:05 +000010619 Attributes RAttrs = CallerPAL.getRetAttributes();
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010620
10621 // If the return value is not being used, the type may not be compatible
10622 // with the existing attributes. Wipe out any problematic attributes.
Devang Patel05988662008-09-25 21:00:45 +000010623 RAttrs &= ~Attribute::typeIncompatible(NewRetTy);
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010624
10625 // Add the new return attributes.
10626 if (RAttrs)
Devang Patel05988662008-09-25 21:00:45 +000010627 attrVec.push_back(AttributeWithIndex::get(0, RAttrs));
Chris Lattner9fe38862003-06-19 17:00:31 +000010628
10629 AI = CS.arg_begin();
10630 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
10631 const Type *ParamTy = FT->getParamType(i);
10632 if ((*AI)->getType() == ParamTy) {
10633 Args.push_back(*AI);
10634 } else {
Reid Spencer8a903db2006-12-18 08:47:13 +000010635 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
Reid Spencerc5b206b2006-12-31 05:48:39 +000010636 false, ParamTy, false);
Chris Lattnerf925cbd2009-08-30 18:50:58 +000010637 Args.push_back(Builder->CreateCast(opcode, *AI, ParamTy, "tmp"));
Chris Lattner9fe38862003-06-19 17:00:31 +000010638 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010639
10640 // Add any parameter attributes.
Devang Patel19c87462008-09-26 22:53:05 +000010641 if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
Devang Patel05988662008-09-25 21:00:45 +000010642 attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
Chris Lattner9fe38862003-06-19 17:00:31 +000010643 }
10644
10645 // If the function takes more arguments than the call was taking, add them
Chris Lattnerf925cbd2009-08-30 18:50:58 +000010646 // now.
Chris Lattner9fe38862003-06-19 17:00:31 +000010647 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
Owen Andersona7235ea2009-07-31 20:28:14 +000010648 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
Chris Lattner9fe38862003-06-19 17:00:31 +000010649
Chris Lattnerf925cbd2009-08-30 18:50:58 +000010650 // If we are removing arguments to the function, emit an obnoxious warning.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000010651 if (FT->getNumParams() < NumActualArgs) {
Chris Lattner9fe38862003-06-19 17:00:31 +000010652 if (!FT->isVarArg()) {
Daniel Dunbarce63ffb2009-07-25 00:23:56 +000010653 errs() << "WARNING: While resolving call to function '"
10654 << Callee->getName() << "' arguments were dropped!\n";
Chris Lattner9fe38862003-06-19 17:00:31 +000010655 } else {
Chris Lattnerf925cbd2009-08-30 18:50:58 +000010656 // Add all of the arguments in their promoted form to the arg list.
Chris Lattner9fe38862003-06-19 17:00:31 +000010657 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
10658 const Type *PTy = getPromotedType((*AI)->getType());
10659 if (PTy != (*AI)->getType()) {
10660 // Must promote to pass through va_arg area!
Chris Lattnerf925cbd2009-08-30 18:50:58 +000010661 Instruction::CastOps opcode =
10662 CastInst::getCastOpcode(*AI, false, PTy, false);
10663 Args.push_back(Builder->CreateCast(opcode, *AI, PTy, "tmp"));
Chris Lattner9fe38862003-06-19 17:00:31 +000010664 } else {
10665 Args.push_back(*AI);
10666 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010667
Duncan Sandse1e520f2008-01-13 08:02:44 +000010668 // Add any parameter attributes.
Devang Patel19c87462008-09-26 22:53:05 +000010669 if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
Devang Patel05988662008-09-25 21:00:45 +000010670 attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
Duncan Sandse1e520f2008-01-13 08:02:44 +000010671 }
Chris Lattner9fe38862003-06-19 17:00:31 +000010672 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000010673 }
Chris Lattner9fe38862003-06-19 17:00:31 +000010674
Devang Patel19c87462008-09-26 22:53:05 +000010675 if (Attributes FnAttrs = CallerPAL.getFnAttributes())
10676 attrVec.push_back(AttributeWithIndex::get(~0, FnAttrs));
10677
Devang Patel9674d152009-10-14 17:29:00 +000010678 if (NewRetTy->isVoidTy())
Chris Lattner6934a042007-02-11 01:23:03 +000010679 Caller->setName(""); // Void type should not have a name.
Chris Lattner9fe38862003-06-19 17:00:31 +000010680
Eric Christophera66297a2009-07-25 02:45:27 +000010681 const AttrListPtr &NewCallerPAL = AttrListPtr::get(attrVec.begin(),
10682 attrVec.end());
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010683
Chris Lattner9fe38862003-06-19 17:00:31 +000010684 Instruction *NC;
10685 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Gabor Greif051a9502008-04-06 20:25:17 +000010686 NC = InvokeInst::Create(Callee, II->getNormalDest(), II->getUnwindDest(),
Gabor Greifb1dbcd82008-05-15 10:04:30 +000010687 Args.begin(), Args.end(),
10688 Caller->getName(), Caller);
Reid Spencered3fa852007-07-30 19:53:57 +000010689 cast<InvokeInst>(NC)->setCallingConv(II->getCallingConv());
Devang Patel05988662008-09-25 21:00:45 +000010690 cast<InvokeInst>(NC)->setAttributes(NewCallerPAL);
Chris Lattner9fe38862003-06-19 17:00:31 +000010691 } else {
Gabor Greif051a9502008-04-06 20:25:17 +000010692 NC = CallInst::Create(Callee, Args.begin(), Args.end(),
10693 Caller->getName(), Caller);
Duncan Sandsdc024672007-11-27 13:23:08 +000010694 CallInst *CI = cast<CallInst>(Caller);
10695 if (CI->isTailCall())
Chris Lattnera9e92112005-05-06 06:48:21 +000010696 cast<CallInst>(NC)->setTailCall();
Duncan Sandsdc024672007-11-27 13:23:08 +000010697 cast<CallInst>(NC)->setCallingConv(CI->getCallingConv());
Devang Patel05988662008-09-25 21:00:45 +000010698 cast<CallInst>(NC)->setAttributes(NewCallerPAL);
Chris Lattner9fe38862003-06-19 17:00:31 +000010699 }
10700
Chris Lattner6934a042007-02-11 01:23:03 +000010701 // Insert a cast of the return type as necessary.
Chris Lattner9fe38862003-06-19 17:00:31 +000010702 Value *NV = NC;
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010703 if (OldRetTy != NV->getType() && !Caller->use_empty()) {
Devang Patel9674d152009-10-14 17:29:00 +000010704 if (!NV->getType()->isVoidTy()) {
Reid Spencerc5b206b2006-12-31 05:48:39 +000010705 Instruction::CastOps opcode = CastInst::getCastOpcode(NC, false,
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010706 OldRetTy, false);
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010707 NV = NC = CastInst::Create(opcode, NC, OldRetTy, "tmp");
Chris Lattnerbb609042003-10-30 00:46:41 +000010708
10709 // If this is an invoke instruction, we should insert it after the first
10710 // non-phi, instruction in the normal successor block.
10711 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Dan Gohman02dea8b2008-05-23 21:05:58 +000010712 BasicBlock::iterator I = II->getNormalDest()->getFirstNonPHI();
Chris Lattnerbb609042003-10-30 00:46:41 +000010713 InsertNewInstBefore(NC, *I);
10714 } else {
10715 // Otherwise, it's a call, just insert cast right after the call instr
10716 InsertNewInstBefore(NC, *Caller);
10717 }
Chris Lattnere5ecdb52009-08-30 06:22:51 +000010718 Worklist.AddUsersToWorkList(*Caller);
Chris Lattner9fe38862003-06-19 17:00:31 +000010719 } else {
Owen Anderson9e9a0d52009-07-30 23:03:37 +000010720 NV = UndefValue::get(Caller->getType());
Chris Lattner9fe38862003-06-19 17:00:31 +000010721 }
10722 }
10723
Devang Patel1bf5ebc2009-10-13 21:41:20 +000010724
Chris Lattner931f8f32009-08-31 05:17:58 +000010725 if (!Caller->use_empty())
Chris Lattner9fe38862003-06-19 17:00:31 +000010726 Caller->replaceAllUsesWith(NV);
Chris Lattner931f8f32009-08-31 05:17:58 +000010727
10728 EraseInstFromFunction(*Caller);
Chris Lattner9fe38862003-06-19 17:00:31 +000010729 return true;
10730}
10731
Duncan Sandscdb6d922007-09-17 10:26:40 +000010732// transformCallThroughTrampoline - Turn a call to a function created by the
10733// init_trampoline intrinsic into a direct call to the underlying function.
10734//
10735Instruction *InstCombiner::transformCallThroughTrampoline(CallSite CS) {
10736 Value *Callee = CS.getCalledValue();
10737 const PointerType *PTy = cast<PointerType>(Callee->getType());
10738 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
Devang Patel05988662008-09-25 21:00:45 +000010739 const AttrListPtr &Attrs = CS.getAttributes();
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010740
10741 // If the call already has the 'nest' attribute somewhere then give up -
10742 // otherwise 'nest' would occur twice after splicing in the chain.
Devang Patel05988662008-09-25 21:00:45 +000010743 if (Attrs.hasAttrSomewhere(Attribute::Nest))
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010744 return 0;
Duncan Sandscdb6d922007-09-17 10:26:40 +000010745
10746 IntrinsicInst *Tramp =
10747 cast<IntrinsicInst>(cast<BitCastInst>(Callee)->getOperand(0));
10748
Anton Korobeynikov0b12ecf2008-05-07 22:54:15 +000010749 Function *NestF = cast<Function>(Tramp->getOperand(2)->stripPointerCasts());
Duncan Sandscdb6d922007-09-17 10:26:40 +000010750 const PointerType *NestFPTy = cast<PointerType>(NestF->getType());
10751 const FunctionType *NestFTy = cast<FunctionType>(NestFPTy->getElementType());
10752
Devang Patel05988662008-09-25 21:00:45 +000010753 const AttrListPtr &NestAttrs = NestF->getAttributes();
Chris Lattner58d74912008-03-12 17:45:29 +000010754 if (!NestAttrs.isEmpty()) {
Duncan Sandscdb6d922007-09-17 10:26:40 +000010755 unsigned NestIdx = 1;
10756 const Type *NestTy = 0;
Devang Patel05988662008-09-25 21:00:45 +000010757 Attributes NestAttr = Attribute::None;
Duncan Sandscdb6d922007-09-17 10:26:40 +000010758
10759 // Look for a parameter marked with the 'nest' attribute.
10760 for (FunctionType::param_iterator I = NestFTy->param_begin(),
10761 E = NestFTy->param_end(); I != E; ++NestIdx, ++I)
Devang Patel05988662008-09-25 21:00:45 +000010762 if (NestAttrs.paramHasAttr(NestIdx, Attribute::Nest)) {
Duncan Sandscdb6d922007-09-17 10:26:40 +000010763 // Record the parameter type and any other attributes.
10764 NestTy = *I;
Devang Patel19c87462008-09-26 22:53:05 +000010765 NestAttr = NestAttrs.getParamAttributes(NestIdx);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010766 break;
10767 }
10768
10769 if (NestTy) {
10770 Instruction *Caller = CS.getInstruction();
10771 std::vector<Value*> NewArgs;
10772 NewArgs.reserve(unsigned(CS.arg_end()-CS.arg_begin())+1);
10773
Devang Patel05988662008-09-25 21:00:45 +000010774 SmallVector<AttributeWithIndex, 8> NewAttrs;
Chris Lattner58d74912008-03-12 17:45:29 +000010775 NewAttrs.reserve(Attrs.getNumSlots() + 1);
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010776
Duncan Sandscdb6d922007-09-17 10:26:40 +000010777 // Insert the nest argument into the call argument list, which may
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010778 // mean appending it. Likewise for attributes.
10779
Devang Patel19c87462008-09-26 22:53:05 +000010780 // Add any result attributes.
10781 if (Attributes Attr = Attrs.getRetAttributes())
Devang Patel05988662008-09-25 21:00:45 +000010782 NewAttrs.push_back(AttributeWithIndex::get(0, Attr));
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010783
Duncan Sandscdb6d922007-09-17 10:26:40 +000010784 {
10785 unsigned Idx = 1;
10786 CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
10787 do {
10788 if (Idx == NestIdx) {
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010789 // Add the chain argument and attributes.
Duncan Sandscdb6d922007-09-17 10:26:40 +000010790 Value *NestVal = Tramp->getOperand(3);
10791 if (NestVal->getType() != NestTy)
10792 NestVal = new BitCastInst(NestVal, NestTy, "nest", Caller);
10793 NewArgs.push_back(NestVal);
Devang Patel05988662008-09-25 21:00:45 +000010794 NewAttrs.push_back(AttributeWithIndex::get(NestIdx, NestAttr));
Duncan Sandscdb6d922007-09-17 10:26:40 +000010795 }
10796
10797 if (I == E)
10798 break;
10799
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010800 // Add the original argument and attributes.
Duncan Sandscdb6d922007-09-17 10:26:40 +000010801 NewArgs.push_back(*I);
Devang Patel19c87462008-09-26 22:53:05 +000010802 if (Attributes Attr = Attrs.getParamAttributes(Idx))
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010803 NewAttrs.push_back
Devang Patel05988662008-09-25 21:00:45 +000010804 (AttributeWithIndex::get(Idx + (Idx >= NestIdx), Attr));
Duncan Sandscdb6d922007-09-17 10:26:40 +000010805
10806 ++Idx, ++I;
10807 } while (1);
10808 }
10809
Devang Patel19c87462008-09-26 22:53:05 +000010810 // Add any function attributes.
10811 if (Attributes Attr = Attrs.getFnAttributes())
10812 NewAttrs.push_back(AttributeWithIndex::get(~0, Attr));
10813
Duncan Sandscdb6d922007-09-17 10:26:40 +000010814 // The trampoline may have been bitcast to a bogus type (FTy).
10815 // Handle this by synthesizing a new function type, equal to FTy
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010816 // with the chain parameter inserted.
Duncan Sandscdb6d922007-09-17 10:26:40 +000010817
Duncan Sandscdb6d922007-09-17 10:26:40 +000010818 std::vector<const Type*> NewTypes;
Duncan Sandscdb6d922007-09-17 10:26:40 +000010819 NewTypes.reserve(FTy->getNumParams()+1);
10820
Duncan Sandscdb6d922007-09-17 10:26:40 +000010821 // Insert the chain's type into the list of parameter types, which may
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010822 // mean appending it.
Duncan Sandscdb6d922007-09-17 10:26:40 +000010823 {
10824 unsigned Idx = 1;
10825 FunctionType::param_iterator I = FTy->param_begin(),
10826 E = FTy->param_end();
10827
10828 do {
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010829 if (Idx == NestIdx)
10830 // Add the chain's type.
Duncan Sandscdb6d922007-09-17 10:26:40 +000010831 NewTypes.push_back(NestTy);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010832
10833 if (I == E)
10834 break;
10835
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010836 // Add the original type.
Duncan Sandscdb6d922007-09-17 10:26:40 +000010837 NewTypes.push_back(*I);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010838
10839 ++Idx, ++I;
10840 } while (1);
10841 }
10842
10843 // Replace the trampoline call with a direct call. Let the generic
10844 // code sort out any function type mismatches.
Owen Andersondebcb012009-07-29 22:17:13 +000010845 FunctionType *NewFTy = FunctionType::get(FTy->getReturnType(), NewTypes,
Owen Andersond672ecb2009-07-03 00:17:18 +000010846 FTy->isVarArg());
10847 Constant *NewCallee =
Owen Andersondebcb012009-07-29 22:17:13 +000010848 NestF->getType() == PointerType::getUnqual(NewFTy) ?
Owen Andersonbaf3c402009-07-29 18:55:55 +000010849 NestF : ConstantExpr::getBitCast(NestF,
Owen Andersondebcb012009-07-29 22:17:13 +000010850 PointerType::getUnqual(NewFTy));
Eric Christophera66297a2009-07-25 02:45:27 +000010851 const AttrListPtr &NewPAL = AttrListPtr::get(NewAttrs.begin(),
10852 NewAttrs.end());
Duncan Sandscdb6d922007-09-17 10:26:40 +000010853
10854 Instruction *NewCaller;
10855 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Gabor Greif051a9502008-04-06 20:25:17 +000010856 NewCaller = InvokeInst::Create(NewCallee,
10857 II->getNormalDest(), II->getUnwindDest(),
10858 NewArgs.begin(), NewArgs.end(),
10859 Caller->getName(), Caller);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010860 cast<InvokeInst>(NewCaller)->setCallingConv(II->getCallingConv());
Devang Patel05988662008-09-25 21:00:45 +000010861 cast<InvokeInst>(NewCaller)->setAttributes(NewPAL);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010862 } else {
Gabor Greif051a9502008-04-06 20:25:17 +000010863 NewCaller = CallInst::Create(NewCallee, NewArgs.begin(), NewArgs.end(),
10864 Caller->getName(), Caller);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010865 if (cast<CallInst>(Caller)->isTailCall())
10866 cast<CallInst>(NewCaller)->setTailCall();
10867 cast<CallInst>(NewCaller)->
10868 setCallingConv(cast<CallInst>(Caller)->getCallingConv());
Devang Patel05988662008-09-25 21:00:45 +000010869 cast<CallInst>(NewCaller)->setAttributes(NewPAL);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010870 }
Devang Patel9674d152009-10-14 17:29:00 +000010871 if (!Caller->getType()->isVoidTy())
Duncan Sandscdb6d922007-09-17 10:26:40 +000010872 Caller->replaceAllUsesWith(NewCaller);
10873 Caller->eraseFromParent();
Chris Lattner7a1e9242009-08-30 06:13:40 +000010874 Worklist.Remove(Caller);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010875 return 0;
10876 }
10877 }
10878
10879 // Replace the trampoline call with a direct call. Since there is no 'nest'
10880 // parameter, there is no need to adjust the argument list. Let the generic
10881 // code sort out any function type mismatches.
10882 Constant *NewCallee =
Owen Andersond672ecb2009-07-03 00:17:18 +000010883 NestF->getType() == PTy ? NestF :
Owen Andersonbaf3c402009-07-29 18:55:55 +000010884 ConstantExpr::getBitCast(NestF, PTy);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010885 CS.setCalledFunction(NewCallee);
10886 return CS.getInstruction();
10887}
10888
Dan Gohman9ad29202009-09-16 16:50:24 +000010889/// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(a,c)]
10890/// 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 +000010891/// and a single binop.
10892Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
10893 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
Chris Lattner38b3dcc2008-12-01 03:42:51 +000010894 assert(isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst));
Chris Lattner7da52b22006-11-01 04:51:18 +000010895 unsigned Opc = FirstInst->getOpcode();
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010896 Value *LHSVal = FirstInst->getOperand(0);
10897 Value *RHSVal = FirstInst->getOperand(1);
10898
10899 const Type *LHSType = LHSVal->getType();
10900 const Type *RHSType = RHSVal->getType();
Chris Lattner7da52b22006-11-01 04:51:18 +000010901
Dan Gohman9ad29202009-09-16 16:50:24 +000010902 // Scan to see if all operands are the same opcode, and all have one use.
Chris Lattner05f18922008-12-01 02:34:36 +000010903 for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
Chris Lattner7da52b22006-11-01 04:51:18 +000010904 Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
Chris Lattnera90a24c2006-11-01 04:55:47 +000010905 if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
Reid Spencere4d87aa2006-12-23 06:05:41 +000010906 // Verify type of the LHS matches so we don't fold cmp's of different
Chris Lattner9c080502006-11-01 07:43:41 +000010907 // types or GEP's with different index types.
10908 I->getOperand(0)->getType() != LHSType ||
10909 I->getOperand(1)->getType() != RHSType)
Chris Lattner7da52b22006-11-01 04:51:18 +000010910 return 0;
Reid Spencere4d87aa2006-12-23 06:05:41 +000010911
10912 // If they are CmpInst instructions, check their predicates
10913 if (Opc == Instruction::ICmp || Opc == Instruction::FCmp)
10914 if (cast<CmpInst>(I)->getPredicate() !=
10915 cast<CmpInst>(FirstInst)->getPredicate())
10916 return 0;
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010917
10918 // Keep track of which operand needs a phi node.
10919 if (I->getOperand(0) != LHSVal) LHSVal = 0;
10920 if (I->getOperand(1) != RHSVal) RHSVal = 0;
Chris Lattner7da52b22006-11-01 04:51:18 +000010921 }
Dan Gohman9ad29202009-09-16 16:50:24 +000010922
10923 // If both LHS and RHS would need a PHI, don't do this transformation,
10924 // because it would increase the number of PHIs entering the block,
10925 // which leads to higher register pressure. This is especially
10926 // bad when the PHIs are in the header of a loop.
10927 if (!LHSVal && !RHSVal)
10928 return 0;
Chris Lattner7da52b22006-11-01 04:51:18 +000010929
Chris Lattner38b3dcc2008-12-01 03:42:51 +000010930 // Otherwise, this is safe to transform!
Chris Lattner53738a42006-11-08 19:42:28 +000010931
Chris Lattner7da52b22006-11-01 04:51:18 +000010932 Value *InLHS = FirstInst->getOperand(0);
Chris Lattner7da52b22006-11-01 04:51:18 +000010933 Value *InRHS = FirstInst->getOperand(1);
Chris Lattner53738a42006-11-08 19:42:28 +000010934 PHINode *NewLHS = 0, *NewRHS = 0;
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010935 if (LHSVal == 0) {
Gabor Greifb1dbcd82008-05-15 10:04:30 +000010936 NewLHS = PHINode::Create(LHSType,
10937 FirstInst->getOperand(0)->getName() + ".pn");
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010938 NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
10939 NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
Chris Lattner9c080502006-11-01 07:43:41 +000010940 InsertNewInstBefore(NewLHS, PN);
10941 LHSVal = NewLHS;
10942 }
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010943
10944 if (RHSVal == 0) {
Gabor Greifb1dbcd82008-05-15 10:04:30 +000010945 NewRHS = PHINode::Create(RHSType,
10946 FirstInst->getOperand(1)->getName() + ".pn");
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010947 NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
10948 NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
Chris Lattner9c080502006-11-01 07:43:41 +000010949 InsertNewInstBefore(NewRHS, PN);
10950 RHSVal = NewRHS;
10951 }
10952
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010953 // Add all operands to the new PHIs.
Chris Lattner05f18922008-12-01 02:34:36 +000010954 if (NewLHS || NewRHS) {
10955 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10956 Instruction *InInst = cast<Instruction>(PN.getIncomingValue(i));
10957 if (NewLHS) {
10958 Value *NewInLHS = InInst->getOperand(0);
10959 NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
10960 }
10961 if (NewRHS) {
10962 Value *NewInRHS = InInst->getOperand(1);
10963 NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
10964 }
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010965 }
10966 }
10967
Chris Lattner7da52b22006-11-01 04:51:18 +000010968 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010969 return BinaryOperator::Create(BinOp->getOpcode(), LHSVal, RHSVal);
Chris Lattner38b3dcc2008-12-01 03:42:51 +000010970 CmpInst *CIOp = cast<CmpInst>(FirstInst);
Dan Gohman1c8a23c2009-08-25 23:17:54 +000010971 return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(),
Owen Anderson333c4002009-07-09 23:48:35 +000010972 LHSVal, RHSVal);
Chris Lattner7da52b22006-11-01 04:51:18 +000010973}
10974
Chris Lattner05f18922008-12-01 02:34:36 +000010975Instruction *InstCombiner::FoldPHIArgGEPIntoPHI(PHINode &PN) {
10976 GetElementPtrInst *FirstInst =cast<GetElementPtrInst>(PN.getIncomingValue(0));
10977
10978 SmallVector<Value*, 16> FixedOperands(FirstInst->op_begin(),
10979 FirstInst->op_end());
Chris Lattner36d3e322009-02-21 00:46:50 +000010980 // This is true if all GEP bases are allocas and if all indices into them are
10981 // constants.
10982 bool AllBasePointersAreAllocas = true;
Dan Gohmanb6c33852009-09-16 02:01:52 +000010983
10984 // We don't want to replace this phi if the replacement would require
Dan Gohman9ad29202009-09-16 16:50:24 +000010985 // more than one phi, which leads to higher register pressure. This is
10986 // especially bad when the PHIs are in the header of a loop.
Dan Gohmanb6c33852009-09-16 02:01:52 +000010987 bool NeededPhi = false;
Chris Lattner05f18922008-12-01 02:34:36 +000010988
Dan Gohman9ad29202009-09-16 16:50:24 +000010989 // Scan to see if all operands are the same opcode, and all have one use.
Chris Lattner05f18922008-12-01 02:34:36 +000010990 for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
10991 GetElementPtrInst *GEP= dyn_cast<GetElementPtrInst>(PN.getIncomingValue(i));
10992 if (!GEP || !GEP->hasOneUse() || GEP->getType() != FirstInst->getType() ||
10993 GEP->getNumOperands() != FirstInst->getNumOperands())
10994 return 0;
10995
Chris Lattner36d3e322009-02-21 00:46:50 +000010996 // Keep track of whether or not all GEPs are of alloca pointers.
10997 if (AllBasePointersAreAllocas &&
10998 (!isa<AllocaInst>(GEP->getOperand(0)) ||
10999 !GEP->hasAllConstantIndices()))
11000 AllBasePointersAreAllocas = false;
11001
Chris Lattner05f18922008-12-01 02:34:36 +000011002 // Compare the operand lists.
11003 for (unsigned op = 0, e = FirstInst->getNumOperands(); op != e; ++op) {
11004 if (FirstInst->getOperand(op) == GEP->getOperand(op))
11005 continue;
11006
11007 // Don't merge two GEPs when two operands differ (introducing phi nodes)
11008 // if one of the PHIs has a constant for the index. The index may be
11009 // substantially cheaper to compute for the constants, so making it a
11010 // variable index could pessimize the path. This also handles the case
11011 // for struct indices, which must always be constant.
11012 if (isa<ConstantInt>(FirstInst->getOperand(op)) ||
11013 isa<ConstantInt>(GEP->getOperand(op)))
11014 return 0;
11015
11016 if (FirstInst->getOperand(op)->getType() !=GEP->getOperand(op)->getType())
11017 return 0;
Dan Gohmanb6c33852009-09-16 02:01:52 +000011018
11019 // If we already needed a PHI for an earlier operand, and another operand
11020 // also requires a PHI, we'd be introducing more PHIs than we're
11021 // eliminating, which increases register pressure on entry to the PHI's
11022 // block.
11023 if (NeededPhi)
11024 return 0;
11025
Chris Lattner05f18922008-12-01 02:34:36 +000011026 FixedOperands[op] = 0; // Needs a PHI.
Dan Gohmanb6c33852009-09-16 02:01:52 +000011027 NeededPhi = true;
Chris Lattner05f18922008-12-01 02:34:36 +000011028 }
11029 }
11030
Chris Lattner36d3e322009-02-21 00:46:50 +000011031 // If all of the base pointers of the PHI'd GEPs are from allocas, don't
Chris Lattner21550882009-02-23 05:56:17 +000011032 // bother doing this transformation. At best, this will just save a bit of
Chris Lattner36d3e322009-02-21 00:46:50 +000011033 // offset calculation, but all the predecessors will have to materialize the
11034 // stack address into a register anyway. We'd actually rather *clone* the
11035 // load up into the predecessors so that we have a load of a gep of an alloca,
11036 // which can usually all be folded into the load.
11037 if (AllBasePointersAreAllocas)
11038 return 0;
11039
Chris Lattner05f18922008-12-01 02:34:36 +000011040 // Otherwise, this is safe to transform. Insert PHI nodes for each operand
11041 // that is variable.
11042 SmallVector<PHINode*, 16> OperandPhis(FixedOperands.size());
11043
11044 bool HasAnyPHIs = false;
11045 for (unsigned i = 0, e = FixedOperands.size(); i != e; ++i) {
11046 if (FixedOperands[i]) continue; // operand doesn't need a phi.
11047 Value *FirstOp = FirstInst->getOperand(i);
11048 PHINode *NewPN = PHINode::Create(FirstOp->getType(),
11049 FirstOp->getName()+".pn");
11050 InsertNewInstBefore(NewPN, PN);
11051
11052 NewPN->reserveOperandSpace(e);
11053 NewPN->addIncoming(FirstOp, PN.getIncomingBlock(0));
11054 OperandPhis[i] = NewPN;
11055 FixedOperands[i] = NewPN;
11056 HasAnyPHIs = true;
11057 }
11058
11059
11060 // Add all operands to the new PHIs.
11061 if (HasAnyPHIs) {
11062 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
11063 GetElementPtrInst *InGEP =cast<GetElementPtrInst>(PN.getIncomingValue(i));
11064 BasicBlock *InBB = PN.getIncomingBlock(i);
11065
11066 for (unsigned op = 0, e = OperandPhis.size(); op != e; ++op)
11067 if (PHINode *OpPhi = OperandPhis[op])
11068 OpPhi->addIncoming(InGEP->getOperand(op), InBB);
11069 }
11070 }
11071
11072 Value *Base = FixedOperands[0];
Dan Gohmanf8dbee72009-09-07 23:54:19 +000011073 return cast<GEPOperator>(FirstInst)->isInBounds() ?
11074 GetElementPtrInst::CreateInBounds(Base, FixedOperands.begin()+1,
11075 FixedOperands.end()) :
Dan Gohmand6aa02d2009-07-28 01:40:03 +000011076 GetElementPtrInst::Create(Base, FixedOperands.begin()+1,
11077 FixedOperands.end());
Chris Lattner05f18922008-12-01 02:34:36 +000011078}
11079
11080
Chris Lattner21550882009-02-23 05:56:17 +000011081/// isSafeAndProfitableToSinkLoad - Return true if we know that it is safe to
11082/// sink the load out of the block that defines it. This means that it must be
Chris Lattner36d3e322009-02-21 00:46:50 +000011083/// obvious the value of the load is not changed from the point of the load to
11084/// the end of the block it is in.
Chris Lattnerfd905ca2007-02-01 22:30:07 +000011085///
11086/// Finally, it is safe, but not profitable, to sink a load targetting a
11087/// non-address-taken alloca. Doing so will cause us to not promote the alloca
11088/// to a register.
Chris Lattner36d3e322009-02-21 00:46:50 +000011089static bool isSafeAndProfitableToSinkLoad(LoadInst *L) {
Chris Lattner76c73142006-11-01 07:13:54 +000011090 BasicBlock::iterator BBI = L, E = L->getParent()->end();
11091
11092 for (++BBI; BBI != E; ++BBI)
11093 if (BBI->mayWriteToMemory())
11094 return false;
Chris Lattnerfd905ca2007-02-01 22:30:07 +000011095
11096 // Check for non-address taken alloca. If not address-taken already, it isn't
11097 // profitable to do this xform.
11098 if (AllocaInst *AI = dyn_cast<AllocaInst>(L->getOperand(0))) {
11099 bool isAddressTaken = false;
11100 for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
11101 UI != E; ++UI) {
11102 if (isa<LoadInst>(UI)) continue;
11103 if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
11104 // If storing TO the alloca, then the address isn't taken.
11105 if (SI->getOperand(1) == AI) continue;
11106 }
11107 isAddressTaken = true;
11108 break;
11109 }
11110
Chris Lattner36d3e322009-02-21 00:46:50 +000011111 if (!isAddressTaken && AI->isStaticAlloca())
Chris Lattnerfd905ca2007-02-01 22:30:07 +000011112 return false;
11113 }
11114
Chris Lattner36d3e322009-02-21 00:46:50 +000011115 // If this load is a load from a GEP with a constant offset from an alloca,
11116 // then we don't want to sink it. In its present form, it will be
11117 // load [constant stack offset]. Sinking it will cause us to have to
11118 // materialize the stack addresses in each predecessor in a register only to
11119 // do a shared load from register in the successor.
11120 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(L->getOperand(0)))
11121 if (AllocaInst *AI = dyn_cast<AllocaInst>(GEP->getOperand(0)))
11122 if (AI->isStaticAlloca() && GEP->hasAllConstantIndices())
11123 return false;
11124
Chris Lattner76c73142006-11-01 07:13:54 +000011125 return true;
11126}
11127
Chris Lattner751a3622009-11-01 20:04:24 +000011128Instruction *InstCombiner::FoldPHIArgLoadIntoPHI(PHINode &PN) {
11129 LoadInst *FirstLI = cast<LoadInst>(PN.getIncomingValue(0));
11130
11131 // When processing loads, we need to propagate two bits of information to the
11132 // sunk load: whether it is volatile, and what its alignment is. We currently
11133 // don't sink loads when some have their alignment specified and some don't.
11134 // visitLoadInst will propagate an alignment onto the load when TD is around,
11135 // and if TD isn't around, we can't handle the mixed case.
11136 bool isVolatile = FirstLI->isVolatile();
11137 unsigned LoadAlignment = FirstLI->getAlignment();
11138
11139 // We can't sink the load if the loaded value could be modified between the
11140 // load and the PHI.
11141 if (FirstLI->getParent() != PN.getIncomingBlock(0) ||
11142 !isSafeAndProfitableToSinkLoad(FirstLI))
11143 return 0;
11144
11145 // If the PHI is of volatile loads and the load block has multiple
11146 // successors, sinking it would remove a load of the volatile value from
11147 // the path through the other successor.
11148 if (isVolatile &&
11149 FirstLI->getParent()->getTerminator()->getNumSuccessors() != 1)
11150 return 0;
11151
11152 // Check to see if all arguments are the same operation.
11153 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
11154 LoadInst *LI = dyn_cast<LoadInst>(PN.getIncomingValue(i));
11155 if (!LI || !LI->hasOneUse())
11156 return 0;
11157
11158 // We can't sink the load if the loaded value could be modified between
11159 // the load and the PHI.
11160 if (LI->isVolatile() != isVolatile ||
11161 LI->getParent() != PN.getIncomingBlock(i) ||
11162 !isSafeAndProfitableToSinkLoad(LI))
11163 return 0;
11164
11165 // If some of the loads have an alignment specified but not all of them,
11166 // we can't do the transformation.
11167 if ((LoadAlignment != 0) != (LI->getAlignment() != 0))
11168 return 0;
11169
Chris Lattnera664bb72009-11-01 20:07:07 +000011170 LoadAlignment = std::min(LoadAlignment, LI->getAlignment());
Chris Lattner751a3622009-11-01 20:04:24 +000011171
11172 // If the PHI is of volatile loads and the load block has multiple
11173 // successors, sinking it would remove a load of the volatile value from
11174 // the path through the other successor.
11175 if (isVolatile &&
11176 LI->getParent()->getTerminator()->getNumSuccessors() != 1)
11177 return 0;
11178 }
11179
11180 // Okay, they are all the same operation. Create a new PHI node of the
11181 // correct type, and PHI together all of the LHS's of the instructions.
11182 PHINode *NewPN = PHINode::Create(FirstLI->getOperand(0)->getType(),
11183 PN.getName()+".in");
11184 NewPN->reserveOperandSpace(PN.getNumOperands()/2);
11185
11186 Value *InVal = FirstLI->getOperand(0);
11187 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
11188
11189 // Add all operands to the new PHI.
11190 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
11191 Value *NewInVal = cast<LoadInst>(PN.getIncomingValue(i))->getOperand(0);
11192 if (NewInVal != InVal)
11193 InVal = 0;
11194 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
11195 }
11196
11197 Value *PhiVal;
11198 if (InVal) {
11199 // The new PHI unions all of the same values together. This is really
11200 // common, so we handle it intelligently here for compile-time speed.
11201 PhiVal = InVal;
11202 delete NewPN;
11203 } else {
11204 InsertNewInstBefore(NewPN, PN);
11205 PhiVal = NewPN;
11206 }
11207
11208 // If this was a volatile load that we are merging, make sure to loop through
11209 // and mark all the input loads as non-volatile. If we don't do this, we will
11210 // insert a new volatile load and the old ones will not be deletable.
11211 if (isVolatile)
11212 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
11213 cast<LoadInst>(PN.getIncomingValue(i))->setVolatile(false);
11214
11215 return new LoadInst(PhiVal, "", isVolatile, LoadAlignment);
11216}
11217
Chris Lattner9fe38862003-06-19 17:00:31 +000011218
Chris Lattnerc22d4d12009-11-10 07:23:37 +000011219
11220/// FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
11221/// operator and they all are only used by the PHI, PHI together their
11222/// inputs, and do the operation once, to the result of the PHI.
Chris Lattnerbac32862004-11-14 19:13:23 +000011223Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
11224 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
11225
Chris Lattner751a3622009-11-01 20:04:24 +000011226 if (isa<GetElementPtrInst>(FirstInst))
11227 return FoldPHIArgGEPIntoPHI(PN);
11228 if (isa<LoadInst>(FirstInst))
11229 return FoldPHIArgLoadIntoPHI(PN);
11230
Chris Lattnerbac32862004-11-14 19:13:23 +000011231 // Scan the instruction, looking for input operations that can be folded away.
11232 // If all input operands to the phi are the same instruction (e.g. a cast from
11233 // the same type or "+42") we can pull the operation through the PHI, reducing
11234 // code size and simplifying code.
11235 Constant *ConstantOp = 0;
11236 const Type *CastSrcTy = 0;
Chris Lattnere3c62812009-11-01 19:50:13 +000011237
Chris Lattnerbac32862004-11-14 19:13:23 +000011238 if (isa<CastInst>(FirstInst)) {
11239 CastSrcTy = FirstInst->getOperand(0)->getType();
Chris Lattnerbf382b52009-11-08 21:20:06 +000011240
11241 // Be careful about transforming integer PHIs. We don't want to pessimize
11242 // the code by turning an i32 into an i1293.
11243 if (isa<IntegerType>(PN.getType()) && isa<IntegerType>(CastSrcTy)) {
Chris Lattnerc22d4d12009-11-10 07:23:37 +000011244 if (!ShouldChangeType(PN.getType(), CastSrcTy, TD))
Chris Lattnerbf382b52009-11-08 21:20:06 +000011245 return 0;
11246 }
Reid Spencer832254e2007-02-02 02:16:23 +000011247 } else if (isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +000011248 // Can fold binop, compare or shift here if the RHS is a constant,
11249 // otherwise call FoldPHIArgBinOpIntoPHI.
Chris Lattnerbac32862004-11-14 19:13:23 +000011250 ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
Chris Lattner7da52b22006-11-01 04:51:18 +000011251 if (ConstantOp == 0)
11252 return FoldPHIArgBinOpIntoPHI(PN);
Chris Lattnerbac32862004-11-14 19:13:23 +000011253 } else {
11254 return 0; // Cannot fold this operation.
11255 }
11256
11257 // Check to see if all arguments are the same operation.
11258 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
Chris Lattner751a3622009-11-01 20:04:24 +000011259 Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
11260 if (I == 0 || !I->hasOneUse() || !I->isSameOperationAs(FirstInst))
Chris Lattnerbac32862004-11-14 19:13:23 +000011261 return 0;
11262 if (CastSrcTy) {
11263 if (I->getOperand(0)->getType() != CastSrcTy)
11264 return 0; // Cast operation must match.
11265 } else if (I->getOperand(1) != ConstantOp) {
11266 return 0;
11267 }
11268 }
11269
11270 // Okay, they are all the same operation. Create a new PHI node of the
11271 // correct type, and PHI together all of the LHS's of the instructions.
Gabor Greif051a9502008-04-06 20:25:17 +000011272 PHINode *NewPN = PHINode::Create(FirstInst->getOperand(0)->getType(),
11273 PN.getName()+".in");
Chris Lattner55517062005-01-29 00:39:08 +000011274 NewPN->reserveOperandSpace(PN.getNumOperands()/2);
Chris Lattnerb5893442004-11-14 19:29:34 +000011275
11276 Value *InVal = FirstInst->getOperand(0);
11277 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
Chris Lattnerbac32862004-11-14 19:13:23 +000011278
11279 // Add all operands to the new PHI.
Chris Lattnerb5893442004-11-14 19:29:34 +000011280 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
11281 Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
11282 if (NewInVal != InVal)
11283 InVal = 0;
11284 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
11285 }
11286
11287 Value *PhiVal;
11288 if (InVal) {
11289 // The new PHI unions all of the same values together. This is really
11290 // common, so we handle it intelligently here for compile-time speed.
11291 PhiVal = InVal;
11292 delete NewPN;
11293 } else {
11294 InsertNewInstBefore(NewPN, PN);
11295 PhiVal = NewPN;
11296 }
Misha Brukmanfd939082005-04-21 23:48:37 +000011297
Chris Lattnerbac32862004-11-14 19:13:23 +000011298 // Insert and return the new operation.
Chris Lattnere3c62812009-11-01 19:50:13 +000011299 if (CastInst *FirstCI = dyn_cast<CastInst>(FirstInst))
Gabor Greif7cbd8a32008-05-16 19:29:10 +000011300 return CastInst::Create(FirstCI->getOpcode(), PhiVal, PN.getType());
Chris Lattnere3c62812009-11-01 19:50:13 +000011301
Chris Lattner54545ac2008-04-29 17:13:43 +000011302 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Gabor Greif7cbd8a32008-05-16 19:29:10 +000011303 return BinaryOperator::Create(BinOp->getOpcode(), PhiVal, ConstantOp);
Chris Lattnere3c62812009-11-01 19:50:13 +000011304
Chris Lattner751a3622009-11-01 20:04:24 +000011305 CmpInst *CIOp = cast<CmpInst>(FirstInst);
11306 return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(),
11307 PhiVal, ConstantOp);
Chris Lattnerbac32862004-11-14 19:13:23 +000011308}
Chris Lattnera1be5662002-05-02 17:06:02 +000011309
Chris Lattnera3fd1c52005-01-17 05:10:15 +000011310/// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
11311/// that is dead.
Chris Lattner0e5444b2007-03-26 20:40:50 +000011312static bool DeadPHICycle(PHINode *PN,
11313 SmallPtrSet<PHINode*, 16> &PotentiallyDeadPHIs) {
Chris Lattnera3fd1c52005-01-17 05:10:15 +000011314 if (PN->use_empty()) return true;
11315 if (!PN->hasOneUse()) return false;
11316
11317 // Remember this node, and if we find the cycle, return.
Chris Lattner0e5444b2007-03-26 20:40:50 +000011318 if (!PotentiallyDeadPHIs.insert(PN))
Chris Lattnera3fd1c52005-01-17 05:10:15 +000011319 return true;
Chris Lattner92103de2007-08-28 04:23:55 +000011320
11321 // Don't scan crazily complex things.
11322 if (PotentiallyDeadPHIs.size() == 16)
11323 return false;
Chris Lattnera3fd1c52005-01-17 05:10:15 +000011324
11325 if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
11326 return DeadPHICycle(PU, PotentiallyDeadPHIs);
Misha Brukmanfd939082005-04-21 23:48:37 +000011327
Chris Lattnera3fd1c52005-01-17 05:10:15 +000011328 return false;
11329}
11330
Chris Lattnercf5008a2007-11-06 21:52:06 +000011331/// PHIsEqualValue - Return true if this phi node is always equal to
11332/// NonPhiInVal. This happens with mutually cyclic phi nodes like:
11333/// z = some value; x = phi (y, z); y = phi (x, z)
11334static bool PHIsEqualValue(PHINode *PN, Value *NonPhiInVal,
11335 SmallPtrSet<PHINode*, 16> &ValueEqualPHIs) {
11336 // See if we already saw this PHI node.
11337 if (!ValueEqualPHIs.insert(PN))
11338 return true;
11339
11340 // Don't scan crazily complex things.
11341 if (ValueEqualPHIs.size() == 16)
11342 return false;
11343
11344 // Scan the operands to see if they are either phi nodes or are equal to
11345 // the value.
11346 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
11347 Value *Op = PN->getIncomingValue(i);
11348 if (PHINode *OpPN = dyn_cast<PHINode>(Op)) {
11349 if (!PHIsEqualValue(OpPN, NonPhiInVal, ValueEqualPHIs))
11350 return false;
11351 } else if (Op != NonPhiInVal)
11352 return false;
11353 }
11354
11355 return true;
11356}
11357
11358
Chris Lattner9956c052009-11-08 19:23:30 +000011359namespace {
11360struct PHIUsageRecord {
Chris Lattnerdd21a1c2009-11-09 01:38:00 +000011361 unsigned PHIId; // The ID # of the PHI (something determinstic to sort on)
Chris Lattner9956c052009-11-08 19:23:30 +000011362 unsigned Shift; // The amount shifted.
11363 Instruction *Inst; // The trunc instruction.
11364
Chris Lattnerdd21a1c2009-11-09 01:38:00 +000011365 PHIUsageRecord(unsigned pn, unsigned Sh, Instruction *User)
11366 : PHIId(pn), Shift(Sh), Inst(User) {}
Chris Lattner9956c052009-11-08 19:23:30 +000011367
11368 bool operator<(const PHIUsageRecord &RHS) const {
Chris Lattnerdd21a1c2009-11-09 01:38:00 +000011369 if (PHIId < RHS.PHIId) return true;
11370 if (PHIId > RHS.PHIId) return false;
Chris Lattner9956c052009-11-08 19:23:30 +000011371 if (Shift < RHS.Shift) return true;
Chris Lattnerdd21a1c2009-11-09 01:38:00 +000011372 if (Shift > RHS.Shift) return false;
11373 return Inst->getType()->getPrimitiveSizeInBits() <
Chris Lattner9956c052009-11-08 19:23:30 +000011374 RHS.Inst->getType()->getPrimitiveSizeInBits();
11375 }
11376};
Chris Lattnerdd21a1c2009-11-09 01:38:00 +000011377
11378struct LoweredPHIRecord {
11379 PHINode *PN; // The PHI that was lowered.
11380 unsigned Shift; // The amount shifted.
11381 unsigned Width; // The width extracted.
11382
11383 LoweredPHIRecord(PHINode *pn, unsigned Sh, const Type *Ty)
11384 : PN(pn), Shift(Sh), Width(Ty->getPrimitiveSizeInBits()) {}
11385
11386 // Ctor form used by DenseMap.
11387 LoweredPHIRecord(PHINode *pn, unsigned Sh)
11388 : PN(pn), Shift(Sh), Width(0) {}
11389};
11390}
11391
11392namespace llvm {
11393 template<>
11394 struct DenseMapInfo<LoweredPHIRecord> {
11395 static inline LoweredPHIRecord getEmptyKey() {
11396 return LoweredPHIRecord(0, 0);
11397 }
11398 static inline LoweredPHIRecord getTombstoneKey() {
11399 return LoweredPHIRecord(0, 1);
11400 }
11401 static unsigned getHashValue(const LoweredPHIRecord &Val) {
11402 return DenseMapInfo<PHINode*>::getHashValue(Val.PN) ^ (Val.Shift>>3) ^
11403 (Val.Width>>3);
11404 }
11405 static bool isEqual(const LoweredPHIRecord &LHS,
11406 const LoweredPHIRecord &RHS) {
11407 return LHS.PN == RHS.PN && LHS.Shift == RHS.Shift &&
11408 LHS.Width == RHS.Width;
11409 }
Chris Lattnerdd21a1c2009-11-09 01:38:00 +000011410 };
Chris Lattner4bbf4ee2009-12-15 07:26:43 +000011411 template <>
11412 struct isPodLike<LoweredPHIRecord> { static const bool value = true; };
Chris Lattner9956c052009-11-08 19:23:30 +000011413}
11414
11415
11416/// SliceUpIllegalIntegerPHI - This is an integer PHI and we know that it has an
11417/// illegal type: see if it is only used by trunc or trunc(lshr) operations. If
11418/// so, we split the PHI into the various pieces being extracted. This sort of
11419/// thing is introduced when SROA promotes an aggregate to large integer values.
11420///
11421/// TODO: The user of the trunc may be an bitcast to float/double/vector or an
11422/// inttoptr. We should produce new PHIs in the right type.
11423///
Chris Lattnerdd21a1c2009-11-09 01:38:00 +000011424Instruction *InstCombiner::SliceUpIllegalIntegerPHI(PHINode &FirstPhi) {
11425 // PHIUsers - Keep track of all of the truncated values extracted from a set
11426 // of PHIs, along with their offset. These are the things we want to rewrite.
Chris Lattner9956c052009-11-08 19:23:30 +000011427 SmallVector<PHIUsageRecord, 16> PHIUsers;
11428
Chris Lattnerdd21a1c2009-11-09 01:38:00 +000011429 // PHIs are often mutually cyclic, so we keep track of a whole set of PHI
11430 // nodes which are extracted from. PHIsToSlice is a set we use to avoid
11431 // revisiting PHIs, PHIsInspected is a ordered list of PHIs that we need to
11432 // check the uses of (to ensure they are all extracts).
11433 SmallVector<PHINode*, 8> PHIsToSlice;
11434 SmallPtrSet<PHINode*, 8> PHIsInspected;
11435
11436 PHIsToSlice.push_back(&FirstPhi);
11437 PHIsInspected.insert(&FirstPhi);
11438
11439 for (unsigned PHIId = 0; PHIId != PHIsToSlice.size(); ++PHIId) {
11440 PHINode *PN = PHIsToSlice[PHIId];
Chris Lattner9956c052009-11-08 19:23:30 +000011441
Chris Lattner0ebc6ce2009-12-19 07:01:15 +000011442 // Scan the input list of the PHI. If any input is an invoke, and if the
11443 // input is defined in the predecessor, then we won't be split the critical
11444 // edge which is required to insert a truncate. Because of this, we have to
11445 // bail out.
11446 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
11447 InvokeInst *II = dyn_cast<InvokeInst>(PN->getIncomingValue(i));
11448 if (II == 0) continue;
11449 if (II->getParent() != PN->getIncomingBlock(i))
11450 continue;
11451
11452 // If we have a phi, and if it's directly in the predecessor, then we have
11453 // a critical edge where we need to put the truncate. Since we can't
11454 // split the edge in instcombine, we have to bail out.
11455 return 0;
11456 }
11457
11458
Chris Lattnerdd21a1c2009-11-09 01:38:00 +000011459 for (Value::use_iterator UI = PN->use_begin(), E = PN->use_end();
11460 UI != E; ++UI) {
11461 Instruction *User = cast<Instruction>(*UI);
11462
11463 // If the user is a PHI, inspect its uses recursively.
11464 if (PHINode *UserPN = dyn_cast<PHINode>(User)) {
11465 if (PHIsInspected.insert(UserPN))
11466 PHIsToSlice.push_back(UserPN);
11467 continue;
11468 }
11469
11470 // Truncates are always ok.
11471 if (isa<TruncInst>(User)) {
11472 PHIUsers.push_back(PHIUsageRecord(PHIId, 0, User));
11473 continue;
11474 }
11475
11476 // Otherwise it must be a lshr which can only be used by one trunc.
11477 if (User->getOpcode() != Instruction::LShr ||
11478 !User->hasOneUse() || !isa<TruncInst>(User->use_back()) ||
11479 !isa<ConstantInt>(User->getOperand(1)))
11480 return 0;
11481
11482 unsigned Shift = cast<ConstantInt>(User->getOperand(1))->getZExtValue();
11483 PHIUsers.push_back(PHIUsageRecord(PHIId, Shift, User->use_back()));
Chris Lattner9956c052009-11-08 19:23:30 +000011484 }
Chris Lattner9956c052009-11-08 19:23:30 +000011485 }
11486
11487 // If we have no users, they must be all self uses, just nuke the PHI.
11488 if (PHIUsers.empty())
Chris Lattnerdd21a1c2009-11-09 01:38:00 +000011489 return ReplaceInstUsesWith(FirstPhi, UndefValue::get(FirstPhi.getType()));
Chris Lattner9956c052009-11-08 19:23:30 +000011490
11491 // If this phi node is transformable, create new PHIs for all the pieces
11492 // extracted out of it. First, sort the users by their offset and size.
11493 array_pod_sort(PHIUsers.begin(), PHIUsers.end());
11494
Chris Lattnerdd21a1c2009-11-09 01:38:00 +000011495 DEBUG(errs() << "SLICING UP PHI: " << FirstPhi << '\n';
11496 for (unsigned i = 1, e = PHIsToSlice.size(); i != e; ++i)
11497 errs() << "AND USER PHI #" << i << ": " << *PHIsToSlice[i] <<'\n';
11498 );
Chris Lattner9956c052009-11-08 19:23:30 +000011499
Chris Lattnerdd21a1c2009-11-09 01:38:00 +000011500 // PredValues - This is a temporary used when rewriting PHI nodes. It is
11501 // hoisted out here to avoid construction/destruction thrashing.
Chris Lattner9956c052009-11-08 19:23:30 +000011502 DenseMap<BasicBlock*, Value*> PredValues;
11503
Chris Lattnerdd21a1c2009-11-09 01:38:00 +000011504 // ExtractedVals - Each new PHI we introduce is saved here so we don't
11505 // introduce redundant PHIs.
11506 DenseMap<LoweredPHIRecord, PHINode*> ExtractedVals;
11507
11508 for (unsigned UserI = 0, UserE = PHIUsers.size(); UserI != UserE; ++UserI) {
11509 unsigned PHIId = PHIUsers[UserI].PHIId;
11510 PHINode *PN = PHIsToSlice[PHIId];
Chris Lattner9956c052009-11-08 19:23:30 +000011511 unsigned Offset = PHIUsers[UserI].Shift;
11512 const Type *Ty = PHIUsers[UserI].Inst->getType();
Chris Lattner9956c052009-11-08 19:23:30 +000011513
Chris Lattnerdd21a1c2009-11-09 01:38:00 +000011514 PHINode *EltPHI;
11515
11516 // If we've already lowered a user like this, reuse the previously lowered
11517 // value.
11518 if ((EltPHI = ExtractedVals[LoweredPHIRecord(PN, Offset, Ty)]) == 0) {
Chris Lattner9956c052009-11-08 19:23:30 +000011519
Chris Lattnerdd21a1c2009-11-09 01:38:00 +000011520 // Otherwise, Create the new PHI node for this user.
11521 EltPHI = PHINode::Create(Ty, PN->getName()+".off"+Twine(Offset), PN);
11522 assert(EltPHI->getType() != PN->getType() &&
11523 "Truncate didn't shrink phi?");
11524
11525 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
11526 BasicBlock *Pred = PN->getIncomingBlock(i);
11527 Value *&PredVal = PredValues[Pred];
11528
11529 // If we already have a value for this predecessor, reuse it.
11530 if (PredVal) {
11531 EltPHI->addIncoming(PredVal, Pred);
11532 continue;
11533 }
Chris Lattner9956c052009-11-08 19:23:30 +000011534
Chris Lattnerdd21a1c2009-11-09 01:38:00 +000011535 // Handle the PHI self-reuse case.
11536 Value *InVal = PN->getIncomingValue(i);
11537 if (InVal == PN) {
11538 PredVal = EltPHI;
11539 EltPHI->addIncoming(PredVal, Pred);
11540 continue;
Chris Lattner0ebc6ce2009-12-19 07:01:15 +000011541 }
11542
11543 if (PHINode *InPHI = dyn_cast<PHINode>(PN)) {
Chris Lattnerdd21a1c2009-11-09 01:38:00 +000011544 // If the incoming value was a PHI, and if it was one of the PHIs we
11545 // already rewrote it, just use the lowered value.
11546 if (Value *Res = ExtractedVals[LoweredPHIRecord(InPHI, Offset, Ty)]) {
11547 PredVal = Res;
11548 EltPHI->addIncoming(PredVal, Pred);
11549 continue;
11550 }
11551 }
11552
11553 // Otherwise, do an extract in the predecessor.
11554 Builder->SetInsertPoint(Pred, Pred->getTerminator());
11555 Value *Res = InVal;
11556 if (Offset)
11557 Res = Builder->CreateLShr(Res, ConstantInt::get(InVal->getType(),
11558 Offset), "extract");
11559 Res = Builder->CreateTrunc(Res, Ty, "extract.t");
11560 PredVal = Res;
11561 EltPHI->addIncoming(Res, Pred);
11562
11563 // If the incoming value was a PHI, and if it was one of the PHIs we are
11564 // rewriting, we will ultimately delete the code we inserted. This
11565 // means we need to revisit that PHI to make sure we extract out the
11566 // needed piece.
11567 if (PHINode *OldInVal = dyn_cast<PHINode>(PN->getIncomingValue(i)))
11568 if (PHIsInspected.count(OldInVal)) {
11569 unsigned RefPHIId = std::find(PHIsToSlice.begin(),PHIsToSlice.end(),
11570 OldInVal)-PHIsToSlice.begin();
11571 PHIUsers.push_back(PHIUsageRecord(RefPHIId, Offset,
11572 cast<Instruction>(Res)));
11573 ++UserE;
11574 }
Chris Lattner9956c052009-11-08 19:23:30 +000011575 }
Chris Lattnerdd21a1c2009-11-09 01:38:00 +000011576 PredValues.clear();
Chris Lattner9956c052009-11-08 19:23:30 +000011577
Chris Lattnerdd21a1c2009-11-09 01:38:00 +000011578 DEBUG(errs() << " Made element PHI for offset " << Offset << ": "
11579 << *EltPHI << '\n');
11580 ExtractedVals[LoweredPHIRecord(PN, Offset, Ty)] = EltPHI;
Chris Lattner9956c052009-11-08 19:23:30 +000011581 }
Chris Lattner9956c052009-11-08 19:23:30 +000011582
Chris Lattnerdd21a1c2009-11-09 01:38:00 +000011583 // Replace the use of this piece with the PHI node.
11584 ReplaceInstUsesWith(*PHIUsers[UserI].Inst, EltPHI);
Chris Lattner9956c052009-11-08 19:23:30 +000011585 }
Chris Lattnerdd21a1c2009-11-09 01:38:00 +000011586
11587 // Replace all the remaining uses of the PHI nodes (self uses and the lshrs)
11588 // with undefs.
11589 Value *Undef = UndefValue::get(FirstPhi.getType());
11590 for (unsigned i = 1, e = PHIsToSlice.size(); i != e; ++i)
11591 ReplaceInstUsesWith(*PHIsToSlice[i], Undef);
11592 return ReplaceInstUsesWith(FirstPhi, Undef);
Chris Lattner9956c052009-11-08 19:23:30 +000011593}
11594
Chris Lattner473945d2002-05-06 18:06:38 +000011595// PHINode simplification
11596//
Chris Lattner7e708292002-06-25 16:13:24 +000011597Instruction *InstCombiner::visitPHINode(PHINode &PN) {
Owen Andersonb64ab872006-07-10 22:15:25 +000011598 // If LCSSA is around, don't mess with Phi nodes
Chris Lattnerf964f322007-03-04 04:27:24 +000011599 if (MustPreserveLCSSA) return 0;
Owen Andersond1b78a12006-07-10 19:03:49 +000011600
Owen Anderson7e057142006-07-10 22:03:18 +000011601 if (Value *V = PN.hasConstantValue())
11602 return ReplaceInstUsesWith(PN, V);
11603
Owen Anderson7e057142006-07-10 22:03:18 +000011604 // If all PHI operands are the same operation, pull them through the PHI,
11605 // reducing code size.
11606 if (isa<Instruction>(PN.getIncomingValue(0)) &&
Chris Lattner05f18922008-12-01 02:34:36 +000011607 isa<Instruction>(PN.getIncomingValue(1)) &&
11608 cast<Instruction>(PN.getIncomingValue(0))->getOpcode() ==
11609 cast<Instruction>(PN.getIncomingValue(1))->getOpcode() &&
11610 // FIXME: The hasOneUse check will fail for PHIs that use the value more
11611 // than themselves more than once.
Owen Anderson7e057142006-07-10 22:03:18 +000011612 PN.getIncomingValue(0)->hasOneUse())
11613 if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
11614 return Result;
11615
11616 // If this is a trivial cycle in the PHI node graph, remove it. Basically, if
11617 // this PHI only has a single use (a PHI), and if that PHI only has one use (a
11618 // PHI)... break the cycle.
Chris Lattnerff9f13a2007-01-15 07:30:06 +000011619 if (PN.hasOneUse()) {
11620 Instruction *PHIUser = cast<Instruction>(PN.use_back());
11621 if (PHINode *PU = dyn_cast<PHINode>(PHIUser)) {
Chris Lattner0e5444b2007-03-26 20:40:50 +000011622 SmallPtrSet<PHINode*, 16> PotentiallyDeadPHIs;
Owen Anderson7e057142006-07-10 22:03:18 +000011623 PotentiallyDeadPHIs.insert(&PN);
11624 if (DeadPHICycle(PU, PotentiallyDeadPHIs))
Owen Anderson9e9a0d52009-07-30 23:03:37 +000011625 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
Owen Anderson7e057142006-07-10 22:03:18 +000011626 }
Chris Lattnerff9f13a2007-01-15 07:30:06 +000011627
11628 // If this phi has a single use, and if that use just computes a value for
11629 // the next iteration of a loop, delete the phi. This occurs with unused
11630 // induction variables, e.g. "for (int j = 0; ; ++j);". Detecting this
11631 // common case here is good because the only other things that catch this
11632 // are induction variable analysis (sometimes) and ADCE, which is only run
11633 // late.
11634 if (PHIUser->hasOneUse() &&
11635 (isa<BinaryOperator>(PHIUser) || isa<GetElementPtrInst>(PHIUser)) &&
11636 PHIUser->use_back() == &PN) {
Owen Anderson9e9a0d52009-07-30 23:03:37 +000011637 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
Chris Lattnerff9f13a2007-01-15 07:30:06 +000011638 }
11639 }
Owen Anderson7e057142006-07-10 22:03:18 +000011640
Chris Lattnercf5008a2007-11-06 21:52:06 +000011641 // We sometimes end up with phi cycles that non-obviously end up being the
11642 // same value, for example:
11643 // z = some value; x = phi (y, z); y = phi (x, z)
11644 // where the phi nodes don't necessarily need to be in the same block. Do a
11645 // quick check to see if the PHI node only contains a single non-phi value, if
11646 // so, scan to see if the phi cycle is actually equal to that value.
11647 {
11648 unsigned InValNo = 0, NumOperandVals = PN.getNumIncomingValues();
11649 // Scan for the first non-phi operand.
11650 while (InValNo != NumOperandVals &&
11651 isa<PHINode>(PN.getIncomingValue(InValNo)))
11652 ++InValNo;
11653
11654 if (InValNo != NumOperandVals) {
11655 Value *NonPhiInVal = PN.getOperand(InValNo);
11656
11657 // Scan the rest of the operands to see if there are any conflicts, if so
11658 // there is no need to recursively scan other phis.
11659 for (++InValNo; InValNo != NumOperandVals; ++InValNo) {
11660 Value *OpVal = PN.getIncomingValue(InValNo);
11661 if (OpVal != NonPhiInVal && !isa<PHINode>(OpVal))
11662 break;
11663 }
11664
11665 // If we scanned over all operands, then we have one unique value plus
11666 // phi values. Scan PHI nodes to see if they all merge in each other or
11667 // the value.
11668 if (InValNo == NumOperandVals) {
11669 SmallPtrSet<PHINode*, 16> ValueEqualPHIs;
11670 if (PHIsEqualValue(&PN, NonPhiInVal, ValueEqualPHIs))
11671 return ReplaceInstUsesWith(PN, NonPhiInVal);
11672 }
11673 }
11674 }
Dan Gohman8e42e4b2009-10-30 22:22:22 +000011675
Dan Gohman5b097012009-10-31 14:22:52 +000011676 // If there are multiple PHIs, sort their operands so that they all list
11677 // the blocks in the same order. This will help identical PHIs be eliminated
11678 // by other passes. Other passes shouldn't depend on this for correctness
11679 // however.
11680 PHINode *FirstPN = cast<PHINode>(PN.getParent()->begin());
11681 if (&PN != FirstPN)
11682 for (unsigned i = 0, e = FirstPN->getNumIncomingValues(); i != e; ++i) {
Dan Gohman8e42e4b2009-10-30 22:22:22 +000011683 BasicBlock *BBA = PN.getIncomingBlock(i);
Dan Gohman5b097012009-10-31 14:22:52 +000011684 BasicBlock *BBB = FirstPN->getIncomingBlock(i);
11685 if (BBA != BBB) {
11686 Value *VA = PN.getIncomingValue(i);
11687 unsigned j = PN.getBasicBlockIndex(BBB);
11688 Value *VB = PN.getIncomingValue(j);
11689 PN.setIncomingBlock(i, BBB);
11690 PN.setIncomingValue(i, VB);
11691 PN.setIncomingBlock(j, BBA);
11692 PN.setIncomingValue(j, VA);
Chris Lattner28f3d342009-10-31 17:48:31 +000011693 // NOTE: Instcombine normally would want us to "return &PN" if we
11694 // modified any of the operands of an instruction. However, since we
11695 // aren't adding or removing uses (just rearranging them) we don't do
11696 // this in this case.
Dan Gohman5b097012009-10-31 14:22:52 +000011697 }
Dan Gohman8e42e4b2009-10-30 22:22:22 +000011698 }
11699
Chris Lattner9956c052009-11-08 19:23:30 +000011700 // If this is an integer PHI and we know that it has an illegal type, see if
11701 // it is only used by trunc or trunc(lshr) operations. If so, we split the
11702 // PHI into the various pieces being extracted. This sort of thing is
11703 // introduced when SROA promotes an aggregate to a single large integer type.
Chris Lattnerbf382b52009-11-08 21:20:06 +000011704 if (isa<IntegerType>(PN.getType()) && TD &&
Chris Lattner9956c052009-11-08 19:23:30 +000011705 !TD->isLegalInteger(PN.getType()->getPrimitiveSizeInBits()))
11706 if (Instruction *Res = SliceUpIllegalIntegerPHI(PN))
11707 return Res;
11708
Chris Lattner60921c92003-12-19 05:58:40 +000011709 return 0;
Chris Lattner473945d2002-05-06 18:06:38 +000011710}
11711
Chris Lattner7e708292002-06-25 16:13:24 +000011712Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
Chris Lattnerc514c1f2009-11-27 00:29:05 +000011713 SmallVector<Value*, 8> Ops(GEP.op_begin(), GEP.op_end());
11714
11715 if (Value *V = SimplifyGEPInst(&Ops[0], Ops.size(), TD))
11716 return ReplaceInstUsesWith(GEP, V);
11717
Chris Lattner620ce142004-05-07 22:09:22 +000011718 Value *PtrOp = GEP.getOperand(0);
Chris Lattnerc6bd1952004-02-22 05:25:17 +000011719
Chris Lattnere87597f2004-10-16 18:11:37 +000011720 if (isa<UndefValue>(GEP.getOperand(0)))
Owen Anderson9e9a0d52009-07-30 23:03:37 +000011721 return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +000011722
Chris Lattner28977af2004-04-05 01:30:19 +000011723 // Eliminate unneeded casts for indices.
Chris Lattnerccf4b342009-08-30 04:49:01 +000011724 if (TD) {
11725 bool MadeChange = false;
11726 unsigned PtrSize = TD->getPointerSizeInBits();
11727
11728 gep_type_iterator GTI = gep_type_begin(GEP);
11729 for (User::op_iterator I = GEP.op_begin() + 1, E = GEP.op_end();
11730 I != E; ++I, ++GTI) {
11731 if (!isa<SequentialType>(*GTI)) continue;
11732
Chris Lattnercb69a4e2004-04-07 18:38:20 +000011733 // If we are using a wider index than needed for this platform, shrink it
Chris Lattnerccf4b342009-08-30 04:49:01 +000011734 // to what we need. If narrower, sign-extend it to what we need. This
11735 // explicit cast can make subsequent optimizations more obvious.
11736 unsigned OpBits = cast<IntegerType>((*I)->getType())->getBitWidth();
Chris Lattnerccf4b342009-08-30 04:49:01 +000011737 if (OpBits == PtrSize)
11738 continue;
11739
Chris Lattner2345d1d2009-08-30 20:01:10 +000011740 *I = Builder->CreateIntCast(*I, TD->getIntPtrType(GEP.getContext()),true);
Chris Lattnerccf4b342009-08-30 04:49:01 +000011741 MadeChange = true;
Chris Lattner28977af2004-04-05 01:30:19 +000011742 }
Chris Lattnerccf4b342009-08-30 04:49:01 +000011743 if (MadeChange) return &GEP;
Chris Lattnerdb9654e2007-03-25 20:43:09 +000011744 }
Chris Lattner28977af2004-04-05 01:30:19 +000011745
Chris Lattner90ac28c2002-08-02 19:29:35 +000011746 // Combine Indices - If the source pointer to this getelementptr instruction
11747 // is a getelementptr instruction, combine the indices of the two
11748 // getelementptr instructions into a single instruction.
11749 //
Dan Gohmand6aa02d2009-07-28 01:40:03 +000011750 if (GEPOperator *Src = dyn_cast<GEPOperator>(PtrOp)) {
Chris Lattner620ce142004-05-07 22:09:22 +000011751 // Note that if our source is a gep chain itself that we wait for that
11752 // chain to be resolved before we perform this transformation. This
11753 // avoids us creating a TON of code in some cases.
11754 //
Chris Lattnerf9b91bb2009-08-30 05:08:50 +000011755 if (GetElementPtrInst *SrcGEP =
11756 dyn_cast<GetElementPtrInst>(Src->getOperand(0)))
11757 if (SrcGEP->getNumOperands() == 2)
11758 return 0; // Wait until our source is folded to completion.
Chris Lattner620ce142004-05-07 22:09:22 +000011759
Chris Lattner72588fc2007-02-15 22:48:32 +000011760 SmallVector<Value*, 8> Indices;
Chris Lattner620ce142004-05-07 22:09:22 +000011761
11762 // Find out whether the last index in the source GEP is a sequential idx.
11763 bool EndsWithSequential = false;
Chris Lattnerab984842009-08-30 05:30:55 +000011764 for (gep_type_iterator I = gep_type_begin(*Src), E = gep_type_end(*Src);
11765 I != E; ++I)
Chris Lattnerbe97b4e2004-05-08 22:41:42 +000011766 EndsWithSequential = !isa<StructType>(*I);
Misha Brukmanfd939082005-04-21 23:48:37 +000011767
Chris Lattner90ac28c2002-08-02 19:29:35 +000011768 // Can we combine the two pointer arithmetics offsets?
Chris Lattner620ce142004-05-07 22:09:22 +000011769 if (EndsWithSequential) {
Chris Lattnerdecd0812003-03-05 22:33:14 +000011770 // Replace: gep (gep %P, long B), long A, ...
11771 // With: T = long A+B; gep %P, T, ...
11772 //
Chris Lattnerf9b91bb2009-08-30 05:08:50 +000011773 Value *Sum;
11774 Value *SO1 = Src->getOperand(Src->getNumOperands()-1);
11775 Value *GO1 = GEP.getOperand(1);
Owen Andersona7235ea2009-07-31 20:28:14 +000011776 if (SO1 == Constant::getNullValue(SO1->getType())) {
Chris Lattner28977af2004-04-05 01:30:19 +000011777 Sum = GO1;
Owen Andersona7235ea2009-07-31 20:28:14 +000011778 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
Chris Lattner28977af2004-04-05 01:30:19 +000011779 Sum = SO1;
11780 } else {
Chris Lattnerab984842009-08-30 05:30:55 +000011781 // If they aren't the same type, then the input hasn't been processed
11782 // by the loop above yet (which canonicalizes sequential index types to
11783 // intptr_t). Just avoid transforming this until the input has been
11784 // normalized.
11785 if (SO1->getType() != GO1->getType())
11786 return 0;
Chris Lattnerf925cbd2009-08-30 18:50:58 +000011787 Sum = Builder->CreateAdd(SO1, GO1, PtrOp->getName()+".sum");
Chris Lattner28977af2004-04-05 01:30:19 +000011788 }
Chris Lattner620ce142004-05-07 22:09:22 +000011789
Chris Lattnerab984842009-08-30 05:30:55 +000011790 // Update the GEP in place if possible.
Chris Lattnerf9b91bb2009-08-30 05:08:50 +000011791 if (Src->getNumOperands() == 2) {
11792 GEP.setOperand(0, Src->getOperand(0));
Chris Lattner620ce142004-05-07 22:09:22 +000011793 GEP.setOperand(1, Sum);
11794 return &GEP;
Chris Lattner620ce142004-05-07 22:09:22 +000011795 }
Chris Lattnerab984842009-08-30 05:30:55 +000011796 Indices.append(Src->op_begin()+1, Src->op_end()-1);
Chris Lattnerccf4b342009-08-30 04:49:01 +000011797 Indices.push_back(Sum);
Chris Lattnerab984842009-08-30 05:30:55 +000011798 Indices.append(GEP.op_begin()+2, GEP.op_end());
Misha Brukmanfd939082005-04-21 23:48:37 +000011799 } else if (isa<Constant>(*GEP.idx_begin()) &&
Chris Lattner28977af2004-04-05 01:30:19 +000011800 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
Chris Lattnerf9b91bb2009-08-30 05:08:50 +000011801 Src->getNumOperands() != 1) {
Chris Lattner90ac28c2002-08-02 19:29:35 +000011802 // Otherwise we can do the fold if the first index of the GEP is a zero
Chris Lattnerab984842009-08-30 05:30:55 +000011803 Indices.append(Src->op_begin()+1, Src->op_end());
11804 Indices.append(GEP.idx_begin()+1, GEP.idx_end());
Chris Lattner90ac28c2002-08-02 19:29:35 +000011805 }
11806
Dan Gohmanf8dbee72009-09-07 23:54:19 +000011807 if (!Indices.empty())
11808 return (cast<GEPOperator>(&GEP)->isInBounds() &&
11809 Src->isInBounds()) ?
11810 GetElementPtrInst::CreateInBounds(Src->getOperand(0), Indices.begin(),
11811 Indices.end(), GEP.getName()) :
Chris Lattnerf9b91bb2009-08-30 05:08:50 +000011812 GetElementPtrInst::Create(Src->getOperand(0), Indices.begin(),
Chris Lattnerccf4b342009-08-30 04:49:01 +000011813 Indices.end(), GEP.getName());
Chris Lattner6e24d832009-08-30 05:00:50 +000011814 }
11815
Chris Lattnerf9b91bb2009-08-30 05:08:50 +000011816 // Handle gep(bitcast x) and gep(gep x, 0, 0, 0).
11817 if (Value *X = getBitCastOperand(PtrOp)) {
Chris Lattner6e24d832009-08-30 05:00:50 +000011818 assert(isa<PointerType>(X->getType()) && "Must be cast from pointer");
Chris Lattner963f4ba2009-08-30 20:36:46 +000011819
Chris Lattner2de23192009-08-30 20:38:21 +000011820 // If the input bitcast is actually "bitcast(bitcast(x))", then we don't
11821 // want to change the gep until the bitcasts are eliminated.
11822 if (getBitCastOperand(X)) {
11823 Worklist.AddValue(PtrOp);
11824 return 0;
11825 }
11826
Chris Lattnerc514c1f2009-11-27 00:29:05 +000011827 bool HasZeroPointerIndex = false;
11828 if (ConstantInt *C = dyn_cast<ConstantInt>(GEP.getOperand(1)))
11829 HasZeroPointerIndex = C->isZero();
11830
Chris Lattner963f4ba2009-08-30 20:36:46 +000011831 // Transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ...
11832 // into : GEP [10 x i8]* X, i32 0, ...
11833 //
11834 // Likewise, transform: GEP (bitcast i8* X to [0 x i8]*), i32 0, ...
11835 // into : GEP i8* X, ...
11836 //
11837 // This occurs when the program declares an array extern like "int X[];"
Chris Lattner6e24d832009-08-30 05:00:50 +000011838 if (HasZeroPointerIndex) {
Chris Lattnereed48272005-09-13 00:40:14 +000011839 const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
11840 const PointerType *XTy = cast<PointerType>(X->getType());
Duncan Sands5b7cfb02009-03-02 09:18:21 +000011841 if (const ArrayType *CATy =
11842 dyn_cast<ArrayType>(CPTy->getElementType())) {
11843 // GEP (bitcast i8* X to [0 x i8]*), i32 0, ... ?
11844 if (CATy->getElementType() == XTy->getElementType()) {
11845 // -> GEP i8* X, ...
11846 SmallVector<Value*, 8> Indices(GEP.idx_begin()+1, GEP.idx_end());
Dan Gohmanf8dbee72009-09-07 23:54:19 +000011847 return cast<GEPOperator>(&GEP)->isInBounds() ?
11848 GetElementPtrInst::CreateInBounds(X, Indices.begin(), Indices.end(),
11849 GEP.getName()) :
Dan Gohmand6aa02d2009-07-28 01:40:03 +000011850 GetElementPtrInst::Create(X, Indices.begin(), Indices.end(),
11851 GEP.getName());
Chris Lattner963f4ba2009-08-30 20:36:46 +000011852 }
11853
11854 if (const ArrayType *XATy = dyn_cast<ArrayType>(XTy->getElementType())){
Duncan Sands5b7cfb02009-03-02 09:18:21 +000011855 // GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ... ?
Chris Lattnereed48272005-09-13 00:40:14 +000011856 if (CATy->getElementType() == XATy->getElementType()) {
Duncan Sands5b7cfb02009-03-02 09:18:21 +000011857 // -> GEP [10 x i8]* X, i32 0, ...
Chris Lattnereed48272005-09-13 00:40:14 +000011858 // At this point, we know that the cast source type is a pointer
11859 // to an array of the same type as the destination pointer
11860 // array. Because the array type is never stepped over (there
11861 // is a leading zero) we can fold the cast into this GEP.
11862 GEP.setOperand(0, X);
11863 return &GEP;
11864 }
Duncan Sands5b7cfb02009-03-02 09:18:21 +000011865 }
11866 }
Chris Lattnereed48272005-09-13 00:40:14 +000011867 } else if (GEP.getNumOperands() == 2) {
11868 // Transform things like:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011869 // %t = getelementptr i32* bitcast ([2 x i32]* %str to i32*), i32 %V
11870 // into: %t1 = getelementptr [2 x i32]* %str, i32 0, i32 %V; bitcast
Chris Lattnereed48272005-09-13 00:40:14 +000011871 const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
11872 const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011873 if (TD && isa<ArrayType>(SrcElTy) &&
Duncan Sands777d2302009-05-09 07:06:46 +000011874 TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
11875 TD->getTypeAllocSize(ResElTy)) {
David Greeneb8f74792007-09-04 15:46:09 +000011876 Value *Idx[2];
Chris Lattner4de84762010-01-04 07:02:48 +000011877 Idx[0] = Constant::getNullValue(Type::getInt32Ty(GEP.getContext()));
David Greeneb8f74792007-09-04 15:46:09 +000011878 Idx[1] = GEP.getOperand(1);
Dan Gohmanf8dbee72009-09-07 23:54:19 +000011879 Value *NewGEP = cast<GEPOperator>(&GEP)->isInBounds() ?
11880 Builder->CreateInBoundsGEP(X, Idx, Idx + 2, GEP.getName()) :
Chris Lattnerf925cbd2009-08-30 18:50:58 +000011881 Builder->CreateGEP(X, Idx, Idx + 2, GEP.getName());
Reid Spencer3da59db2006-11-27 01:05:10 +000011882 // V and GEP are both pointer types --> BitCast
Chris Lattnerf925cbd2009-08-30 18:50:58 +000011883 return new BitCastInst(NewGEP, GEP.getType());
Chris Lattnerc6bd1952004-02-22 05:25:17 +000011884 }
Chris Lattner7835cdd2005-09-13 18:36:04 +000011885
11886 // Transform things like:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011887 // getelementptr i8* bitcast ([100 x double]* X to i8*), i32 %tmp
Chris Lattner7835cdd2005-09-13 18:36:04 +000011888 // (where tmp = 8*tmp2) into:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011889 // getelementptr [100 x double]* %arr, i32 0, i32 %tmp2; bitcast
Chris Lattner7835cdd2005-09-13 18:36:04 +000011890
Chris Lattner4de84762010-01-04 07:02:48 +000011891 if (TD && isa<ArrayType>(SrcElTy) &&
11892 ResElTy == Type::getInt8Ty(GEP.getContext())) {
Chris Lattner7835cdd2005-09-13 18:36:04 +000011893 uint64_t ArrayEltSize =
Duncan Sands777d2302009-05-09 07:06:46 +000011894 TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType());
Chris Lattner7835cdd2005-09-13 18:36:04 +000011895
11896 // Check to see if "tmp" is a scale by a multiple of ArrayEltSize. We
11897 // allow either a mul, shift, or constant here.
11898 Value *NewIdx = 0;
11899 ConstantInt *Scale = 0;
11900 if (ArrayEltSize == 1) {
11901 NewIdx = GEP.getOperand(1);
Chris Lattnerab984842009-08-30 05:30:55 +000011902 Scale = ConstantInt::get(cast<IntegerType>(NewIdx->getType()), 1);
Chris Lattner7835cdd2005-09-13 18:36:04 +000011903 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
Owen Andersoneed707b2009-07-24 23:12:02 +000011904 NewIdx = ConstantInt::get(CI->getType(), 1);
Chris Lattner7835cdd2005-09-13 18:36:04 +000011905 Scale = CI;
11906 } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
11907 if (Inst->getOpcode() == Instruction::Shl &&
11908 isa<ConstantInt>(Inst->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +000011909 ConstantInt *ShAmt = cast<ConstantInt>(Inst->getOperand(1));
11910 uint32_t ShAmtVal = ShAmt->getLimitedValue(64);
Owen Andersoneed707b2009-07-24 23:12:02 +000011911 Scale = ConstantInt::get(cast<IntegerType>(Inst->getType()),
Dan Gohman6de29f82009-06-15 22:12:54 +000011912 1ULL << ShAmtVal);
Chris Lattner7835cdd2005-09-13 18:36:04 +000011913 NewIdx = Inst->getOperand(0);
11914 } else if (Inst->getOpcode() == Instruction::Mul &&
11915 isa<ConstantInt>(Inst->getOperand(1))) {
11916 Scale = cast<ConstantInt>(Inst->getOperand(1));
11917 NewIdx = Inst->getOperand(0);
11918 }
11919 }
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011920
Chris Lattner7835cdd2005-09-13 18:36:04 +000011921 // If the index will be to exactly the right offset with the scale taken
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011922 // out, perform the transformation. Note, we don't know whether Scale is
11923 // signed or not. We'll use unsigned version of division/modulo
11924 // operation after making sure Scale doesn't have the sign bit set.
Chris Lattner58b1ac72009-02-25 18:20:01 +000011925 if (ArrayEltSize && Scale && Scale->getSExtValue() >= 0LL &&
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011926 Scale->getZExtValue() % ArrayEltSize == 0) {
Owen Andersoneed707b2009-07-24 23:12:02 +000011927 Scale = ConstantInt::get(Scale->getType(),
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011928 Scale->getZExtValue() / ArrayEltSize);
Reid Spencerb83eb642006-10-20 07:07:24 +000011929 if (Scale->getZExtValue() != 1) {
Chris Lattner878daed2009-08-30 05:56:44 +000011930 Constant *C = ConstantExpr::getIntegerCast(Scale, NewIdx->getType(),
11931 false /*ZExt*/);
Chris Lattnerf925cbd2009-08-30 18:50:58 +000011932 NewIdx = Builder->CreateMul(NewIdx, C, "idxscale");
Chris Lattner7835cdd2005-09-13 18:36:04 +000011933 }
11934
11935 // Insert the new GEP instruction.
David Greeneb8f74792007-09-04 15:46:09 +000011936 Value *Idx[2];
Chris Lattner4de84762010-01-04 07:02:48 +000011937 Idx[0] = Constant::getNullValue(Type::getInt32Ty(GEP.getContext()));
David Greeneb8f74792007-09-04 15:46:09 +000011938 Idx[1] = NewIdx;
Dan Gohmanf8dbee72009-09-07 23:54:19 +000011939 Value *NewGEP = cast<GEPOperator>(&GEP)->isInBounds() ?
11940 Builder->CreateInBoundsGEP(X, Idx, Idx + 2, GEP.getName()) :
11941 Builder->CreateGEP(X, Idx, Idx + 2, GEP.getName());
Reid Spencer3da59db2006-11-27 01:05:10 +000011942 // The NewGEP must be pointer typed, so must the old one -> BitCast
11943 return new BitCastInst(NewGEP, GEP.getType());
Chris Lattner7835cdd2005-09-13 18:36:04 +000011944 }
11945 }
Chris Lattnerc6bd1952004-02-22 05:25:17 +000011946 }
Chris Lattner8a2a3112001-12-14 16:52:21 +000011947 }
Chris Lattner58407792009-01-09 04:53:57 +000011948
Chris Lattner46cd5a12009-01-09 05:44:56 +000011949 /// See if we can simplify:
Chris Lattner873ff012009-08-30 05:55:36 +000011950 /// X = bitcast A* to B*
Chris Lattner46cd5a12009-01-09 05:44:56 +000011951 /// Y = gep X, <...constant indices...>
11952 /// into a gep of the original struct. This is important for SROA and alias
11953 /// analysis of unions. If "A" is also a bitcast, wait for A/X to be merged.
Chris Lattner58407792009-01-09 04:53:57 +000011954 if (BitCastInst *BCI = dyn_cast<BitCastInst>(PtrOp)) {
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011955 if (TD &&
11956 !isa<BitCastInst>(BCI->getOperand(0)) && GEP.hasAllConstantIndices()) {
Chris Lattner46cd5a12009-01-09 05:44:56 +000011957 // Determine how much the GEP moves the pointer. We are guaranteed to get
11958 // a constant back from EmitGEPOffset.
Chris Lattner092543c2009-11-04 08:05:20 +000011959 ConstantInt *OffsetV = cast<ConstantInt>(EmitGEPOffset(&GEP, *this));
Chris Lattner46cd5a12009-01-09 05:44:56 +000011960 int64_t Offset = OffsetV->getSExtValue();
11961
11962 // If this GEP instruction doesn't move the pointer, just replace the GEP
11963 // with a bitcast of the real input to the dest type.
11964 if (Offset == 0) {
11965 // If the bitcast is of an allocation, and the allocation will be
11966 // converted to match the type of the cast, don't touch this.
Victor Hernandez7b929da2009-10-23 21:09:37 +000011967 if (isa<AllocaInst>(BCI->getOperand(0)) ||
Victor Hernandez83d63912009-09-18 22:35:49 +000011968 isMalloc(BCI->getOperand(0))) {
Chris Lattner46cd5a12009-01-09 05:44:56 +000011969 // See if the bitcast simplifies, if so, don't nuke this GEP yet.
11970 if (Instruction *I = visitBitCast(*BCI)) {
11971 if (I != BCI) {
11972 I->takeName(BCI);
11973 BCI->getParent()->getInstList().insert(BCI, I);
11974 ReplaceInstUsesWith(*BCI, I);
11975 }
11976 return &GEP;
Chris Lattner58407792009-01-09 04:53:57 +000011977 }
Chris Lattner58407792009-01-09 04:53:57 +000011978 }
Chris Lattner46cd5a12009-01-09 05:44:56 +000011979 return new BitCastInst(BCI->getOperand(0), GEP.getType());
Chris Lattner58407792009-01-09 04:53:57 +000011980 }
Chris Lattner46cd5a12009-01-09 05:44:56 +000011981
11982 // Otherwise, if the offset is non-zero, we need to find out if there is a
11983 // field at Offset in 'A's type. If so, we can pull the cast through the
11984 // GEP.
11985 SmallVector<Value*, 8> NewIndices;
11986 const Type *InTy =
11987 cast<PointerType>(BCI->getOperand(0)->getType())->getElementType();
Chris Lattner4de84762010-01-04 07:02:48 +000011988 if (FindElementAtOffset(InTy, Offset, NewIndices, TD)) {
Dan Gohmanf8dbee72009-09-07 23:54:19 +000011989 Value *NGEP = cast<GEPOperator>(&GEP)->isInBounds() ?
11990 Builder->CreateInBoundsGEP(BCI->getOperand(0), NewIndices.begin(),
11991 NewIndices.end()) :
11992 Builder->CreateGEP(BCI->getOperand(0), NewIndices.begin(),
11993 NewIndices.end());
Chris Lattnerf925cbd2009-08-30 18:50:58 +000011994
11995 if (NGEP->getType() == GEP.getType())
11996 return ReplaceInstUsesWith(GEP, NGEP);
Chris Lattner46cd5a12009-01-09 05:44:56 +000011997 NGEP->takeName(&GEP);
11998 return new BitCastInst(NGEP, GEP.getType());
11999 }
Chris Lattner58407792009-01-09 04:53:57 +000012000 }
12001 }
12002
Chris Lattner8a2a3112001-12-14 16:52:21 +000012003 return 0;
12004}
12005
Victor Hernandez7b929da2009-10-23 21:09:37 +000012006Instruction *InstCombiner::visitAllocaInst(AllocaInst &AI) {
Chris Lattnere3c62812009-11-01 19:50:13 +000012007 // Convert: alloca Ty, C - where C is a constant != 1 into: alloca [C x Ty], 1
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000012008 if (AI.isArrayAllocation()) { // Check C != 1
Reid Spencerb83eb642006-10-20 07:07:24 +000012009 if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
12010 const Type *NewTy =
Owen Andersondebcb012009-07-29 22:17:13 +000012011 ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
Victor Hernandeza276c602009-10-17 01:18:07 +000012012 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
Victor Hernandez7b929da2009-10-23 21:09:37 +000012013 AllocaInst *New = Builder->CreateAlloca(NewTy, 0, AI.getName());
Chris Lattnerf925cbd2009-08-30 18:50:58 +000012014 New->setAlignment(AI.getAlignment());
Misha Brukmanfd939082005-04-21 23:48:37 +000012015
Chris Lattner0864acf2002-11-04 16:18:53 +000012016 // Scan to the end of the allocation instructions, to skip over a block of
Dale Johannesena8915182009-03-11 22:19:43 +000012017 // allocas if possible...also skip interleaved debug info
Chris Lattner0864acf2002-11-04 16:18:53 +000012018 //
12019 BasicBlock::iterator It = New;
Victor Hernandez7b929da2009-10-23 21:09:37 +000012020 while (isa<AllocaInst>(*It) || isa<DbgInfoIntrinsic>(*It)) ++It;
Chris Lattner0864acf2002-11-04 16:18:53 +000012021
12022 // Now that I is pointing to the first non-allocation-inst in the block,
12023 // insert our getelementptr instruction...
12024 //
Chris Lattner4de84762010-01-04 07:02:48 +000012025 Value *NullIdx =Constant::getNullValue(Type::getInt32Ty(AI.getContext()));
David Greeneb8f74792007-09-04 15:46:09 +000012026 Value *Idx[2];
12027 Idx[0] = NullIdx;
12028 Idx[1] = NullIdx;
Dan Gohmanf8dbee72009-09-07 23:54:19 +000012029 Value *V = GetElementPtrInst::CreateInBounds(New, Idx, Idx + 2,
12030 New->getName()+".sub", It);
Chris Lattner0864acf2002-11-04 16:18:53 +000012031
12032 // Now make everything use the getelementptr instead of the original
12033 // allocation.
Chris Lattner7c881df2004-03-19 06:08:10 +000012034 return ReplaceInstUsesWith(AI, V);
Chris Lattnere87597f2004-10-16 18:11:37 +000012035 } else if (isa<UndefValue>(AI.getArraySize())) {
Owen Andersona7235ea2009-07-31 20:28:14 +000012036 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
Chris Lattner0864acf2002-11-04 16:18:53 +000012037 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000012038 }
Chris Lattner7c881df2004-03-19 06:08:10 +000012039
Dan Gohmance9fe9f2009-07-21 23:21:54 +000012040 if (TD && isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized()) {
Dan Gohman6893cd72009-01-13 20:18:38 +000012041 // If alloca'ing a zero byte object, replace the alloca with a null pointer.
Chris Lattner46d232d2009-03-17 17:55:15 +000012042 // Note that we only do this for alloca's, because malloc should allocate
12043 // and return a unique pointer, even for a zero byte allocation.
Duncan Sands777d2302009-05-09 07:06:46 +000012044 if (TD->getTypeAllocSize(AI.getAllocatedType()) == 0)
Owen Andersona7235ea2009-07-31 20:28:14 +000012045 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
Dan Gohman6893cd72009-01-13 20:18:38 +000012046
12047 // If the alignment is 0 (unspecified), assign it the preferred alignment.
12048 if (AI.getAlignment() == 0)
12049 AI.setAlignment(TD->getPrefTypeAlignment(AI.getAllocatedType()));
12050 }
Chris Lattner7c881df2004-03-19 06:08:10 +000012051
Chris Lattner0864acf2002-11-04 16:18:53 +000012052 return 0;
12053}
12054
Victor Hernandez66284e02009-10-24 04:23:03 +000012055Instruction *InstCombiner::visitFree(Instruction &FI) {
12056 Value *Op = FI.getOperand(1);
12057
12058 // free undef -> unreachable.
12059 if (isa<UndefValue>(Op)) {
12060 // Insert a new store to null because we cannot modify the CFG here.
Chris Lattner4de84762010-01-04 07:02:48 +000012061 new StoreInst(ConstantInt::getTrue(FI.getContext()),
12062 UndefValue::get(Type::getInt1PtrTy(FI.getContext())), &FI);
Victor Hernandez66284e02009-10-24 04:23:03 +000012063 return EraseInstFromFunction(FI);
12064 }
12065
12066 // If we have 'free null' delete the instruction. This can happen in stl code
12067 // when lots of inlining happens.
12068 if (isa<ConstantPointerNull>(Op))
12069 return EraseInstFromFunction(FI);
12070
Victor Hernandez046e78c2009-10-26 23:43:48 +000012071 // If we have a malloc call whose only use is a free call, delete both.
Dan Gohman7f712a12009-10-27 00:11:02 +000012072 if (isMalloc(Op)) {
Victor Hernandez66284e02009-10-24 04:23:03 +000012073 if (CallInst* CI = extractMallocCallFromBitCast(Op)) {
12074 if (Op->hasOneUse() && CI->hasOneUse()) {
12075 EraseInstFromFunction(FI);
12076 EraseInstFromFunction(*CI);
12077 return EraseInstFromFunction(*cast<Instruction>(Op));
12078 }
12079 } else {
12080 // Op is a call to malloc
12081 if (Op->hasOneUse()) {
12082 EraseInstFromFunction(FI);
12083 return EraseInstFromFunction(*cast<Instruction>(Op));
12084 }
12085 }
Dan Gohman7f712a12009-10-27 00:11:02 +000012086 }
Victor Hernandez66284e02009-10-24 04:23:03 +000012087
12088 return 0;
12089}
Chris Lattner67b1e1b2003-12-07 01:24:23 +000012090
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000012091/// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
Devang Patel99db6ad2007-10-18 19:52:32 +000012092static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI,
Bill Wendling587c01d2008-02-26 10:53:30 +000012093 const TargetData *TD) {
Chris Lattnerb89e0712004-07-13 01:49:43 +000012094 User *CI = cast<User>(LI.getOperand(0));
Chris Lattnerf9527852005-01-31 04:50:46 +000012095 Value *CastOp = CI->getOperand(0);
Chris Lattnerb89e0712004-07-13 01:49:43 +000012096
Mon P Wang6753f952009-02-07 22:19:29 +000012097 const PointerType *DestTy = cast<PointerType>(CI->getType());
12098 const Type *DestPTy = DestTy->getElementType();
Chris Lattnerf9527852005-01-31 04:50:46 +000012099 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
Mon P Wang6753f952009-02-07 22:19:29 +000012100
12101 // If the address spaces don't match, don't eliminate the cast.
12102 if (DestTy->getAddressSpace() != SrcTy->getAddressSpace())
12103 return 0;
12104
Chris Lattnerb89e0712004-07-13 01:49:43 +000012105 const Type *SrcPTy = SrcTy->getElementType();
Chris Lattnerf9527852005-01-31 04:50:46 +000012106
Reid Spencer42230162007-01-22 05:51:25 +000012107 if (DestPTy->isInteger() || isa<PointerType>(DestPTy) ||
Reid Spencer9d6565a2007-02-15 02:26:10 +000012108 isa<VectorType>(DestPTy)) {
Chris Lattnerf9527852005-01-31 04:50:46 +000012109 // If the source is an array, the code below will not succeed. Check to
12110 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
12111 // constants.
12112 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
12113 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
12114 if (ASrcTy->getNumElements() != 0) {
Chris Lattner55eb1c42007-01-31 04:40:53 +000012115 Value *Idxs[2];
Chris Lattner4de84762010-01-04 07:02:48 +000012116 Idxs[0] = Constant::getNullValue(Type::getInt32Ty(LI.getContext()));
Chris Lattnere00c43f2009-10-22 06:44:07 +000012117 Idxs[1] = Idxs[0];
Owen Andersonbaf3c402009-07-29 18:55:55 +000012118 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
Chris Lattnerf9527852005-01-31 04:50:46 +000012119 SrcTy = cast<PointerType>(CastOp->getType());
12120 SrcPTy = SrcTy->getElementType();
12121 }
12122
Dan Gohmance9fe9f2009-07-21 23:21:54 +000012123 if (IC.getTargetData() &&
12124 (SrcPTy->isInteger() || isa<PointerType>(SrcPTy) ||
Reid Spencer9d6565a2007-02-15 02:26:10 +000012125 isa<VectorType>(SrcPTy)) &&
Chris Lattnerb1515fe2005-03-29 06:37:47 +000012126 // Do not allow turning this into a load of an integer, which is then
12127 // casted to a pointer, this pessimizes pointer analysis a lot.
12128 (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
Dan Gohmance9fe9f2009-07-21 23:21:54 +000012129 IC.getTargetData()->getTypeSizeInBits(SrcPTy) ==
12130 IC.getTargetData()->getTypeSizeInBits(DestPTy)) {
Misha Brukmanfd939082005-04-21 23:48:37 +000012131
Chris Lattnerf9527852005-01-31 04:50:46 +000012132 // Okay, we are casting from one integer or pointer type to another of
12133 // the same size. Instead of casting the pointer before the load, cast
12134 // the result of the loaded value.
Chris Lattnerf925cbd2009-08-30 18:50:58 +000012135 Value *NewLoad =
12136 IC.Builder->CreateLoad(CastOp, LI.isVolatile(), CI->getName());
Chris Lattnerf9527852005-01-31 04:50:46 +000012137 // Now cast the result of the load.
Reid Spencerd977d862006-12-12 23:36:14 +000012138 return new BitCastInst(NewLoad, LI.getType());
Chris Lattnerf9527852005-01-31 04:50:46 +000012139 }
Chris Lattnerb89e0712004-07-13 01:49:43 +000012140 }
12141 }
12142 return 0;
12143}
12144
Chris Lattner833b8a42003-06-26 05:06:25 +000012145Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
12146 Value *Op = LI.getOperand(0);
Chris Lattner5f16a132004-01-12 04:13:56 +000012147
Dan Gohman9941f742007-07-20 16:34:21 +000012148 // Attempt to improve the alignment.
Dan Gohmance9fe9f2009-07-21 23:21:54 +000012149 if (TD) {
12150 unsigned KnownAlign =
12151 GetOrEnforceKnownAlignment(Op, TD->getPrefTypeAlignment(LI.getType()));
12152 if (KnownAlign >
12153 (LI.getAlignment() == 0 ? TD->getABITypeAlignment(LI.getType()) :
12154 LI.getAlignment()))
12155 LI.setAlignment(KnownAlign);
12156 }
Dan Gohman9941f742007-07-20 16:34:21 +000012157
Chris Lattner963f4ba2009-08-30 20:36:46 +000012158 // load (cast X) --> cast (load X) iff safe.
Reid Spencer3ed469c2006-11-02 20:25:50 +000012159 if (isa<CastInst>(Op))
Devang Patel99db6ad2007-10-18 19:52:32 +000012160 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
Chris Lattner37366c12005-05-01 04:24:53 +000012161 return Res;
12162
12163 // None of the following transforms are legal for volatile loads.
12164 if (LI.isVolatile()) return 0;
Chris Lattner62f254d2005-09-12 22:00:15 +000012165
Dan Gohman2276a7b2008-10-15 23:19:35 +000012166 // Do really simple store-to-load forwarding and load CSE, to catch cases
12167 // where there are several consequtive memory accesses to the same location,
12168 // separated by a few arithmetic operations.
12169 BasicBlock::iterator BBI = &LI;
Chris Lattner4aebaee2008-11-27 08:56:30 +000012170 if (Value *AvailableVal = FindAvailableLoadedValue(Op, LI.getParent(), BBI,6))
12171 return ReplaceInstUsesWith(LI, AvailableVal);
Chris Lattner37366c12005-05-01 04:24:53 +000012172
Chris Lattner878e4942009-10-22 06:25:11 +000012173 // load(gep null, ...) -> unreachable
Christopher Lambb15147e2007-12-29 07:56:53 +000012174 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
12175 const Value *GEPI0 = GEPI->getOperand(0);
12176 // TODO: Consider a target hook for valid address spaces for this xform.
Chris Lattner8a67ac52009-08-30 20:06:40 +000012177 if (isa<ConstantPointerNull>(GEPI0) && GEPI->getPointerAddressSpace() == 0){
Chris Lattner37366c12005-05-01 04:24:53 +000012178 // Insert a new store to null instruction before the load to indicate
12179 // that this code is not reachable. We do this instead of inserting
12180 // an unreachable instruction directly because we cannot modify the
12181 // CFG.
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012182 new StoreInst(UndefValue::get(LI.getType()),
Owen Andersona7235ea2009-07-31 20:28:14 +000012183 Constant::getNullValue(Op->getType()), &LI);
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012184 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Chris Lattner37366c12005-05-01 04:24:53 +000012185 }
Christopher Lambb15147e2007-12-29 07:56:53 +000012186 }
Chris Lattner37366c12005-05-01 04:24:53 +000012187
Chris Lattner878e4942009-10-22 06:25:11 +000012188 // load null/undef -> unreachable
12189 // TODO: Consider a target hook for valid address spaces for this xform.
12190 if (isa<UndefValue>(Op) ||
12191 (isa<ConstantPointerNull>(Op) && LI.getPointerAddressSpace() == 0)) {
12192 // Insert a new store to null instruction before the load to indicate that
12193 // this code is not reachable. We do this instead of inserting an
12194 // unreachable instruction directly because we cannot modify the CFG.
12195 new StoreInst(UndefValue::get(LI.getType()),
12196 Constant::getNullValue(Op->getType()), &LI);
12197 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +000012198 }
Chris Lattner878e4942009-10-22 06:25:11 +000012199
12200 // Instcombine load (constantexpr_cast global) -> cast (load global)
12201 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op))
12202 if (CE->isCast())
12203 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
12204 return Res;
12205
Chris Lattner37366c12005-05-01 04:24:53 +000012206 if (Op->hasOneUse()) {
Chris Lattnerc10aced2004-09-19 18:43:46 +000012207 // Change select and PHI nodes to select values instead of addresses: this
12208 // helps alias analysis out a lot, allows many others simplifications, and
12209 // exposes redundancy in the code.
12210 //
12211 // Note that we cannot do the transformation unless we know that the
12212 // introduced loads cannot trap! Something like this is valid as long as
12213 // the condition is always false: load (select bool %C, int* null, int* %G),
12214 // but it would not be valid if we transformed it to load from null
12215 // unconditionally.
12216 //
12217 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
12218 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
Chris Lattner8a375202004-09-19 19:18:10 +000012219 if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
12220 isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +000012221 Value *V1 = Builder->CreateLoad(SI->getOperand(1),
12222 SI->getOperand(1)->getName()+".val");
12223 Value *V2 = Builder->CreateLoad(SI->getOperand(2),
12224 SI->getOperand(2)->getName()+".val");
Gabor Greif051a9502008-04-06 20:25:17 +000012225 return SelectInst::Create(SI->getCondition(), V1, V2);
Chris Lattnerc10aced2004-09-19 18:43:46 +000012226 }
12227
Chris Lattner684fe212004-09-23 15:46:00 +000012228 // load (select (cond, null, P)) -> load P
12229 if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
12230 if (C->isNullValue()) {
12231 LI.setOperand(0, SI->getOperand(2));
12232 return &LI;
12233 }
12234
12235 // load (select (cond, P, null)) -> load P
12236 if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
12237 if (C->isNullValue()) {
12238 LI.setOperand(0, SI->getOperand(1));
12239 return &LI;
12240 }
Chris Lattnerc10aced2004-09-19 18:43:46 +000012241 }
12242 }
Chris Lattner833b8a42003-06-26 05:06:25 +000012243 return 0;
12244}
12245
Reid Spencer55af2b52007-01-19 21:20:31 +000012246/// InstCombineStoreToCast - Fold store V, (cast P) -> store (cast V), P
Chris Lattner3914f722009-01-24 01:00:13 +000012247/// when possible. This makes it generally easy to do alias analysis and/or
12248/// SROA/mem2reg of the memory object.
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000012249static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
12250 User *CI = cast<User>(SI.getOperand(1));
12251 Value *CastOp = CI->getOperand(0);
12252
12253 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
Chris Lattner1b8eaf52009-01-16 20:08:59 +000012254 const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType());
12255 if (SrcTy == 0) return 0;
12256
12257 const Type *SrcPTy = SrcTy->getElementType();
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000012258
Chris Lattner1b8eaf52009-01-16 20:08:59 +000012259 if (!DestPTy->isInteger() && !isa<PointerType>(DestPTy))
12260 return 0;
12261
Chris Lattner3914f722009-01-24 01:00:13 +000012262 /// NewGEPIndices - If SrcPTy is an aggregate type, we can emit a "noop gep"
12263 /// to its first element. This allows us to handle things like:
12264 /// store i32 xxx, (bitcast {foo*, float}* %P to i32*)
12265 /// on 32-bit hosts.
12266 SmallVector<Value*, 4> NewGEPIndices;
12267
Chris Lattner1b8eaf52009-01-16 20:08:59 +000012268 // If the source is an array, the code below will not succeed. Check to
12269 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
12270 // constants.
Chris Lattner3914f722009-01-24 01:00:13 +000012271 if (isa<ArrayType>(SrcPTy) || isa<StructType>(SrcPTy)) {
12272 // Index through pointer.
Chris Lattner4de84762010-01-04 07:02:48 +000012273 Constant *Zero = Constant::getNullValue(Type::getInt32Ty(SI.getContext()));
Chris Lattner3914f722009-01-24 01:00:13 +000012274 NewGEPIndices.push_back(Zero);
12275
12276 while (1) {
12277 if (const StructType *STy = dyn_cast<StructType>(SrcPTy)) {
Torok Edwin08ffee52009-01-24 17:16:04 +000012278 if (!STy->getNumElements()) /* Struct can be empty {} */
Torok Edwin629e92b2009-01-24 11:30:49 +000012279 break;
Chris Lattner3914f722009-01-24 01:00:13 +000012280 NewGEPIndices.push_back(Zero);
12281 SrcPTy = STy->getElementType(0);
12282 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcPTy)) {
12283 NewGEPIndices.push_back(Zero);
12284 SrcPTy = ATy->getElementType();
12285 } else {
12286 break;
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000012287 }
Chris Lattner3914f722009-01-24 01:00:13 +000012288 }
12289
Owen Andersondebcb012009-07-29 22:17:13 +000012290 SrcTy = PointerType::get(SrcPTy, SrcTy->getAddressSpace());
Chris Lattner3914f722009-01-24 01:00:13 +000012291 }
Chris Lattner1b8eaf52009-01-16 20:08:59 +000012292
12293 if (!SrcPTy->isInteger() && !isa<PointerType>(SrcPTy))
12294 return 0;
12295
Chris Lattner71759c42009-01-16 20:12:52 +000012296 // If the pointers point into different address spaces or if they point to
12297 // values with different sizes, we can't do the transformation.
Dan Gohmance9fe9f2009-07-21 23:21:54 +000012298 if (!IC.getTargetData() ||
12299 SrcTy->getAddressSpace() !=
Chris Lattner71759c42009-01-16 20:12:52 +000012300 cast<PointerType>(CI->getType())->getAddressSpace() ||
Dan Gohmance9fe9f2009-07-21 23:21:54 +000012301 IC.getTargetData()->getTypeSizeInBits(SrcPTy) !=
12302 IC.getTargetData()->getTypeSizeInBits(DestPTy))
Chris Lattner1b8eaf52009-01-16 20:08:59 +000012303 return 0;
12304
12305 // Okay, we are casting from one integer or pointer type to another of
12306 // the same size. Instead of casting the pointer before
12307 // the store, cast the value to be stored.
12308 Value *NewCast;
12309 Value *SIOp0 = SI.getOperand(0);
12310 Instruction::CastOps opcode = Instruction::BitCast;
12311 const Type* CastSrcTy = SIOp0->getType();
12312 const Type* CastDstTy = SrcPTy;
12313 if (isa<PointerType>(CastDstTy)) {
12314 if (CastSrcTy->isInteger())
12315 opcode = Instruction::IntToPtr;
12316 } else if (isa<IntegerType>(CastDstTy)) {
12317 if (isa<PointerType>(SIOp0->getType()))
12318 opcode = Instruction::PtrToInt;
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000012319 }
Chris Lattner3914f722009-01-24 01:00:13 +000012320
12321 // SIOp0 is a pointer to aggregate and this is a store to the first field,
12322 // emit a GEP to index into its first field.
Dan Gohmanf8dbee72009-09-07 23:54:19 +000012323 if (!NewGEPIndices.empty())
12324 CastOp = IC.Builder->CreateInBoundsGEP(CastOp, NewGEPIndices.begin(),
12325 NewGEPIndices.end());
Chris Lattner3914f722009-01-24 01:00:13 +000012326
Chris Lattnerf925cbd2009-08-30 18:50:58 +000012327 NewCast = IC.Builder->CreateCast(opcode, SIOp0, CastDstTy,
12328 SIOp0->getName()+".c");
Chris Lattner1b8eaf52009-01-16 20:08:59 +000012329 return new StoreInst(NewCast, CastOp);
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000012330}
12331
Chris Lattner4aebaee2008-11-27 08:56:30 +000012332/// equivalentAddressValues - Test if A and B will obviously have the same
12333/// value. This includes recognizing that %t0 and %t1 will have the same
12334/// value in code like this:
Dan Gohman0f8b53f2009-03-03 02:55:14 +000012335/// %t0 = getelementptr \@a, 0, 3
Chris Lattner4aebaee2008-11-27 08:56:30 +000012336/// store i32 0, i32* %t0
Dan Gohman0f8b53f2009-03-03 02:55:14 +000012337/// %t1 = getelementptr \@a, 0, 3
Chris Lattner4aebaee2008-11-27 08:56:30 +000012338/// %t2 = load i32* %t1
12339///
12340static bool equivalentAddressValues(Value *A, Value *B) {
12341 // Test if the values are trivially equivalent.
12342 if (A == B) return true;
12343
12344 // Test if the values come form identical arithmetic instructions.
Dan Gohman58cfa3b2009-08-25 22:11:20 +000012345 // This uses isIdenticalToWhenDefined instead of isIdenticalTo because
12346 // its only used to compare two uses within the same basic block, which
12347 // means that they'll always either have the same value or one of them
12348 // will have an undefined value.
Chris Lattner4aebaee2008-11-27 08:56:30 +000012349 if (isa<BinaryOperator>(A) ||
12350 isa<CastInst>(A) ||
12351 isa<PHINode>(A) ||
12352 isa<GetElementPtrInst>(A))
12353 if (Instruction *BI = dyn_cast<Instruction>(B))
Dan Gohman58cfa3b2009-08-25 22:11:20 +000012354 if (cast<Instruction>(A)->isIdenticalToWhenDefined(BI))
Chris Lattner4aebaee2008-11-27 08:56:30 +000012355 return true;
12356
12357 // Otherwise they may not be equivalent.
12358 return false;
12359}
12360
Dale Johannesen4945c652009-03-03 21:26:39 +000012361// If this instruction has two uses, one of which is a llvm.dbg.declare,
12362// return the llvm.dbg.declare.
12363DbgDeclareInst *InstCombiner::hasOneUsePlusDeclare(Value *V) {
12364 if (!V->hasNUses(2))
12365 return 0;
12366 for (Value::use_iterator UI = V->use_begin(), E = V->use_end();
12367 UI != E; ++UI) {
12368 if (DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(UI))
12369 return DI;
12370 if (isa<BitCastInst>(UI) && UI->hasOneUse()) {
12371 if (DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(UI->use_begin()))
12372 return DI;
12373 }
12374 }
12375 return 0;
12376}
12377
Chris Lattner2f503e62005-01-31 05:36:43 +000012378Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
12379 Value *Val = SI.getOperand(0);
12380 Value *Ptr = SI.getOperand(1);
12381
Chris Lattner836692d2007-01-15 06:51:56 +000012382 // If the RHS is an alloca with a single use, zapify the store, making the
12383 // alloca dead.
Dale Johannesen4945c652009-03-03 21:26:39 +000012384 // If the RHS is an alloca with a two uses, the other one being a
12385 // llvm.dbg.declare, zapify the store and the declare, making the
12386 // alloca dead. We must do this to prevent declare's from affecting
12387 // codegen.
12388 if (!SI.isVolatile()) {
12389 if (Ptr->hasOneUse()) {
12390 if (isa<AllocaInst>(Ptr)) {
Chris Lattner836692d2007-01-15 06:51:56 +000012391 EraseInstFromFunction(SI);
12392 ++NumCombined;
12393 return 0;
12394 }
Dale Johannesen4945c652009-03-03 21:26:39 +000012395 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr)) {
12396 if (isa<AllocaInst>(GEP->getOperand(0))) {
12397 if (GEP->getOperand(0)->hasOneUse()) {
12398 EraseInstFromFunction(SI);
12399 ++NumCombined;
12400 return 0;
12401 }
12402 if (DbgDeclareInst *DI = hasOneUsePlusDeclare(GEP->getOperand(0))) {
12403 EraseInstFromFunction(*DI);
12404 EraseInstFromFunction(SI);
12405 ++NumCombined;
12406 return 0;
12407 }
12408 }
12409 }
12410 }
12411 if (DbgDeclareInst *DI = hasOneUsePlusDeclare(Ptr)) {
12412 EraseInstFromFunction(*DI);
12413 EraseInstFromFunction(SI);
12414 ++NumCombined;
12415 return 0;
12416 }
Chris Lattner836692d2007-01-15 06:51:56 +000012417 }
Chris Lattner2f503e62005-01-31 05:36:43 +000012418
Dan Gohman9941f742007-07-20 16:34:21 +000012419 // Attempt to improve the alignment.
Dan Gohmance9fe9f2009-07-21 23:21:54 +000012420 if (TD) {
12421 unsigned KnownAlign =
12422 GetOrEnforceKnownAlignment(Ptr, TD->getPrefTypeAlignment(Val->getType()));
12423 if (KnownAlign >
12424 (SI.getAlignment() == 0 ? TD->getABITypeAlignment(Val->getType()) :
12425 SI.getAlignment()))
12426 SI.setAlignment(KnownAlign);
12427 }
Dan Gohman9941f742007-07-20 16:34:21 +000012428
Dale Johannesenacb51a32009-03-03 01:43:03 +000012429 // Do really simple DSE, to catch cases where there are several consecutive
Chris Lattner9ca96412006-02-08 03:25:32 +000012430 // stores to the same location, separated by a few arithmetic operations. This
12431 // situation often occurs with bitfield accesses.
12432 BasicBlock::iterator BBI = &SI;
12433 for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
12434 --ScanInsts) {
Dale Johannesen0d6596b2009-03-04 01:20:34 +000012435 --BBI;
Dale Johannesencdb16aa2009-03-04 01:53:05 +000012436 // Don't count debug info directives, lest they affect codegen,
12437 // and we skip pointer-to-pointer bitcasts, which are NOPs.
12438 // It is necessary for correctness to skip those that feed into a
12439 // llvm.dbg.declare, as these are not present when debugging is off.
Dale Johannesen4ded40a2009-03-03 22:36:47 +000012440 if (isa<DbgInfoIntrinsic>(BBI) ||
Dale Johannesencdb16aa2009-03-04 01:53:05 +000012441 (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType()))) {
Dale Johannesenacb51a32009-03-03 01:43:03 +000012442 ScanInsts++;
Dale Johannesenacb51a32009-03-03 01:43:03 +000012443 continue;
12444 }
Chris Lattner9ca96412006-02-08 03:25:32 +000012445
12446 if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
12447 // Prev store isn't volatile, and stores to the same location?
Chris Lattner4aebaee2008-11-27 08:56:30 +000012448 if (!PrevSI->isVolatile() &&equivalentAddressValues(PrevSI->getOperand(1),
12449 SI.getOperand(1))) {
Chris Lattner9ca96412006-02-08 03:25:32 +000012450 ++NumDeadStore;
12451 ++BBI;
12452 EraseInstFromFunction(*PrevSI);
12453 continue;
12454 }
12455 break;
12456 }
12457
Chris Lattnerb4db97f2006-05-26 19:19:20 +000012458 // If this is a load, we have to stop. However, if the loaded value is from
12459 // the pointer we're loading and is producing the pointer we're storing,
12460 // then *this* store is dead (X = load P; store X -> P).
12461 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
Dan Gohman2276a7b2008-10-15 23:19:35 +000012462 if (LI == Val && equivalentAddressValues(LI->getOperand(0), Ptr) &&
12463 !SI.isVolatile()) {
Chris Lattnerb4db97f2006-05-26 19:19:20 +000012464 EraseInstFromFunction(SI);
12465 ++NumCombined;
12466 return 0;
12467 }
12468 // Otherwise, this is a load from some other location. Stores before it
12469 // may not be dead.
12470 break;
12471 }
12472
Chris Lattner9ca96412006-02-08 03:25:32 +000012473 // Don't skip over loads or things that can modify memory.
Chris Lattner0ef546e2008-05-08 17:20:30 +000012474 if (BBI->mayWriteToMemory() || BBI->mayReadFromMemory())
Chris Lattner9ca96412006-02-08 03:25:32 +000012475 break;
12476 }
12477
12478
12479 if (SI.isVolatile()) return 0; // Don't hack volatile stores.
Chris Lattner2f503e62005-01-31 05:36:43 +000012480
12481 // store X, null -> turns into 'unreachable' in SimplifyCFG
Chris Lattner8a67ac52009-08-30 20:06:40 +000012482 if (isa<ConstantPointerNull>(Ptr) && SI.getPointerAddressSpace() == 0) {
Chris Lattner2f503e62005-01-31 05:36:43 +000012483 if (!isa<UndefValue>(Val)) {
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012484 SI.setOperand(0, UndefValue::get(Val->getType()));
Chris Lattner2f503e62005-01-31 05:36:43 +000012485 if (Instruction *U = dyn_cast<Instruction>(Val))
Chris Lattner7a1e9242009-08-30 06:13:40 +000012486 Worklist.Add(U); // Dropped a use.
Chris Lattner2f503e62005-01-31 05:36:43 +000012487 ++NumCombined;
12488 }
12489 return 0; // Do not modify these!
12490 }
12491
12492 // store undef, Ptr -> noop
12493 if (isa<UndefValue>(Val)) {
Chris Lattner9ca96412006-02-08 03:25:32 +000012494 EraseInstFromFunction(SI);
Chris Lattner2f503e62005-01-31 05:36:43 +000012495 ++NumCombined;
12496 return 0;
12497 }
12498
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000012499 // If the pointer destination is a cast, see if we can fold the cast into the
12500 // source instead.
Reid Spencer3ed469c2006-11-02 20:25:50 +000012501 if (isa<CastInst>(Ptr))
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000012502 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
12503 return Res;
12504 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
Reid Spencer3da59db2006-11-27 01:05:10 +000012505 if (CE->isCast())
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000012506 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
12507 return Res;
12508
Chris Lattner408902b2005-09-12 23:23:25 +000012509
Dale Johannesen4084c4e2009-03-05 02:06:48 +000012510 // If this store is the last instruction in the basic block (possibly
12511 // excepting debug info instructions and the pointer bitcasts that feed
12512 // into them), and if the block ends with an unconditional branch, try
12513 // to move it to the successor block.
12514 BBI = &SI;
12515 do {
12516 ++BBI;
12517 } while (isa<DbgInfoIntrinsic>(BBI) ||
12518 (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType())));
Chris Lattner408902b2005-09-12 23:23:25 +000012519 if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
Chris Lattner3284d1f2007-04-15 00:07:55 +000012520 if (BI->isUnconditional())
12521 if (SimplifyStoreAtEndOfBlock(SI))
12522 return 0; // xform done!
Chris Lattner408902b2005-09-12 23:23:25 +000012523
Chris Lattner2f503e62005-01-31 05:36:43 +000012524 return 0;
12525}
12526
Chris Lattner3284d1f2007-04-15 00:07:55 +000012527/// SimplifyStoreAtEndOfBlock - Turn things like:
12528/// if () { *P = v1; } else { *P = v2 }
12529/// into a phi node with a store in the successor.
12530///
Chris Lattner31755a02007-04-15 01:02:18 +000012531/// Simplify things like:
12532/// *P = v1; if () { *P = v2; }
12533/// into a phi node with a store in the successor.
12534///
Chris Lattner3284d1f2007-04-15 00:07:55 +000012535bool InstCombiner::SimplifyStoreAtEndOfBlock(StoreInst &SI) {
12536 BasicBlock *StoreBB = SI.getParent();
12537
12538 // Check to see if the successor block has exactly two incoming edges. If
12539 // so, see if the other predecessor contains a store to the same location.
12540 // if so, insert a PHI node (if needed) and move the stores down.
Chris Lattner31755a02007-04-15 01:02:18 +000012541 BasicBlock *DestBB = StoreBB->getTerminator()->getSuccessor(0);
Chris Lattner3284d1f2007-04-15 00:07:55 +000012542
12543 // Determine whether Dest has exactly two predecessors and, if so, compute
12544 // the other predecessor.
Chris Lattner31755a02007-04-15 01:02:18 +000012545 pred_iterator PI = pred_begin(DestBB);
12546 BasicBlock *OtherBB = 0;
Chris Lattner3284d1f2007-04-15 00:07:55 +000012547 if (*PI != StoreBB)
Chris Lattner31755a02007-04-15 01:02:18 +000012548 OtherBB = *PI;
Chris Lattner3284d1f2007-04-15 00:07:55 +000012549 ++PI;
Chris Lattner31755a02007-04-15 01:02:18 +000012550 if (PI == pred_end(DestBB))
Chris Lattner3284d1f2007-04-15 00:07:55 +000012551 return false;
12552
12553 if (*PI != StoreBB) {
Chris Lattner31755a02007-04-15 01:02:18 +000012554 if (OtherBB)
Chris Lattner3284d1f2007-04-15 00:07:55 +000012555 return false;
Chris Lattner31755a02007-04-15 01:02:18 +000012556 OtherBB = *PI;
Chris Lattner3284d1f2007-04-15 00:07:55 +000012557 }
Chris Lattner31755a02007-04-15 01:02:18 +000012558 if (++PI != pred_end(DestBB))
Chris Lattner3284d1f2007-04-15 00:07:55 +000012559 return false;
Eli Friedman66fe80a2008-06-13 21:17:49 +000012560
12561 // Bail out if all the relevant blocks aren't distinct (this can happen,
12562 // for example, if SI is in an infinite loop)
12563 if (StoreBB == DestBB || OtherBB == DestBB)
12564 return false;
12565
Chris Lattner31755a02007-04-15 01:02:18 +000012566 // Verify that the other block ends in a branch and is not otherwise empty.
12567 BasicBlock::iterator BBI = OtherBB->getTerminator();
Chris Lattner3284d1f2007-04-15 00:07:55 +000012568 BranchInst *OtherBr = dyn_cast<BranchInst>(BBI);
Chris Lattner31755a02007-04-15 01:02:18 +000012569 if (!OtherBr || BBI == OtherBB->begin())
Chris Lattner3284d1f2007-04-15 00:07:55 +000012570 return false;
12571
Chris Lattner31755a02007-04-15 01:02:18 +000012572 // If the other block ends in an unconditional branch, check for the 'if then
12573 // else' case. there is an instruction before the branch.
12574 StoreInst *OtherStore = 0;
12575 if (OtherBr->isUnconditional()) {
Chris Lattner31755a02007-04-15 01:02:18 +000012576 --BBI;
Dale Johannesen4084c4e2009-03-05 02:06:48 +000012577 // Skip over debugging info.
12578 while (isa<DbgInfoIntrinsic>(BBI) ||
12579 (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType()))) {
12580 if (BBI==OtherBB->begin())
12581 return false;
12582 --BBI;
12583 }
Chris Lattner7ebbabf2009-11-02 02:06:37 +000012584 // If this isn't a store, isn't a store to the same location, or if the
12585 // alignments differ, bail out.
Chris Lattner31755a02007-04-15 01:02:18 +000012586 OtherStore = dyn_cast<StoreInst>(BBI);
Chris Lattner7ebbabf2009-11-02 02:06:37 +000012587 if (!OtherStore || OtherStore->getOperand(1) != SI.getOperand(1) ||
12588 OtherStore->getAlignment() != SI.getAlignment())
Chris Lattner31755a02007-04-15 01:02:18 +000012589 return false;
12590 } else {
Chris Lattnerd717c182007-05-05 22:32:24 +000012591 // Otherwise, the other block ended with a conditional branch. If one of the
Chris Lattner31755a02007-04-15 01:02:18 +000012592 // destinations is StoreBB, then we have the if/then case.
12593 if (OtherBr->getSuccessor(0) != StoreBB &&
12594 OtherBr->getSuccessor(1) != StoreBB)
12595 return false;
12596
12597 // Okay, we know that OtherBr now goes to Dest and StoreBB, so this is an
Chris Lattnerd717c182007-05-05 22:32:24 +000012598 // if/then triangle. See if there is a store to the same ptr as SI that
12599 // lives in OtherBB.
Chris Lattner31755a02007-04-15 01:02:18 +000012600 for (;; --BBI) {
12601 // Check to see if we find the matching store.
12602 if ((OtherStore = dyn_cast<StoreInst>(BBI))) {
Chris Lattner7ebbabf2009-11-02 02:06:37 +000012603 if (OtherStore->getOperand(1) != SI.getOperand(1) ||
12604 OtherStore->getAlignment() != SI.getAlignment())
Chris Lattner31755a02007-04-15 01:02:18 +000012605 return false;
12606 break;
12607 }
Eli Friedman6903a242008-06-13 22:02:12 +000012608 // If we find something that may be using or overwriting the stored
12609 // value, or if we run out of instructions, we can't do the xform.
12610 if (BBI->mayReadFromMemory() || BBI->mayWriteToMemory() ||
Chris Lattner31755a02007-04-15 01:02:18 +000012611 BBI == OtherBB->begin())
12612 return false;
12613 }
12614
12615 // In order to eliminate the store in OtherBr, we have to
Eli Friedman6903a242008-06-13 22:02:12 +000012616 // make sure nothing reads or overwrites the stored value in
12617 // StoreBB.
Chris Lattner31755a02007-04-15 01:02:18 +000012618 for (BasicBlock::iterator I = StoreBB->begin(); &*I != &SI; ++I) {
12619 // FIXME: This should really be AA driven.
Eli Friedman6903a242008-06-13 22:02:12 +000012620 if (I->mayReadFromMemory() || I->mayWriteToMemory())
Chris Lattner31755a02007-04-15 01:02:18 +000012621 return false;
12622 }
12623 }
Chris Lattner3284d1f2007-04-15 00:07:55 +000012624
Chris Lattner31755a02007-04-15 01:02:18 +000012625 // Insert a PHI node now if we need it.
Chris Lattner3284d1f2007-04-15 00:07:55 +000012626 Value *MergedVal = OtherStore->getOperand(0);
12627 if (MergedVal != SI.getOperand(0)) {
Gabor Greif051a9502008-04-06 20:25:17 +000012628 PHINode *PN = PHINode::Create(MergedVal->getType(), "storemerge");
Chris Lattner3284d1f2007-04-15 00:07:55 +000012629 PN->reserveOperandSpace(2);
12630 PN->addIncoming(SI.getOperand(0), SI.getParent());
Chris Lattner31755a02007-04-15 01:02:18 +000012631 PN->addIncoming(OtherStore->getOperand(0), OtherBB);
12632 MergedVal = InsertNewInstBefore(PN, DestBB->front());
Chris Lattner3284d1f2007-04-15 00:07:55 +000012633 }
12634
12635 // Advance to a place where it is safe to insert the new store and
12636 // insert it.
Dan Gohman02dea8b2008-05-23 21:05:58 +000012637 BBI = DestBB->getFirstNonPHI();
Chris Lattner3284d1f2007-04-15 00:07:55 +000012638 InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
Chris Lattner7ebbabf2009-11-02 02:06:37 +000012639 OtherStore->isVolatile(),
12640 SI.getAlignment()), *BBI);
Chris Lattner3284d1f2007-04-15 00:07:55 +000012641
12642 // Nuke the old stores.
12643 EraseInstFromFunction(SI);
12644 EraseInstFromFunction(*OtherStore);
12645 ++NumCombined;
12646 return true;
12647}
12648
Chris Lattner2f503e62005-01-31 05:36:43 +000012649
Chris Lattnerc4d10eb2003-06-04 04:46:00 +000012650Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
12651 // Change br (not X), label True, label False to: br X, label False, True
Reid Spencer4b828e62005-06-18 17:37:34 +000012652 Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +000012653 BasicBlock *TrueDest;
12654 BasicBlock *FalseDest;
Dan Gohman4ae51262009-08-12 16:23:25 +000012655 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
Chris Lattneracd1f0f2004-07-30 07:50:03 +000012656 !isa<Constant>(X)) {
12657 // Swap Destinations and condition...
12658 BI.setCondition(X);
12659 BI.setSuccessor(0, FalseDest);
12660 BI.setSuccessor(1, TrueDest);
12661 return &BI;
12662 }
12663
Reid Spencere4d87aa2006-12-23 06:05:41 +000012664 // Cannonicalize fcmp_one -> fcmp_oeq
12665 FCmpInst::Predicate FPred; Value *Y;
12666 if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)),
Chris Lattner7a1e9242009-08-30 06:13:40 +000012667 TrueDest, FalseDest)) &&
12668 BI.getCondition()->hasOneUse())
12669 if (FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
12670 FPred == FCmpInst::FCMP_OGE) {
12671 FCmpInst *Cond = cast<FCmpInst>(BI.getCondition());
12672 Cond->setPredicate(FCmpInst::getInversePredicate(FPred));
12673
12674 // Swap Destinations and condition.
Reid Spencere4d87aa2006-12-23 06:05:41 +000012675 BI.setSuccessor(0, FalseDest);
12676 BI.setSuccessor(1, TrueDest);
Chris Lattner7a1e9242009-08-30 06:13:40 +000012677 Worklist.Add(Cond);
Reid Spencere4d87aa2006-12-23 06:05:41 +000012678 return &BI;
12679 }
12680
12681 // Cannonicalize icmp_ne -> icmp_eq
12682 ICmpInst::Predicate IPred;
12683 if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
Chris Lattner7a1e9242009-08-30 06:13:40 +000012684 TrueDest, FalseDest)) &&
12685 BI.getCondition()->hasOneUse())
12686 if (IPred == ICmpInst::ICMP_NE || IPred == ICmpInst::ICMP_ULE ||
12687 IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
12688 IPred == ICmpInst::ICMP_SGE) {
12689 ICmpInst *Cond = cast<ICmpInst>(BI.getCondition());
12690 Cond->setPredicate(ICmpInst::getInversePredicate(IPred));
12691 // Swap Destinations and condition.
Chris Lattner40f5d702003-06-04 05:10:11 +000012692 BI.setSuccessor(0, FalseDest);
12693 BI.setSuccessor(1, TrueDest);
Chris Lattner7a1e9242009-08-30 06:13:40 +000012694 Worklist.Add(Cond);
Chris Lattner40f5d702003-06-04 05:10:11 +000012695 return &BI;
12696 }
Misha Brukmanfd939082005-04-21 23:48:37 +000012697
Chris Lattnerc4d10eb2003-06-04 04:46:00 +000012698 return 0;
12699}
Chris Lattner0864acf2002-11-04 16:18:53 +000012700
Chris Lattner46238a62004-07-03 00:26:11 +000012701Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
12702 Value *Cond = SI.getCondition();
12703 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
12704 if (I->getOpcode() == Instruction::Add)
12705 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
12706 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
12707 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
Owen Andersond672ecb2009-07-03 00:17:18 +000012708 SI.setOperand(i,
Owen Andersonbaf3c402009-07-29 18:55:55 +000012709 ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
Chris Lattner46238a62004-07-03 00:26:11 +000012710 AddRHS));
12711 SI.setOperand(0, I->getOperand(0));
Chris Lattner7a1e9242009-08-30 06:13:40 +000012712 Worklist.Add(I);
Chris Lattner46238a62004-07-03 00:26:11 +000012713 return &SI;
12714 }
12715 }
12716 return 0;
12717}
12718
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +000012719Instruction *InstCombiner::visitExtractValueInst(ExtractValueInst &EV) {
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +000012720 Value *Agg = EV.getAggregateOperand();
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +000012721
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +000012722 if (!EV.hasIndices())
12723 return ReplaceInstUsesWith(EV, Agg);
12724
12725 if (Constant *C = dyn_cast<Constant>(Agg)) {
12726 if (isa<UndefValue>(C))
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012727 return ReplaceInstUsesWith(EV, UndefValue::get(EV.getType()));
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +000012728
12729 if (isa<ConstantAggregateZero>(C))
Owen Andersona7235ea2009-07-31 20:28:14 +000012730 return ReplaceInstUsesWith(EV, Constant::getNullValue(EV.getType()));
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +000012731
12732 if (isa<ConstantArray>(C) || isa<ConstantStruct>(C)) {
12733 // Extract the element indexed by the first index out of the constant
12734 Value *V = C->getOperand(*EV.idx_begin());
12735 if (EV.getNumIndices() > 1)
12736 // Extract the remaining indices out of the constant indexed by the
12737 // first index
12738 return ExtractValueInst::Create(V, EV.idx_begin() + 1, EV.idx_end());
12739 else
12740 return ReplaceInstUsesWith(EV, V);
12741 }
12742 return 0; // Can't handle other constants
12743 }
12744 if (InsertValueInst *IV = dyn_cast<InsertValueInst>(Agg)) {
12745 // We're extracting from an insertvalue instruction, compare the indices
12746 const unsigned *exti, *exte, *insi, *inse;
12747 for (exti = EV.idx_begin(), insi = IV->idx_begin(),
12748 exte = EV.idx_end(), inse = IV->idx_end();
12749 exti != exte && insi != inse;
12750 ++exti, ++insi) {
12751 if (*insi != *exti)
12752 // The insert and extract both reference distinctly different elements.
12753 // This means the extract is not influenced by the insert, and we can
12754 // replace the aggregate operand of the extract with the aggregate
12755 // operand of the insert. i.e., replace
12756 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
12757 // %E = extractvalue { i32, { i32 } } %I, 0
12758 // with
12759 // %E = extractvalue { i32, { i32 } } %A, 0
12760 return ExtractValueInst::Create(IV->getAggregateOperand(),
12761 EV.idx_begin(), EV.idx_end());
12762 }
12763 if (exti == exte && insi == inse)
12764 // Both iterators are at the end: Index lists are identical. Replace
12765 // %B = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
12766 // %C = extractvalue { i32, { i32 } } %B, 1, 0
12767 // with "i32 42"
12768 return ReplaceInstUsesWith(EV, IV->getInsertedValueOperand());
12769 if (exti == exte) {
12770 // The extract list is a prefix of the insert list. i.e. replace
12771 // %I = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
12772 // %E = extractvalue { i32, { i32 } } %I, 1
12773 // with
12774 // %X = extractvalue { i32, { i32 } } %A, 1
12775 // %E = insertvalue { i32 } %X, i32 42, 0
12776 // by switching the order of the insert and extract (though the
12777 // insertvalue should be left in, since it may have other uses).
Chris Lattnerf925cbd2009-08-30 18:50:58 +000012778 Value *NewEV = Builder->CreateExtractValue(IV->getAggregateOperand(),
12779 EV.idx_begin(), EV.idx_end());
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +000012780 return InsertValueInst::Create(NewEV, IV->getInsertedValueOperand(),
12781 insi, inse);
12782 }
12783 if (insi == inse)
12784 // The insert list is a prefix of the extract list
12785 // We can simply remove the common indices from the extract and make it
12786 // operate on the inserted value instead of the insertvalue result.
12787 // i.e., replace
12788 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
12789 // %E = extractvalue { i32, { i32 } } %I, 1, 0
12790 // with
12791 // %E extractvalue { i32 } { i32 42 }, 0
12792 return ExtractValueInst::Create(IV->getInsertedValueOperand(),
12793 exti, exte);
12794 }
Chris Lattner7e606e22009-11-09 07:07:56 +000012795 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Agg)) {
12796 // We're extracting from an intrinsic, see if we're the only user, which
12797 // allows us to simplify multiple result intrinsics to simpler things that
12798 // just get one value..
12799 if (II->hasOneUse()) {
12800 // Check if we're grabbing the overflow bit or the result of a 'with
12801 // overflow' intrinsic. If it's the latter we can remove the intrinsic
12802 // and replace it with a traditional binary instruction.
12803 switch (II->getIntrinsicID()) {
12804 case Intrinsic::uadd_with_overflow:
12805 case Intrinsic::sadd_with_overflow:
12806 if (*EV.idx_begin() == 0) { // Normal result.
12807 Value *LHS = II->getOperand(1), *RHS = II->getOperand(2);
12808 II->replaceAllUsesWith(UndefValue::get(II->getType()));
12809 EraseInstFromFunction(*II);
12810 return BinaryOperator::CreateAdd(LHS, RHS);
12811 }
12812 break;
12813 case Intrinsic::usub_with_overflow:
12814 case Intrinsic::ssub_with_overflow:
12815 if (*EV.idx_begin() == 0) { // Normal result.
12816 Value *LHS = II->getOperand(1), *RHS = II->getOperand(2);
12817 II->replaceAllUsesWith(UndefValue::get(II->getType()));
12818 EraseInstFromFunction(*II);
12819 return BinaryOperator::CreateSub(LHS, RHS);
12820 }
12821 break;
12822 case Intrinsic::umul_with_overflow:
12823 case Intrinsic::smul_with_overflow:
12824 if (*EV.idx_begin() == 0) { // Normal result.
12825 Value *LHS = II->getOperand(1), *RHS = II->getOperand(2);
12826 II->replaceAllUsesWith(UndefValue::get(II->getType()));
12827 EraseInstFromFunction(*II);
12828 return BinaryOperator::CreateMul(LHS, RHS);
12829 }
12830 break;
12831 default:
12832 break;
12833 }
12834 }
12835 }
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +000012836 // Can't simplify extracts from other values. Note that nested extracts are
12837 // already simplified implicitely by the above (extract ( extract (insert) )
12838 // will be translated into extract ( insert ( extract ) ) first and then just
12839 // the value inserted, if appropriate).
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +000012840 return 0;
12841}
12842
Chris Lattner220b0cf2006-03-05 00:22:33 +000012843/// CheapToScalarize - Return true if the value is cheaper to scalarize than it
12844/// is to leave as a vector operation.
12845static bool CheapToScalarize(Value *V, bool isConstant) {
12846 if (isa<ConstantAggregateZero>(V))
12847 return true;
Reid Spencer9d6565a2007-02-15 02:26:10 +000012848 if (ConstantVector *C = dyn_cast<ConstantVector>(V)) {
Chris Lattner220b0cf2006-03-05 00:22:33 +000012849 if (isConstant) return true;
12850 // If all elts are the same, we can extract.
12851 Constant *Op0 = C->getOperand(0);
12852 for (unsigned i = 1; i < C->getNumOperands(); ++i)
12853 if (C->getOperand(i) != Op0)
12854 return false;
12855 return true;
12856 }
12857 Instruction *I = dyn_cast<Instruction>(V);
12858 if (!I) return false;
12859
12860 // Insert element gets simplified to the inserted element or is deleted if
12861 // this is constant idx extract element and its a constant idx insertelt.
12862 if (I->getOpcode() == Instruction::InsertElement && isConstant &&
12863 isa<ConstantInt>(I->getOperand(2)))
12864 return true;
12865 if (I->getOpcode() == Instruction::Load && I->hasOneUse())
12866 return true;
12867 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
12868 if (BO->hasOneUse() &&
12869 (CheapToScalarize(BO->getOperand(0), isConstant) ||
12870 CheapToScalarize(BO->getOperand(1), isConstant)))
12871 return true;
Reid Spencere4d87aa2006-12-23 06:05:41 +000012872 if (CmpInst *CI = dyn_cast<CmpInst>(I))
12873 if (CI->hasOneUse() &&
12874 (CheapToScalarize(CI->getOperand(0), isConstant) ||
12875 CheapToScalarize(CI->getOperand(1), isConstant)))
12876 return true;
Chris Lattner220b0cf2006-03-05 00:22:33 +000012877
12878 return false;
12879}
12880
Chris Lattnerd2b7cec2007-02-14 05:52:17 +000012881/// Read and decode a shufflevector mask.
12882///
12883/// It turns undef elements into values that are larger than the number of
12884/// elements in the input.
Chris Lattner863bcff2006-05-25 23:48:38 +000012885static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
12886 unsigned NElts = SVI->getType()->getNumElements();
12887 if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
12888 return std::vector<unsigned>(NElts, 0);
12889 if (isa<UndefValue>(SVI->getOperand(2)))
12890 return std::vector<unsigned>(NElts, 2*NElts);
12891
12892 std::vector<unsigned> Result;
Reid Spencer9d6565a2007-02-15 02:26:10 +000012893 const ConstantVector *CP = cast<ConstantVector>(SVI->getOperand(2));
Gabor Greif177dd3f2008-06-12 21:37:33 +000012894 for (User::const_op_iterator i = CP->op_begin(), e = CP->op_end(); i!=e; ++i)
12895 if (isa<UndefValue>(*i))
Chris Lattner863bcff2006-05-25 23:48:38 +000012896 Result.push_back(NElts*2); // undef -> 8
12897 else
Gabor Greif177dd3f2008-06-12 21:37:33 +000012898 Result.push_back(cast<ConstantInt>(*i)->getZExtValue());
Chris Lattner863bcff2006-05-25 23:48:38 +000012899 return Result;
12900}
12901
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012902/// FindScalarElement - Given a vector and an element number, see if the scalar
12903/// value is already around as a register, for example if it were inserted then
12904/// extracted from the vector.
Chris Lattner4de84762010-01-04 07:02:48 +000012905static Value *FindScalarElement(Value *V, unsigned EltNo) {
Reid Spencer9d6565a2007-02-15 02:26:10 +000012906 assert(isa<VectorType>(V->getType()) && "Not looking at a vector?");
12907 const VectorType *PTy = cast<VectorType>(V->getType());
Chris Lattner389a6f52006-04-10 23:06:36 +000012908 unsigned Width = PTy->getNumElements();
12909 if (EltNo >= Width) // Out of range access.
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012910 return UndefValue::get(PTy->getElementType());
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012911
12912 if (isa<UndefValue>(V))
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012913 return UndefValue::get(PTy->getElementType());
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012914 else if (isa<ConstantAggregateZero>(V))
Owen Andersona7235ea2009-07-31 20:28:14 +000012915 return Constant::getNullValue(PTy->getElementType());
Reid Spencer9d6565a2007-02-15 02:26:10 +000012916 else if (ConstantVector *CP = dyn_cast<ConstantVector>(V))
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012917 return CP->getOperand(EltNo);
12918 else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
12919 // If this is an insert to a variable element, we don't know what it is.
Reid Spencerb83eb642006-10-20 07:07:24 +000012920 if (!isa<ConstantInt>(III->getOperand(2)))
12921 return 0;
12922 unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012923
12924 // If this is an insert to the element we are looking for, return the
12925 // inserted value.
Reid Spencerb83eb642006-10-20 07:07:24 +000012926 if (EltNo == IIElt)
12927 return III->getOperand(1);
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012928
12929 // Otherwise, the insertelement doesn't modify the value, recurse on its
12930 // vector input.
Chris Lattner4de84762010-01-04 07:02:48 +000012931 return FindScalarElement(III->getOperand(0), EltNo);
Chris Lattner389a6f52006-04-10 23:06:36 +000012932 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
Mon P Wangaeb06d22008-11-10 04:46:22 +000012933 unsigned LHSWidth =
12934 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
Chris Lattner863bcff2006-05-25 23:48:38 +000012935 unsigned InEl = getShuffleMask(SVI)[EltNo];
Mon P Wangaeb06d22008-11-10 04:46:22 +000012936 if (InEl < LHSWidth)
Chris Lattner4de84762010-01-04 07:02:48 +000012937 return FindScalarElement(SVI->getOperand(0), InEl);
Mon P Wangaeb06d22008-11-10 04:46:22 +000012938 else if (InEl < LHSWidth*2)
Chris Lattner4de84762010-01-04 07:02:48 +000012939 return FindScalarElement(SVI->getOperand(1), InEl - LHSWidth);
Chris Lattner863bcff2006-05-25 23:48:38 +000012940 else
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012941 return UndefValue::get(PTy->getElementType());
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012942 }
12943
12944 // Otherwise, we don't know.
12945 return 0;
12946}
12947
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012948Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
Dan Gohman07a96762007-07-16 14:29:03 +000012949 // If vector val is undef, replace extract with scalar undef.
Chris Lattner1f13c882006-03-31 18:25:14 +000012950 if (isa<UndefValue>(EI.getOperand(0)))
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012951 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
Chris Lattner1f13c882006-03-31 18:25:14 +000012952
Dan Gohman07a96762007-07-16 14:29:03 +000012953 // If vector val is constant 0, replace extract with scalar 0.
Chris Lattner1f13c882006-03-31 18:25:14 +000012954 if (isa<ConstantAggregateZero>(EI.getOperand(0)))
Owen Andersona7235ea2009-07-31 20:28:14 +000012955 return ReplaceInstUsesWith(EI, Constant::getNullValue(EI.getType()));
Chris Lattner1f13c882006-03-31 18:25:14 +000012956
Reid Spencer9d6565a2007-02-15 02:26:10 +000012957 if (ConstantVector *C = dyn_cast<ConstantVector>(EI.getOperand(0))) {
Matthijs Kooijmanb4d6a5a2008-06-11 09:00:12 +000012958 // If vector val is constant with all elements the same, replace EI with
12959 // that element. When the elements are not identical, we cannot replace yet
12960 // (we do that below, but only when the index is constant).
Chris Lattner220b0cf2006-03-05 00:22:33 +000012961 Constant *op0 = C->getOperand(0);
Chris Lattner4cb81bd2009-09-08 03:44:51 +000012962 for (unsigned i = 1; i != C->getNumOperands(); ++i)
Chris Lattner220b0cf2006-03-05 00:22:33 +000012963 if (C->getOperand(i) != op0) {
12964 op0 = 0;
12965 break;
12966 }
12967 if (op0)
12968 return ReplaceInstUsesWith(EI, op0);
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012969 }
Eli Friedman76e7ba82009-07-18 19:04:16 +000012970
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012971 // If extracting a specified index from the vector, see if we can recursively
12972 // find a previously computed scalar that was inserted into the vector.
Reid Spencerb83eb642006-10-20 07:07:24 +000012973 if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
Chris Lattner85464092007-04-09 01:37:55 +000012974 unsigned IndexVal = IdxC->getZExtValue();
Chris Lattner4cb81bd2009-09-08 03:44:51 +000012975 unsigned VectorWidth = EI.getVectorOperandType()->getNumElements();
Chris Lattner85464092007-04-09 01:37:55 +000012976
12977 // If this is extracting an invalid index, turn this into undef, to avoid
12978 // crashing the code below.
12979 if (IndexVal >= VectorWidth)
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012980 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
Chris Lattner85464092007-04-09 01:37:55 +000012981
Chris Lattner867b99f2006-10-05 06:55:50 +000012982 // This instruction only demands the single element from the input vector.
12983 // If the input vector has a single use, simplify it based on this use
12984 // property.
Eli Friedman76e7ba82009-07-18 19:04:16 +000012985 if (EI.getOperand(0)->hasOneUse() && VectorWidth != 1) {
Evan Cheng388df622009-02-03 10:05:09 +000012986 APInt UndefElts(VectorWidth, 0);
12987 APInt DemandedMask(VectorWidth, 1 << IndexVal);
Chris Lattner867b99f2006-10-05 06:55:50 +000012988 if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
Evan Cheng388df622009-02-03 10:05:09 +000012989 DemandedMask, UndefElts)) {
Chris Lattner867b99f2006-10-05 06:55:50 +000012990 EI.setOperand(0, V);
12991 return &EI;
12992 }
12993 }
12994
Chris Lattner4de84762010-01-04 07:02:48 +000012995 if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal))
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012996 return ReplaceInstUsesWith(EI, Elt);
Chris Lattnerb7300fa2007-04-14 23:02:14 +000012997
12998 // If the this extractelement is directly using a bitcast from a vector of
12999 // the same number of elements, see if we can find the source element from
13000 // it. In this case, we will end up needing to bitcast the scalars.
13001 if (BitCastInst *BCI = dyn_cast<BitCastInst>(EI.getOperand(0))) {
13002 if (const VectorType *VT =
13003 dyn_cast<VectorType>(BCI->getOperand(0)->getType()))
13004 if (VT->getNumElements() == VectorWidth)
Chris Lattner4de84762010-01-04 07:02:48 +000013005 if (Value *Elt = FindScalarElement(BCI->getOperand(0), IndexVal))
Chris Lattnerb7300fa2007-04-14 23:02:14 +000013006 return new BitCastInst(Elt, EI.getType());
13007 }
Chris Lattner389a6f52006-04-10 23:06:36 +000013008 }
Chris Lattner6e6b0da2006-03-31 23:01:56 +000013009
Chris Lattner73fa49d2006-05-25 22:53:38 +000013010 if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
Chris Lattner275a6d62009-09-08 18:48:01 +000013011 // Push extractelement into predecessor operation if legal and
13012 // profitable to do so
13013 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
13014 if (I->hasOneUse() &&
13015 CheapToScalarize(BO, isa<ConstantInt>(EI.getOperand(1)))) {
13016 Value *newEI0 =
13017 Builder->CreateExtractElement(BO->getOperand(0), EI.getOperand(1),
13018 EI.getName()+".lhs");
13019 Value *newEI1 =
13020 Builder->CreateExtractElement(BO->getOperand(1), EI.getOperand(1),
13021 EI.getName()+".rhs");
13022 return BinaryOperator::Create(BO->getOpcode(), newEI0, newEI1);
Chris Lattner73fa49d2006-05-25 22:53:38 +000013023 }
Chris Lattner275a6d62009-09-08 18:48:01 +000013024 } else if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
Chris Lattner73fa49d2006-05-25 22:53:38 +000013025 // Extracting the inserted element?
13026 if (IE->getOperand(2) == EI.getOperand(1))
13027 return ReplaceInstUsesWith(EI, IE->getOperand(1));
13028 // If the inserted and extracted elements are constants, they must not
13029 // be the same value, extract from the pre-inserted value instead.
Chris Lattner08142f22009-08-30 19:47:22 +000013030 if (isa<Constant>(IE->getOperand(2)) && isa<Constant>(EI.getOperand(1))) {
Chris Lattner3c4e38e2009-08-30 06:27:41 +000013031 Worklist.AddValue(EI.getOperand(0));
Chris Lattner73fa49d2006-05-25 22:53:38 +000013032 EI.setOperand(0, IE->getOperand(0));
13033 return &EI;
13034 }
13035 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
13036 // If this is extracting an element from a shufflevector, figure out where
13037 // it came from and extract from the appropriate input element instead.
Reid Spencerb83eb642006-10-20 07:07:24 +000013038 if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
13039 unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
Chris Lattner863bcff2006-05-25 23:48:38 +000013040 Value *Src;
Mon P Wangaeb06d22008-11-10 04:46:22 +000013041 unsigned LHSWidth =
13042 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
13043
13044 if (SrcIdx < LHSWidth)
Chris Lattner863bcff2006-05-25 23:48:38 +000013045 Src = SVI->getOperand(0);
Mon P Wangaeb06d22008-11-10 04:46:22 +000013046 else if (SrcIdx < LHSWidth*2) {
13047 SrcIdx -= LHSWidth;
Chris Lattner863bcff2006-05-25 23:48:38 +000013048 Src = SVI->getOperand(1);
13049 } else {
Owen Anderson9e9a0d52009-07-30 23:03:37 +000013050 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
Chris Lattnerdf084ff2006-03-30 22:02:40 +000013051 }
Eric Christophera3500da2009-07-25 02:28:41 +000013052 return ExtractElementInst::Create(Src,
Chris Lattner4de84762010-01-04 07:02:48 +000013053 ConstantInt::get(Type::getInt32Ty(EI.getContext()),
13054 SrcIdx, false));
Robert Bocchino1d7456d2006-01-13 22:48:06 +000013055 }
13056 }
Eli Friedman2451a642009-07-18 23:06:53 +000013057 // FIXME: Canonicalize extractelement(bitcast) -> bitcast(extractelement)
Chris Lattner73fa49d2006-05-25 22:53:38 +000013058 }
Robert Bocchino1d7456d2006-01-13 22:48:06 +000013059 return 0;
13060}
13061
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000013062/// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
13063/// elements from either LHS or RHS, return the shuffle mask and true.
13064/// Otherwise, return false.
13065static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
Chris Lattner4de84762010-01-04 07:02:48 +000013066 std::vector<Constant*> &Mask) {
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000013067 assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
13068 "Invalid CollectSingleShuffleElements");
Reid Spencer9d6565a2007-02-15 02:26:10 +000013069 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000013070
13071 if (isa<UndefValue>(V)) {
Chris Lattner4de84762010-01-04 07:02:48 +000013072 Mask.assign(NumElts, UndefValue::get(Type::getInt32Ty(V->getContext())));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000013073 return true;
Chris Lattner4de84762010-01-04 07:02:48 +000013074 }
13075
13076 if (V == LHS) {
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000013077 for (unsigned i = 0; i != NumElts; ++i)
Chris Lattner4de84762010-01-04 07:02:48 +000013078 Mask.push_back(ConstantInt::get(Type::getInt32Ty(V->getContext()), i));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000013079 return true;
Chris Lattner4de84762010-01-04 07:02:48 +000013080 }
13081
13082 if (V == RHS) {
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000013083 for (unsigned i = 0; i != NumElts; ++i)
Chris Lattner4de84762010-01-04 07:02:48 +000013084 Mask.push_back(ConstantInt::get(Type::getInt32Ty(V->getContext()),
13085 i+NumElts));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000013086 return true;
Chris Lattner4de84762010-01-04 07:02:48 +000013087 }
13088
13089 if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000013090 // If this is an insert of an extract from some other vector, include it.
13091 Value *VecOp = IEI->getOperand(0);
13092 Value *ScalarOp = IEI->getOperand(1);
13093 Value *IdxOp = IEI->getOperand(2);
13094
Chris Lattnerd929f062006-04-27 21:14:21 +000013095 if (!isa<ConstantInt>(IdxOp))
13096 return false;
Reid Spencerb83eb642006-10-20 07:07:24 +000013097 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerd929f062006-04-27 21:14:21 +000013098
13099 if (isa<UndefValue>(ScalarOp)) { // inserting undef into vector.
13100 // Okay, we can handle this if the vector we are insertinting into is
13101 // transitively ok.
Chris Lattner4de84762010-01-04 07:02:48 +000013102 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
Chris Lattnerd929f062006-04-27 21:14:21 +000013103 // If so, update the mask to reflect the inserted undef.
Chris Lattner4de84762010-01-04 07:02:48 +000013104 Mask[InsertedIdx] = UndefValue::get(Type::getInt32Ty(V->getContext()));
Chris Lattnerd929f062006-04-27 21:14:21 +000013105 return true;
13106 }
13107 } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
13108 if (isa<ConstantInt>(EI->getOperand(1)) &&
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000013109 EI->getOperand(0)->getType() == V->getType()) {
13110 unsigned ExtractedIdx =
Reid Spencerb83eb642006-10-20 07:07:24 +000013111 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000013112
13113 // This must be extracting from either LHS or RHS.
13114 if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
13115 // Okay, we can handle this if the vector we are insertinting into is
13116 // transitively ok.
Chris Lattner4de84762010-01-04 07:02:48 +000013117 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000013118 // If so, update the mask to reflect the inserted value.
13119 if (EI->getOperand(0) == LHS) {
Mon P Wang4f5ca2c2008-08-20 02:23:25 +000013120 Mask[InsertedIdx % NumElts] =
Chris Lattner4de84762010-01-04 07:02:48 +000013121 ConstantInt::get(Type::getInt32Ty(V->getContext()),
13122 ExtractedIdx);
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000013123 } else {
13124 assert(EI->getOperand(0) == RHS);
Mon P Wang4f5ca2c2008-08-20 02:23:25 +000013125 Mask[InsertedIdx % NumElts] =
Chris Lattner4de84762010-01-04 07:02:48 +000013126 ConstantInt::get(Type::getInt32Ty(V->getContext()),
13127 ExtractedIdx+NumElts);
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000013128
13129 }
13130 return true;
13131 }
13132 }
13133 }
13134 }
13135 }
13136 // TODO: Handle shufflevector here!
13137
13138 return false;
13139}
13140
13141/// CollectShuffleElements - We are building a shuffle of V, using RHS as the
13142/// RHS of the shuffle instruction, if it is not null. Return a shuffle mask
13143/// that computes V and the LHS value of the shuffle.
Chris Lattnerefb47352006-04-15 01:39:45 +000013144static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
Chris Lattner4de84762010-01-04 07:02:48 +000013145 Value *&RHS) {
Reid Spencer9d6565a2007-02-15 02:26:10 +000013146 assert(isa<VectorType>(V->getType()) &&
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000013147 (RHS == 0 || V->getType() == RHS->getType()) &&
Chris Lattnerefb47352006-04-15 01:39:45 +000013148 "Invalid shuffle!");
Reid Spencer9d6565a2007-02-15 02:26:10 +000013149 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
Chris Lattnerefb47352006-04-15 01:39:45 +000013150
13151 if (isa<UndefValue>(V)) {
Chris Lattner4de84762010-01-04 07:02:48 +000013152 Mask.assign(NumElts, UndefValue::get(Type::getInt32Ty(V->getContext())));
Chris Lattnerefb47352006-04-15 01:39:45 +000013153 return V;
13154 } else if (isa<ConstantAggregateZero>(V)) {
Chris Lattner4de84762010-01-04 07:02:48 +000013155 Mask.assign(NumElts, ConstantInt::get(Type::getInt32Ty(V->getContext()),0));
Chris Lattnerefb47352006-04-15 01:39:45 +000013156 return V;
13157 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
13158 // If this is an insert of an extract from some other vector, include it.
13159 Value *VecOp = IEI->getOperand(0);
13160 Value *ScalarOp = IEI->getOperand(1);
13161 Value *IdxOp = IEI->getOperand(2);
13162
13163 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
13164 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
13165 EI->getOperand(0)->getType() == V->getType()) {
13166 unsigned ExtractedIdx =
Reid Spencerb83eb642006-10-20 07:07:24 +000013167 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
13168 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerefb47352006-04-15 01:39:45 +000013169
13170 // Either the extracted from or inserted into vector must be RHSVec,
13171 // otherwise we'd end up with a shuffle of three inputs.
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000013172 if (EI->getOperand(0) == RHS || RHS == 0) {
13173 RHS = EI->getOperand(0);
Chris Lattner4de84762010-01-04 07:02:48 +000013174 Value *V = CollectShuffleElements(VecOp, Mask, RHS);
Mon P Wang4f5ca2c2008-08-20 02:23:25 +000013175 Mask[InsertedIdx % NumElts] =
Chris Lattner4de84762010-01-04 07:02:48 +000013176 ConstantInt::get(Type::getInt32Ty(V->getContext()),
13177 NumElts+ExtractedIdx);
Chris Lattnerefb47352006-04-15 01:39:45 +000013178 return V;
13179 }
13180
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000013181 if (VecOp == RHS) {
Chris Lattner4de84762010-01-04 07:02:48 +000013182 Value *V = CollectShuffleElements(EI->getOperand(0), Mask, RHS);
Chris Lattnerefb47352006-04-15 01:39:45 +000013183 // Everything but the extracted element is replaced with the RHS.
13184 for (unsigned i = 0; i != NumElts; ++i) {
13185 if (i != InsertedIdx)
Chris Lattner4de84762010-01-04 07:02:48 +000013186 Mask[i] = ConstantInt::get(Type::getInt32Ty(V->getContext()),
13187 NumElts+i);
Chris Lattnerefb47352006-04-15 01:39:45 +000013188 }
13189 return V;
13190 }
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000013191
13192 // If this insertelement is a chain that comes from exactly these two
13193 // vectors, return the vector and the effective shuffle.
Chris Lattner4de84762010-01-04 07:02:48 +000013194 if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask))
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000013195 return EI->getOperand(0);
Chris Lattnerefb47352006-04-15 01:39:45 +000013196 }
13197 }
13198 }
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000013199 // TODO: Handle shufflevector here!
Chris Lattnerefb47352006-04-15 01:39:45 +000013200
13201 // Otherwise, can't do anything fancy. Return an identity vector.
13202 for (unsigned i = 0; i != NumElts; ++i)
Chris Lattner4de84762010-01-04 07:02:48 +000013203 Mask.push_back(ConstantInt::get(Type::getInt32Ty(V->getContext()), i));
Chris Lattnerefb47352006-04-15 01:39:45 +000013204 return V;
13205}
13206
13207Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
13208 Value *VecOp = IE.getOperand(0);
13209 Value *ScalarOp = IE.getOperand(1);
13210 Value *IdxOp = IE.getOperand(2);
13211
Chris Lattner599ded12007-04-09 01:11:16 +000013212 // Inserting an undef or into an undefined place, remove this.
13213 if (isa<UndefValue>(ScalarOp) || isa<UndefValue>(IdxOp))
13214 ReplaceInstUsesWith(IE, VecOp);
Eli Friedman76e7ba82009-07-18 19:04:16 +000013215
Chris Lattnerefb47352006-04-15 01:39:45 +000013216 // If the inserted element was extracted from some other vector, and if the
13217 // indexes are constant, try to turn this into a shufflevector operation.
13218 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
13219 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
13220 EI->getOperand(0)->getType() == IE.getType()) {
Eli Friedman76e7ba82009-07-18 19:04:16 +000013221 unsigned NumVectorElts = IE.getType()->getNumElements();
Chris Lattnere34e9a22007-04-14 23:32:02 +000013222 unsigned ExtractedIdx =
13223 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
Reid Spencerb83eb642006-10-20 07:07:24 +000013224 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerefb47352006-04-15 01:39:45 +000013225
13226 if (ExtractedIdx >= NumVectorElts) // Out of range extract.
13227 return ReplaceInstUsesWith(IE, VecOp);
13228
13229 if (InsertedIdx >= NumVectorElts) // Out of range insert.
Owen Anderson9e9a0d52009-07-30 23:03:37 +000013230 return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
Chris Lattnerefb47352006-04-15 01:39:45 +000013231
13232 // If we are extracting a value from a vector, then inserting it right
13233 // back into the same place, just use the input vector.
13234 if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
13235 return ReplaceInstUsesWith(IE, VecOp);
13236
Chris Lattnerefb47352006-04-15 01:39:45 +000013237 // If this insertelement isn't used by some other insertelement, turn it
13238 // (and any insertelements it points to), into one big shuffle.
13239 if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
13240 std::vector<Constant*> Mask;
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000013241 Value *RHS = 0;
Chris Lattner4de84762010-01-04 07:02:48 +000013242 Value *LHS = CollectShuffleElements(&IE, Mask, RHS);
Owen Anderson9e9a0d52009-07-30 23:03:37 +000013243 if (RHS == 0) RHS = UndefValue::get(LHS->getType());
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000013244 // We now have a shuffle of LHS, RHS, Mask.
Owen Andersond672ecb2009-07-03 00:17:18 +000013245 return new ShuffleVectorInst(LHS, RHS,
Owen Andersonaf7ec972009-07-28 21:19:26 +000013246 ConstantVector::get(Mask));
Chris Lattnerefb47352006-04-15 01:39:45 +000013247 }
13248 }
13249 }
13250
Eli Friedmanb9a4cac2009-06-06 20:08:03 +000013251 unsigned VWidth = cast<VectorType>(VecOp->getType())->getNumElements();
13252 APInt UndefElts(VWidth, 0);
13253 APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
13254 if (SimplifyDemandedVectorElts(&IE, AllOnesEltMask, UndefElts))
13255 return &IE;
13256
Chris Lattnerefb47352006-04-15 01:39:45 +000013257 return 0;
13258}
13259
13260
Chris Lattnera844fc4c2006-04-10 22:45:52 +000013261Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
13262 Value *LHS = SVI.getOperand(0);
13263 Value *RHS = SVI.getOperand(1);
Chris Lattner863bcff2006-05-25 23:48:38 +000013264 std::vector<unsigned> Mask = getShuffleMask(&SVI);
Chris Lattnera844fc4c2006-04-10 22:45:52 +000013265
13266 bool MadeChange = false;
Mon P Wangaeb06d22008-11-10 04:46:22 +000013267
Chris Lattner867b99f2006-10-05 06:55:50 +000013268 // Undefined shuffle mask -> undefined value.
Chris Lattner863bcff2006-05-25 23:48:38 +000013269 if (isa<UndefValue>(SVI.getOperand(2)))
Owen Anderson9e9a0d52009-07-30 23:03:37 +000013270 return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
Dan Gohman488fbfc2008-09-09 18:11:14 +000013271
Dan Gohman488fbfc2008-09-09 18:11:14 +000013272 unsigned VWidth = cast<VectorType>(SVI.getType())->getNumElements();
Mon P Wangaeb06d22008-11-10 04:46:22 +000013273
13274 if (VWidth != cast<VectorType>(LHS->getType())->getNumElements())
13275 return 0;
13276
Evan Cheng388df622009-02-03 10:05:09 +000013277 APInt UndefElts(VWidth, 0);
13278 APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
13279 if (SimplifyDemandedVectorElts(&SVI, AllOnesEltMask, UndefElts)) {
Dan Gohman3139ff82008-09-11 22:47:57 +000013280 LHS = SVI.getOperand(0);
13281 RHS = SVI.getOperand(1);
Dan Gohman488fbfc2008-09-09 18:11:14 +000013282 MadeChange = true;
Dan Gohman3139ff82008-09-11 22:47:57 +000013283 }
Chris Lattnerefb47352006-04-15 01:39:45 +000013284
Chris Lattner863bcff2006-05-25 23:48:38 +000013285 // Canonicalize shuffle(x ,x,mask) -> shuffle(x, undef,mask')
13286 // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
13287 if (LHS == RHS || isa<UndefValue>(LHS)) {
13288 if (isa<UndefValue>(LHS) && LHS == RHS) {
Chris Lattnera844fc4c2006-04-10 22:45:52 +000013289 // shuffle(undef,undef,mask) -> undef.
13290 return ReplaceInstUsesWith(SVI, LHS);
13291 }
13292
Chris Lattner863bcff2006-05-25 23:48:38 +000013293 // Remap any references to RHS to use LHS.
13294 std::vector<Constant*> Elts;
13295 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
Chris Lattner7b2e27922006-05-26 00:29:06 +000013296 if (Mask[i] >= 2*e)
Chris Lattner4de84762010-01-04 07:02:48 +000013297 Elts.push_back(UndefValue::get(Type::getInt32Ty(SVI.getContext())));
Chris Lattner7b2e27922006-05-26 00:29:06 +000013298 else {
13299 if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
Dan Gohman4ce96272008-08-06 18:17:32 +000013300 (Mask[i] < e && isa<UndefValue>(LHS))) {
Chris Lattner7b2e27922006-05-26 00:29:06 +000013301 Mask[i] = 2*e; // Turn into undef.
Chris Lattner4de84762010-01-04 07:02:48 +000013302 Elts.push_back(UndefValue::get(Type::getInt32Ty(SVI.getContext())));
Dan Gohman4ce96272008-08-06 18:17:32 +000013303 } else {
Mon P Wang4f5ca2c2008-08-20 02:23:25 +000013304 Mask[i] = Mask[i] % e; // Force to LHS.
Chris Lattner4de84762010-01-04 07:02:48 +000013305 Elts.push_back(ConstantInt::get(Type::getInt32Ty(SVI.getContext()),
13306 Mask[i]));
Dan Gohman4ce96272008-08-06 18:17:32 +000013307 }
Chris Lattner7b2e27922006-05-26 00:29:06 +000013308 }
Chris Lattnera844fc4c2006-04-10 22:45:52 +000013309 }
Chris Lattner863bcff2006-05-25 23:48:38 +000013310 SVI.setOperand(0, SVI.getOperand(1));
Owen Anderson9e9a0d52009-07-30 23:03:37 +000013311 SVI.setOperand(1, UndefValue::get(RHS->getType()));
Owen Andersonaf7ec972009-07-28 21:19:26 +000013312 SVI.setOperand(2, ConstantVector::get(Elts));
Chris Lattner7b2e27922006-05-26 00:29:06 +000013313 LHS = SVI.getOperand(0);
13314 RHS = SVI.getOperand(1);
Chris Lattnera844fc4c2006-04-10 22:45:52 +000013315 MadeChange = true;
13316 }
13317
Chris Lattner7b2e27922006-05-26 00:29:06 +000013318 // Analyze the shuffle, are the LHS or RHS and identity shuffles?
Chris Lattner863bcff2006-05-25 23:48:38 +000013319 bool isLHSID = true, isRHSID = true;
Chris Lattner706126d2006-04-16 00:03:56 +000013320
Chris Lattner863bcff2006-05-25 23:48:38 +000013321 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
13322 if (Mask[i] >= e*2) continue; // Ignore undef values.
13323 // Is this an identity shuffle of the LHS value?
13324 isLHSID &= (Mask[i] == i);
13325
13326 // Is this an identity shuffle of the RHS value?
13327 isRHSID &= (Mask[i]-e == i);
Chris Lattner706126d2006-04-16 00:03:56 +000013328 }
Chris Lattnera844fc4c2006-04-10 22:45:52 +000013329
Chris Lattner863bcff2006-05-25 23:48:38 +000013330 // Eliminate identity shuffles.
13331 if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
13332 if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
Chris Lattnera844fc4c2006-04-10 22:45:52 +000013333
Chris Lattner7b2e27922006-05-26 00:29:06 +000013334 // If the LHS is a shufflevector itself, see if we can combine it with this
13335 // one without producing an unusual shuffle. Here we are really conservative:
13336 // we are absolutely afraid of producing a shuffle mask not in the input
13337 // program, because the code gen may not be smart enough to turn a merged
13338 // shuffle into two specific shuffles: it may produce worse code. As such,
13339 // we only merge two shuffles if the result is one of the two input shuffle
13340 // masks. In this case, merging the shuffles just removes one instruction,
13341 // which we know is safe. This is good for things like turning:
13342 // (splat(splat)) -> splat.
13343 if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
13344 if (isa<UndefValue>(RHS)) {
13345 std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
13346
David Greenef941d292009-11-16 21:52:23 +000013347 if (LHSMask.size() == Mask.size()) {
13348 std::vector<unsigned> NewMask;
13349 for (unsigned i = 0, e = Mask.size(); i != e; ++i)
Duncan Sands76700ba2009-11-20 13:19:51 +000013350 if (Mask[i] >= e)
David Greenef941d292009-11-16 21:52:23 +000013351 NewMask.push_back(2*e);
13352 else
13353 NewMask.push_back(LHSMask[Mask[i]]);
Chris Lattner7b2e27922006-05-26 00:29:06 +000013354
David Greenef941d292009-11-16 21:52:23 +000013355 // If the result mask is equal to the src shuffle or this
13356 // shuffle mask, do the replacement.
13357 if (NewMask == LHSMask || NewMask == Mask) {
13358 unsigned LHSInNElts =
13359 cast<VectorType>(LHSSVI->getOperand(0)->getType())->
13360 getNumElements();
13361 std::vector<Constant*> Elts;
13362 for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
13363 if (NewMask[i] >= LHSInNElts*2) {
Chris Lattner4de84762010-01-04 07:02:48 +000013364 Elts.push_back(UndefValue::get(
13365 Type::getInt32Ty(SVI.getContext())));
David Greenef941d292009-11-16 21:52:23 +000013366 } else {
Chris Lattner4de84762010-01-04 07:02:48 +000013367 Elts.push_back(ConstantInt::get(
13368 Type::getInt32Ty(SVI.getContext()),
David Greenef941d292009-11-16 21:52:23 +000013369 NewMask[i]));
13370 }
Chris Lattner7b2e27922006-05-26 00:29:06 +000013371 }
David Greenef941d292009-11-16 21:52:23 +000013372 return new ShuffleVectorInst(LHSSVI->getOperand(0),
13373 LHSSVI->getOperand(1),
13374 ConstantVector::get(Elts));
Chris Lattner7b2e27922006-05-26 00:29:06 +000013375 }
Chris Lattner7b2e27922006-05-26 00:29:06 +000013376 }
13377 }
13378 }
Chris Lattnerc5eff442007-01-30 22:32:46 +000013379
Chris Lattnera844fc4c2006-04-10 22:45:52 +000013380 return MadeChange ? &SVI : 0;
13381}
13382
13383
Robert Bocchino1d7456d2006-01-13 22:48:06 +000013384
Chris Lattnerea1c4542004-12-08 23:43:58 +000013385
13386/// TryToSinkInstruction - Try to move the specified instruction from its
13387/// current block into the beginning of DestBlock, which can only happen if it's
13388/// safe to move the instruction past all of the instructions between it and the
13389/// end of its block.
13390static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
13391 assert(I->hasOneUse() && "Invariants didn't hold!");
13392
Chris Lattner108e9022005-10-27 17:13:11 +000013393 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
Duncan Sands7af1c782009-05-06 06:49:50 +000013394 if (isa<PHINode>(I) || I->mayHaveSideEffects() || isa<TerminatorInst>(I))
Chris Lattnerbfc538c2008-05-09 15:07:33 +000013395 return false;
Misha Brukmanfd939082005-04-21 23:48:37 +000013396
Chris Lattnerea1c4542004-12-08 23:43:58 +000013397 // Do not sink alloca instructions out of the entry block.
Dan Gohmanecb7a772007-03-22 16:38:57 +000013398 if (isa<AllocaInst>(I) && I->getParent() ==
13399 &DestBlock->getParent()->getEntryBlock())
Chris Lattnerea1c4542004-12-08 23:43:58 +000013400 return false;
13401
Chris Lattner96a52a62004-12-09 07:14:34 +000013402 // We can only sink load instructions if there is nothing between the load and
13403 // the end of block that could change the value.
Chris Lattner2539e332008-05-08 17:37:37 +000013404 if (I->mayReadFromMemory()) {
13405 for (BasicBlock::iterator Scan = I, E = I->getParent()->end();
Chris Lattner96a52a62004-12-09 07:14:34 +000013406 Scan != E; ++Scan)
13407 if (Scan->mayWriteToMemory())
13408 return false;
Chris Lattner96a52a62004-12-09 07:14:34 +000013409 }
Chris Lattnerea1c4542004-12-08 23:43:58 +000013410
Dan Gohman02dea8b2008-05-23 21:05:58 +000013411 BasicBlock::iterator InsertPos = DestBlock->getFirstNonPHI();
Chris Lattnerea1c4542004-12-08 23:43:58 +000013412
Dale Johannesenbd8e6502009-03-03 01:09:07 +000013413 CopyPrecedingStopPoint(I, InsertPos);
Chris Lattner4bc5f802005-08-08 19:11:57 +000013414 I->moveBefore(InsertPos);
Chris Lattnerea1c4542004-12-08 23:43:58 +000013415 ++NumSunkInst;
13416 return true;
13417}
13418
Chris Lattnerf4f5a772006-05-10 19:00:36 +000013419
13420/// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
13421/// all reachable code to the worklist.
13422///
13423/// This has a couple of tricks to make the code faster and more powerful. In
13424/// particular, we constant fold and DCE instructions as we go, to avoid adding
13425/// them to the worklist (this significantly speeds up instcombine on code where
13426/// many instructions are dead or constant). Additionally, if we find a branch
13427/// whose condition is a known constant, we only visit the reachable successors.
13428///
Chris Lattner2ee743b2009-10-15 04:59:28 +000013429static bool AddReachableCodeToWorklist(BasicBlock *BB,
Chris Lattner1f87a582007-02-15 19:41:52 +000013430 SmallPtrSet<BasicBlock*, 64> &Visited,
Chris Lattnerdbab3862007-03-02 21:28:56 +000013431 InstCombiner &IC,
Chris Lattner8c8c66a2006-05-11 17:11:52 +000013432 const TargetData *TD) {
Chris Lattner2ee743b2009-10-15 04:59:28 +000013433 bool MadeIRChange = false;
Chris Lattner2806dff2008-08-15 04:03:01 +000013434 SmallVector<BasicBlock*, 256> Worklist;
Chris Lattner2c7718a2007-03-23 19:17:18 +000013435 Worklist.push_back(BB);
Chris Lattner67f7d542009-10-12 03:58:40 +000013436
13437 std::vector<Instruction*> InstrsForInstCombineWorklist;
13438 InstrsForInstCombineWorklist.reserve(128);
Chris Lattnerf4f5a772006-05-10 19:00:36 +000013439
Chris Lattner2ee743b2009-10-15 04:59:28 +000013440 SmallPtrSet<ConstantExpr*, 64> FoldedConstants;
13441
Chris Lattner2c7718a2007-03-23 19:17:18 +000013442 while (!Worklist.empty()) {
13443 BB = Worklist.back();
13444 Worklist.pop_back();
13445
13446 // We have now visited this block! If we've already been here, ignore it.
13447 if (!Visited.insert(BB)) continue;
Devang Patel7fe1dec2008-11-19 18:56:50 +000013448
Chris Lattner2c7718a2007-03-23 19:17:18 +000013449 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
13450 Instruction *Inst = BBI++;
Chris Lattnerf4f5a772006-05-10 19:00:36 +000013451
Chris Lattner2c7718a2007-03-23 19:17:18 +000013452 // DCE instruction if trivially dead.
13453 if (isInstructionTriviallyDead(Inst)) {
13454 ++NumDeadInst;
Chris Lattnerbdff5482009-08-23 04:37:46 +000013455 DEBUG(errs() << "IC: DCE: " << *Inst << '\n');
Chris Lattner2c7718a2007-03-23 19:17:18 +000013456 Inst->eraseFromParent();
13457 continue;
13458 }
13459
13460 // ConstantProp instruction if trivially constant.
Chris Lattnere2cc1ad2009-10-15 04:13:44 +000013461 if (!Inst->use_empty() && isa<Constant>(Inst->getOperand(0)))
Chris Lattner7b550cc2009-11-06 04:27:31 +000013462 if (Constant *C = ConstantFoldInstruction(Inst, TD)) {
Chris Lattnere2cc1ad2009-10-15 04:13:44 +000013463 DEBUG(errs() << "IC: ConstFold to: " << *C << " from: "
13464 << *Inst << '\n');
13465 Inst->replaceAllUsesWith(C);
13466 ++NumConstProp;
13467 Inst->eraseFromParent();
13468 continue;
13469 }
Chris Lattner2ee743b2009-10-15 04:59:28 +000013470
13471
13472
13473 if (TD) {
13474 // See if we can constant fold its operands.
13475 for (User::op_iterator i = Inst->op_begin(), e = Inst->op_end();
13476 i != e; ++i) {
13477 ConstantExpr *CE = dyn_cast<ConstantExpr>(i);
13478 if (CE == 0) continue;
13479
13480 // If we already folded this constant, don't try again.
13481 if (!FoldedConstants.insert(CE))
13482 continue;
13483
Chris Lattner7b550cc2009-11-06 04:27:31 +000013484 Constant *NewC = ConstantFoldConstantExpression(CE, TD);
Chris Lattner2ee743b2009-10-15 04:59:28 +000013485 if (NewC && NewC != CE) {
13486 *i = NewC;
13487 MadeIRChange = true;
13488 }
13489 }
13490 }
13491
Devang Patel7fe1dec2008-11-19 18:56:50 +000013492
Chris Lattner67f7d542009-10-12 03:58:40 +000013493 InstrsForInstCombineWorklist.push_back(Inst);
Chris Lattnerf4f5a772006-05-10 19:00:36 +000013494 }
Chris Lattner2c7718a2007-03-23 19:17:18 +000013495
13496 // Recursively visit successors. If this is a branch or switch on a
13497 // constant, only visit the reachable successor.
13498 TerminatorInst *TI = BB->getTerminator();
13499 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
13500 if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
13501 bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
Nick Lewycky91436992008-03-09 08:50:23 +000013502 BasicBlock *ReachableBB = BI->getSuccessor(!CondVal);
Nick Lewycky280a6e62008-04-25 16:53:59 +000013503 Worklist.push_back(ReachableBB);
Chris Lattner2c7718a2007-03-23 19:17:18 +000013504 continue;
13505 }
13506 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
13507 if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
13508 // See if this is an explicit destination.
13509 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
13510 if (SI->getCaseValue(i) == Cond) {
Nick Lewycky91436992008-03-09 08:50:23 +000013511 BasicBlock *ReachableBB = SI->getSuccessor(i);
Nick Lewycky280a6e62008-04-25 16:53:59 +000013512 Worklist.push_back(ReachableBB);
Chris Lattner2c7718a2007-03-23 19:17:18 +000013513 continue;
13514 }
13515
13516 // Otherwise it is the default destination.
13517 Worklist.push_back(SI->getSuccessor(0));
13518 continue;
13519 }
13520 }
13521
13522 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
13523 Worklist.push_back(TI->getSuccessor(i));
Chris Lattnerf4f5a772006-05-10 19:00:36 +000013524 }
Chris Lattner67f7d542009-10-12 03:58:40 +000013525
13526 // Once we've found all of the instructions to add to instcombine's worklist,
13527 // add them in reverse order. This way instcombine will visit from the top
13528 // of the function down. This jives well with the way that it adds all uses
13529 // of instructions to the worklist after doing a transformation, thus avoiding
13530 // some N^2 behavior in pathological cases.
13531 IC.Worklist.AddInitialGroup(&InstrsForInstCombineWorklist[0],
13532 InstrsForInstCombineWorklist.size());
Chris Lattner2ee743b2009-10-15 04:59:28 +000013533
13534 return MadeIRChange;
Chris Lattnerf4f5a772006-05-10 19:00:36 +000013535}
13536
Chris Lattnerec9c3582007-03-03 02:04:50 +000013537bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) {
Chris Lattnerb0b822c2009-08-31 06:57:37 +000013538 MadeIRChange = false;
Chris Lattnerec9c3582007-03-03 02:04:50 +000013539
Daniel Dunbarce63ffb2009-07-25 00:23:56 +000013540 DEBUG(errs() << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
13541 << F.getNameStr() << "\n");
Chris Lattner8a2a3112001-12-14 16:52:21 +000013542
Chris Lattnerb3d59702005-07-07 20:40:38 +000013543 {
Chris Lattnerf4f5a772006-05-10 19:00:36 +000013544 // Do a depth-first traversal of the function, populate the worklist with
13545 // the reachable instructions. Ignore blocks that are not reachable. Keep
13546 // track of which blocks we visit.
Chris Lattner1f87a582007-02-15 19:41:52 +000013547 SmallPtrSet<BasicBlock*, 64> Visited;
Chris Lattner2ee743b2009-10-15 04:59:28 +000013548 MadeIRChange |= AddReachableCodeToWorklist(F.begin(), Visited, *this, TD);
Jeff Cohen00b168892005-07-27 06:12:32 +000013549
Chris Lattnerb3d59702005-07-07 20:40:38 +000013550 // Do a quick scan over the function. If we find any blocks that are
13551 // unreachable, remove any instructions inside of them. This prevents
13552 // the instcombine code from having to deal with some bad special cases.
13553 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
13554 if (!Visited.count(BB)) {
13555 Instruction *Term = BB->getTerminator();
13556 while (Term != BB->begin()) { // Remove instrs bottom-up
13557 BasicBlock::iterator I = Term; --I;
Chris Lattner6ffe5512004-04-27 15:13:33 +000013558
Chris Lattnerbdff5482009-08-23 04:37:46 +000013559 DEBUG(errs() << "IC: DCE: " << *I << '\n');
Dale Johannesenff278b12009-03-10 21:19:49 +000013560 // A debug intrinsic shouldn't force another iteration if we weren't
13561 // going to do one without it.
13562 if (!isa<DbgInfoIntrinsic>(I)) {
13563 ++NumDeadInst;
Chris Lattnerb0b822c2009-08-31 06:57:37 +000013564 MadeIRChange = true;
Dale Johannesenff278b12009-03-10 21:19:49 +000013565 }
Devang Patel228ebd02009-10-13 22:56:32 +000013566
Devang Patel228ebd02009-10-13 22:56:32 +000013567 // If I is not void type then replaceAllUsesWith undef.
13568 // This allows ValueHandlers and custom metadata to adjust itself.
Devang Patel9674d152009-10-14 17:29:00 +000013569 if (!I->getType()->isVoidTy())
Devang Patel228ebd02009-10-13 22:56:32 +000013570 I->replaceAllUsesWith(UndefValue::get(I->getType()));
Chris Lattnerb3d59702005-07-07 20:40:38 +000013571 I->eraseFromParent();
13572 }
13573 }
13574 }
Chris Lattner8a2a3112001-12-14 16:52:21 +000013575
Chris Lattner873ff012009-08-30 05:55:36 +000013576 while (!Worklist.isEmpty()) {
13577 Instruction *I = Worklist.RemoveOne();
Chris Lattnerdbab3862007-03-02 21:28:56 +000013578 if (I == 0) continue; // skip null values.
Chris Lattner8a2a3112001-12-14 16:52:21 +000013579
Chris Lattner8c8c66a2006-05-11 17:11:52 +000013580 // Check to see if we can DCE the instruction.
Chris Lattner62b14df2002-09-02 04:59:56 +000013581 if (isInstructionTriviallyDead(I)) {
Chris Lattnerbdff5482009-08-23 04:37:46 +000013582 DEBUG(errs() << "IC: DCE: " << *I << '\n');
Chris Lattner7a1e9242009-08-30 06:13:40 +000013583 EraseInstFromFunction(*I);
13584 ++NumDeadInst;
Chris Lattnerb0b822c2009-08-31 06:57:37 +000013585 MadeIRChange = true;
Chris Lattner4bb7c022003-10-06 17:11:01 +000013586 continue;
13587 }
Chris Lattner62b14df2002-09-02 04:59:56 +000013588
Chris Lattner8c8c66a2006-05-11 17:11:52 +000013589 // Instruction isn't dead, see if we can constant propagate it.
Chris Lattnere2cc1ad2009-10-15 04:13:44 +000013590 if (!I->use_empty() && isa<Constant>(I->getOperand(0)))
Chris Lattner7b550cc2009-11-06 04:27:31 +000013591 if (Constant *C = ConstantFoldInstruction(I, TD)) {
Chris Lattnere2cc1ad2009-10-15 04:13:44 +000013592 DEBUG(errs() << "IC: ConstFold to: " << *C << " from: " << *I << '\n');
Chris Lattnerad5fec12005-01-28 19:32:01 +000013593
Chris Lattnere2cc1ad2009-10-15 04:13:44 +000013594 // Add operands to the worklist.
13595 ReplaceInstUsesWith(*I, C);
13596 ++NumConstProp;
13597 EraseInstFromFunction(*I);
13598 MadeIRChange = true;
13599 continue;
13600 }
Chris Lattner4bb7c022003-10-06 17:11:01 +000013601
Chris Lattnerea1c4542004-12-08 23:43:58 +000013602 // See if we can trivially sink this instruction to a successor basic block.
Dan Gohmanfc74abf2008-07-23 00:34:11 +000013603 if (I->hasOneUse()) {
Chris Lattnerea1c4542004-12-08 23:43:58 +000013604 BasicBlock *BB = I->getParent();
Chris Lattner8db2cd12009-10-14 15:21:58 +000013605 Instruction *UserInst = cast<Instruction>(I->use_back());
13606 BasicBlock *UserParent;
13607
13608 // Get the block the use occurs in.
13609 if (PHINode *PN = dyn_cast<PHINode>(UserInst))
13610 UserParent = PN->getIncomingBlock(I->use_begin().getUse());
13611 else
13612 UserParent = UserInst->getParent();
13613
Chris Lattnerea1c4542004-12-08 23:43:58 +000013614 if (UserParent != BB) {
13615 bool UserIsSuccessor = false;
13616 // See if the user is one of our successors.
13617 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
13618 if (*SI == UserParent) {
13619 UserIsSuccessor = true;
13620 break;
13621 }
13622
13623 // If the user is one of our immediate successors, and if that successor
13624 // only has us as a predecessors (we'd have to split the critical edge
13625 // otherwise), we can keep going.
Chris Lattner8db2cd12009-10-14 15:21:58 +000013626 if (UserIsSuccessor && UserParent->getSinglePredecessor())
Chris Lattnerea1c4542004-12-08 23:43:58 +000013627 // Okay, the CFG is simple enough, try to sink this instruction.
Chris Lattnerb0b822c2009-08-31 06:57:37 +000013628 MadeIRChange |= TryToSinkInstruction(I, UserParent);
Chris Lattnerea1c4542004-12-08 23:43:58 +000013629 }
13630 }
13631
Chris Lattner74381062009-08-30 07:44:24 +000013632 // Now that we have an instruction, try combining it to simplify it.
13633 Builder->SetInsertPoint(I->getParent(), I);
13634
Reid Spencera9b81012007-03-26 17:44:01 +000013635#ifndef NDEBUG
13636 std::string OrigI;
13637#endif
Chris Lattnerbdff5482009-08-23 04:37:46 +000013638 DEBUG(raw_string_ostream SS(OrigI); I->print(SS); OrigI = SS.str(););
Jeffrey Yasskin43069632009-10-08 00:12:24 +000013639 DEBUG(errs() << "IC: Visiting: " << OrigI << '\n');
13640
Chris Lattner90ac28c2002-08-02 19:29:35 +000013641 if (Instruction *Result = visit(*I)) {
Chris Lattner3dec1f22002-05-10 15:38:35 +000013642 ++NumCombined;
Chris Lattnerdd841ae2002-04-18 17:39:14 +000013643 // Should we replace the old instruction with a new one?
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +000013644 if (Result != I) {
Chris Lattnerbdff5482009-08-23 04:37:46 +000013645 DEBUG(errs() << "IC: Old = " << *I << '\n'
13646 << " New = " << *Result << '\n');
Chris Lattner0cea42a2004-03-13 23:54:27 +000013647
Chris Lattnerf523d062004-06-09 05:08:07 +000013648 // Everything uses the new instruction now.
13649 I->replaceAllUsesWith(Result);
13650
13651 // Push the new instruction and any users onto the worklist.
Chris Lattner7a1e9242009-08-30 06:13:40 +000013652 Worklist.Add(Result);
Chris Lattnere5ecdb52009-08-30 06:22:51 +000013653 Worklist.AddUsersToWorkList(*Result);
Chris Lattner4bb7c022003-10-06 17:11:01 +000013654
Chris Lattner6934a042007-02-11 01:23:03 +000013655 // Move the name to the new instruction first.
13656 Result->takeName(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +000013657
13658 // Insert the new instruction into the basic block...
13659 BasicBlock *InstParent = I->getParent();
Chris Lattnerbac32862004-11-14 19:13:23 +000013660 BasicBlock::iterator InsertPos = I;
13661
13662 if (!isa<PHINode>(Result)) // If combining a PHI, don't insert
13663 while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
13664 ++InsertPos;
13665
13666 InstParent->getInstList().insert(InsertPos, Result);
Chris Lattner4bb7c022003-10-06 17:11:01 +000013667
Chris Lattner7a1e9242009-08-30 06:13:40 +000013668 EraseInstFromFunction(*I);
Chris Lattner7e708292002-06-25 16:13:24 +000013669 } else {
Evan Chengc7baf682007-03-27 16:44:48 +000013670#ifndef NDEBUG
Chris Lattnerbdff5482009-08-23 04:37:46 +000013671 DEBUG(errs() << "IC: Mod = " << OrigI << '\n'
13672 << " New = " << *I << '\n');
Evan Chengc7baf682007-03-27 16:44:48 +000013673#endif
Chris Lattner0cea42a2004-03-13 23:54:27 +000013674
Chris Lattner90ac28c2002-08-02 19:29:35 +000013675 // If the instruction was modified, it's possible that it is now dead.
13676 // if so, remove it.
Chris Lattner00d51312004-05-01 23:27:23 +000013677 if (isInstructionTriviallyDead(I)) {
Chris Lattner7a1e9242009-08-30 06:13:40 +000013678 EraseInstFromFunction(*I);
Chris Lattnerf523d062004-06-09 05:08:07 +000013679 } else {
Chris Lattner7a1e9242009-08-30 06:13:40 +000013680 Worklist.Add(I);
Chris Lattnere5ecdb52009-08-30 06:22:51 +000013681 Worklist.AddUsersToWorkList(*I);
Chris Lattner90ac28c2002-08-02 19:29:35 +000013682 }
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +000013683 }
Chris Lattnerb0b822c2009-08-31 06:57:37 +000013684 MadeIRChange = true;
Chris Lattner8a2a3112001-12-14 16:52:21 +000013685 }
13686 }
13687
Chris Lattner873ff012009-08-30 05:55:36 +000013688 Worklist.Zap();
Chris Lattnerb0b822c2009-08-31 06:57:37 +000013689 return MadeIRChange;
Chris Lattnerbd0ef772002-02-26 21:46:54 +000013690}
13691
Chris Lattnerec9c3582007-03-03 02:04:50 +000013692
13693bool InstCombiner::runOnFunction(Function &F) {
Chris Lattnerf964f322007-03-04 04:27:24 +000013694 MustPreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
Chris Lattnere2cc1ad2009-10-15 04:13:44 +000013695 TD = getAnalysisIfAvailable<TargetData>();
13696
Chris Lattner74381062009-08-30 07:44:24 +000013697
13698 /// Builder - This is an IRBuilder that automatically inserts new
13699 /// instructions into the worklist when they are created.
Chris Lattnere2cc1ad2009-10-15 04:13:44 +000013700 IRBuilder<true, TargetFolder, InstCombineIRInserter>
Chris Lattnerf55eeb92009-11-06 05:59:53 +000013701 TheBuilder(F.getContext(), TargetFolder(TD),
Chris Lattner74381062009-08-30 07:44:24 +000013702 InstCombineIRInserter(Worklist));
13703 Builder = &TheBuilder;
13704
Chris Lattnerec9c3582007-03-03 02:04:50 +000013705 bool EverMadeChange = false;
13706
13707 // Iterate while there is work to do.
13708 unsigned Iteration = 0;
Bill Wendlinga6c31122008-05-14 22:45:20 +000013709 while (DoOneIteration(F, Iteration++))
Chris Lattnerec9c3582007-03-03 02:04:50 +000013710 EverMadeChange = true;
Chris Lattner74381062009-08-30 07:44:24 +000013711
13712 Builder = 0;
Chris Lattnerec9c3582007-03-03 02:04:50 +000013713 return EverMadeChange;
13714}
13715
Brian Gaeke96d4bf72004-07-27 17:43:21 +000013716FunctionPass *llvm::createInstructionCombiningPass() {
Chris Lattnerdd841ae2002-04-18 17:39:14 +000013717 return new InstCombiner();
Chris Lattnerbd0ef772002-02-26 21:46:54 +000013718}