blob: a0bd43ab701e01376588ef0f104be276f8d03a08 [file] [log] [blame]
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001//===- InstructionCombining.cpp - Combine multiple instructions -----------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner081ce942007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007//
8//===----------------------------------------------------------------------===//
9//
10// InstructionCombining - Combine instructions to form fewer, simple
Dan Gohman089efff2008-05-13 00:00:25 +000011// instructions. This pass does not modify the CFG. This pass is where
12// algebraic simplification happens.
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013//
14// This pass combines things like:
15// %Y = add i32 %X, 1
16// %Z = add i32 %Y, 1
17// into:
18// %Z = add i32 %X, 2
19//
20// This is a simple worklist driven algorithm.
21//
22// This pass guarantees that the following canonicalizations are performed on
23// the program:
24// 1. If a binary operator has a constant operand, it is moved to the RHS
25// 2. Bitwise operators with constant operands are always grouped so that
26// shifts are performed first, then or's, then and's, then xor's.
27// 3. Compare instructions are converted from <,>,<=,>= to ==,!= if possible
28// 4. All cmp instructions on boolean values are replaced with logical ops
29// 5. add X, X is represented as (X*2) => (X << 1)
30// 6. Multiplies with a power-of-two constant argument are transformed into
31// shifts.
32// ... etc.
33//
34//===----------------------------------------------------------------------===//
35
36#define DEBUG_TYPE "instcombine"
37#include "llvm/Transforms/Scalar.h"
Chris Lattner530dd162010-01-04 07:12:23 +000038#include "InstCombine.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000039#include "llvm/IntrinsicInst.h"
Owen Anderson24be4c12009-07-03 00:17:18 +000040#include "llvm/LLVMContext.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000041#include "llvm/DerivedTypes.h"
42#include "llvm/GlobalVariable.h"
Dan Gohman9545fb02009-07-17 20:47:02 +000043#include "llvm/Operator.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000044#include "llvm/Analysis/ConstantFolding.h"
Chris Lattnera9333562009-11-09 23:28:39 +000045#include "llvm/Analysis/InstructionSimplify.h"
Victor Hernandez28f4d2f2009-10-27 20:05:49 +000046#include "llvm/Analysis/MemoryBuiltins.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000047#include "llvm/Target/TargetData.h"
48#include "llvm/Transforms/Utils/BasicBlockUtils.h"
49#include "llvm/Transforms/Utils/Local.h"
50#include "llvm/Support/CallSite.h"
51#include "llvm/Support/Debug.h"
Edwin Törökced9ff82009-07-11 13:10:19 +000052#include "llvm/Support/ErrorHandling.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000053#include "llvm/Support/GetElementPtrTypeIterator.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000054#include "llvm/Support/MathExtras.h"
55#include "llvm/Support/PatternMatch.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000056#include "llvm/ADT/SmallPtrSet.h"
57#include "llvm/ADT/Statistic.h"
58#include "llvm/ADT/STLExtras.h"
59#include <algorithm>
Edwin Töröka0e6fce2008-04-20 08:33:11 +000060#include <climits>
Dan Gohmanf17a25c2007-07-18 16:29:46 +000061using namespace llvm;
62using namespace llvm::PatternMatch;
63
64STATISTIC(NumCombined , "Number of insts combined");
65STATISTIC(NumConstProp, "Number of constant folds");
66STATISTIC(NumDeadInst , "Number of dead inst eliminated");
67STATISTIC(NumDeadStore, "Number of dead stores eliminated");
68STATISTIC(NumSunkInst , "Number of instructions sunk");
69
Dan Gohmanf17a25c2007-07-18 16:29:46 +000070
Dan Gohman089efff2008-05-13 00:00:25 +000071char InstCombiner::ID = 0;
72static RegisterPass<InstCombiner>
73X("instcombine", "Combine redundant instructions");
74
Chris Lattnerc1cea3f2010-01-04 07:17:19 +000075void InstCombiner::getAnalysisUsage(AnalysisUsage &AU) const {
76 AU.addPreservedID(LCSSAID);
77 AU.setPreservesCFG();
78}
79
80
Dan Gohmanf17a25c2007-07-18 16:29:46 +000081// isOnlyUse - Return true if this instruction will be deleted if we stop using
82// it.
83static bool isOnlyUse(Value *V) {
84 return V->hasOneUse() || isa<Constant>(V);
85}
86
87// getPromotedType - Return the specified type promoted as it would be to pass
88// though a va_arg area...
89static const Type *getPromotedType(const Type *Ty) {
90 if (const IntegerType* ITy = dyn_cast<IntegerType>(Ty)) {
91 if (ITy->getBitWidth() < 32)
Owen Anderson35b47072009-08-13 21:58:54 +000092 return Type::getInt32Ty(Ty->getContext());
Dan Gohmanf17a25c2007-07-18 16:29:46 +000093 }
94 return Ty;
95}
96
Chris Lattnerd0011092009-11-10 07:23:37 +000097/// ShouldChangeType - Return true if it is desirable to convert a computation
98/// from 'From' to 'To'. We don't want to convert from a legal to an illegal
99/// type for example, or from a smaller to a larger illegal type.
100static bool ShouldChangeType(const Type *From, const Type *To,
101 const TargetData *TD) {
102 assert(isa<IntegerType>(From) && isa<IntegerType>(To));
103
104 // If we don't have TD, we don't know if the source/dest are legal.
105 if (!TD) return false;
106
107 unsigned FromWidth = From->getPrimitiveSizeInBits();
108 unsigned ToWidth = To->getPrimitiveSizeInBits();
109 bool FromLegal = TD->isLegalInteger(FromWidth);
110 bool ToLegal = TD->isLegalInteger(ToWidth);
111
112 // If this is a legal integer from type, and the result would be an illegal
113 // type, don't do the transformation.
114 if (FromLegal && !ToLegal)
115 return false;
116
117 // Otherwise, if both are illegal, do not increase the size of the result. We
118 // do allow things like i160 -> i64, but not i64 -> i160.
119 if (!FromLegal && !ToLegal && ToWidth > FromWidth)
120 return false;
121
122 return true;
123}
124
Matthijs Kooijman5e2a3182008-10-13 15:17:01 +0000125/// getBitCastOperand - If the specified operand is a CastInst, a constant
126/// expression bitcast, or a GetElementPtrInst with all zero indices, return the
127/// operand value, otherwise return null.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000128static Value *getBitCastOperand(Value *V) {
Dan Gohmanae402b02009-07-17 23:55:56 +0000129 if (Operator *O = dyn_cast<Operator>(V)) {
130 if (O->getOpcode() == Instruction::BitCast)
131 return O->getOperand(0);
132 if (GEPOperator *GEP = dyn_cast<GEPOperator>(V))
133 if (GEP->hasAllZeroIndices())
134 return GEP->getPointerOperand();
Matthijs Kooijman5e2a3182008-10-13 15:17:01 +0000135 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000136 return 0;
137}
138
139/// This function is a wrapper around CastInst::isEliminableCastPair. It
140/// simply extracts arguments and returns what that function returns.
141static Instruction::CastOps
142isEliminableCastPair(
143 const CastInst *CI, ///< The first cast instruction
144 unsigned opcode, ///< The opcode of the second cast instruction
145 const Type *DstTy, ///< The target type for the second cast instruction
146 TargetData *TD ///< The target data for pointer size
147) {
Dan Gohmana80e2712009-07-21 23:21:54 +0000148
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000149 const Type *SrcTy = CI->getOperand(0)->getType(); // A from above
150 const Type *MidTy = CI->getType(); // B from above
151
152 // Get the opcodes of the two Cast instructions
153 Instruction::CastOps firstOp = Instruction::CastOps(CI->getOpcode());
154 Instruction::CastOps secondOp = Instruction::CastOps(opcode);
155
Chris Lattner3e10f8d2009-03-24 18:35:40 +0000156 unsigned Res = CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy,
Dan Gohmana80e2712009-07-21 23:21:54 +0000157 DstTy,
Owen Anderson35b47072009-08-13 21:58:54 +0000158 TD ? TD->getIntPtrType(CI->getContext()) : 0);
Chris Lattner3e10f8d2009-03-24 18:35:40 +0000159
160 // We don't want to form an inttoptr or ptrtoint that converts to an integer
161 // type that differs from the pointer size.
Owen Anderson35b47072009-08-13 21:58:54 +0000162 if ((Res == Instruction::IntToPtr &&
Dan Gohman033445f2009-08-19 23:38:22 +0000163 (!TD || SrcTy != TD->getIntPtrType(CI->getContext()))) ||
Owen Anderson35b47072009-08-13 21:58:54 +0000164 (Res == Instruction::PtrToInt &&
Dan Gohman033445f2009-08-19 23:38:22 +0000165 (!TD || DstTy != TD->getIntPtrType(CI->getContext()))))
Chris Lattner3e10f8d2009-03-24 18:35:40 +0000166 Res = 0;
167
168 return Instruction::CastOps(Res);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000169}
170
171/// ValueRequiresCast - Return true if the cast from "V to Ty" actually results
172/// in any code being generated. It does not require codegen if V is simple
173/// enough or if the cast can be folded into other casts.
174static bool ValueRequiresCast(Instruction::CastOps opcode, const Value *V,
175 const Type *Ty, TargetData *TD) {
176 if (V->getType() == Ty || isa<Constant>(V)) return false;
177
178 // If this is another cast that can be eliminated, it isn't codegen either.
179 if (const CastInst *CI = dyn_cast<CastInst>(V))
Dan Gohmana80e2712009-07-21 23:21:54 +0000180 if (isEliminableCastPair(CI, opcode, Ty, TD))
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000181 return false;
182 return true;
183}
184
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000185// SimplifyCommutative - This performs a few simplifications for commutative
186// operators:
187//
188// 1. Order operands such that they are listed from right (least complex) to
189// left (most complex). This puts constants before unary operators before
190// binary operators.
191//
192// 2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
193// 3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
194//
195bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
196 bool Changed = false;
Dan Gohman5d138f92009-08-29 23:39:38 +0000197 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000198 Changed = !I.swapOperands();
199
200 if (!I.isAssociative()) return Changed;
201 Instruction::BinaryOps Opcode = I.getOpcode();
202 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
203 if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
204 if (isa<Constant>(I.getOperand(1))) {
Owen Anderson02b48c32009-07-29 18:55:55 +0000205 Constant *Folded = ConstantExpr::get(I.getOpcode(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000206 cast<Constant>(I.getOperand(1)),
207 cast<Constant>(Op->getOperand(1)));
208 I.setOperand(0, Op->getOperand(0));
209 I.setOperand(1, Folded);
210 return true;
211 } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
212 if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
213 isOnlyUse(Op) && isOnlyUse(Op1)) {
214 Constant *C1 = cast<Constant>(Op->getOperand(1));
215 Constant *C2 = cast<Constant>(Op1->getOperand(1));
216
217 // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Owen Anderson02b48c32009-07-29 18:55:55 +0000218 Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
Gabor Greifa645dd32008-05-16 19:29:10 +0000219 Instruction *New = BinaryOperator::Create(Opcode, Op->getOperand(0),
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000220 Op1->getOperand(0),
221 Op1->getName(), &I);
Chris Lattner3183fb62009-08-30 06:13:40 +0000222 Worklist.Add(New);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000223 I.setOperand(0, New);
224 I.setOperand(1, Folded);
225 return true;
226 }
227 }
228 return Changed;
229}
230
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000231// dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
232// if the LHS is a constant zero (which is the 'negate' form).
233//
Chris Lattner63ac8422010-01-04 07:37:31 +0000234Value *InstCombiner::dyn_castNegVal(Value *V) const {
Owen Anderson76f49252009-07-13 22:18:28 +0000235 if (BinaryOperator::isNeg(V))
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000236 return BinaryOperator::getNegArgument(V);
237
238 // Constants can be considered to be negated values if they can be folded.
239 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
Owen Anderson02b48c32009-07-29 18:55:55 +0000240 return ConstantExpr::getNeg(C);
Nick Lewycky58867bc2008-05-23 04:54:45 +0000241
242 if (ConstantVector *C = dyn_cast<ConstantVector>(V))
243 if (C->getType()->getElementType()->isInteger())
Owen Anderson02b48c32009-07-29 18:55:55 +0000244 return ConstantExpr::getNeg(C);
Nick Lewycky58867bc2008-05-23 04:54:45 +0000245
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000246 return 0;
247}
248
Dan Gohman7ce405e2009-06-04 22:49:04 +0000249// dyn_castFNegVal - Given a 'fsub' instruction, return the RHS of the
250// instruction if the LHS is a constant negative zero (which is the 'negate'
251// form).
252//
Dan Gohmanfe91cd62009-08-12 16:04:34 +0000253static inline Value *dyn_castFNegVal(Value *V) {
Owen Anderson76f49252009-07-13 22:18:28 +0000254 if (BinaryOperator::isFNeg(V))
Dan Gohman7ce405e2009-06-04 22:49:04 +0000255 return BinaryOperator::getFNegArgument(V);
256
257 // Constants can be considered to be negated values if they can be folded.
258 if (ConstantFP *C = dyn_cast<ConstantFP>(V))
Owen Anderson02b48c32009-07-29 18:55:55 +0000259 return ConstantExpr::getFNeg(C);
Dan Gohman7ce405e2009-06-04 22:49:04 +0000260
261 if (ConstantVector *C = dyn_cast<ConstantVector>(V))
262 if (C->getType()->getElementType()->isFloatingPoint())
Owen Anderson02b48c32009-07-29 18:55:55 +0000263 return ConstantExpr::getFNeg(C);
Dan Gohman7ce405e2009-06-04 22:49:04 +0000264
265 return 0;
266}
267
Chris Lattner78500cb2009-12-21 06:03:05 +0000268/// MatchSelectPattern - Pattern match integer [SU]MIN, [SU]MAX, and ABS idioms,
269/// returning the kind and providing the out parameter results if we
270/// successfully match.
271static SelectPatternFlavor
272MatchSelectPattern(Value *V, Value *&LHS, Value *&RHS) {
273 SelectInst *SI = dyn_cast<SelectInst>(V);
274 if (SI == 0) return SPF_UNKNOWN;
275
276 ICmpInst *ICI = dyn_cast<ICmpInst>(SI->getCondition());
277 if (ICI == 0) return SPF_UNKNOWN;
278
279 LHS = ICI->getOperand(0);
280 RHS = ICI->getOperand(1);
281
282 // (icmp X, Y) ? X : Y
283 if (SI->getTrueValue() == ICI->getOperand(0) &&
284 SI->getFalseValue() == ICI->getOperand(1)) {
285 switch (ICI->getPredicate()) {
286 default: return SPF_UNKNOWN; // Equality.
287 case ICmpInst::ICMP_UGT:
288 case ICmpInst::ICMP_UGE: return SPF_UMAX;
289 case ICmpInst::ICMP_SGT:
290 case ICmpInst::ICMP_SGE: return SPF_SMAX;
291 case ICmpInst::ICMP_ULT:
292 case ICmpInst::ICMP_ULE: return SPF_UMIN;
293 case ICmpInst::ICMP_SLT:
294 case ICmpInst::ICMP_SLE: return SPF_SMIN;
295 }
296 }
297
298 // (icmp X, Y) ? Y : X
299 if (SI->getTrueValue() == ICI->getOperand(1) &&
300 SI->getFalseValue() == ICI->getOperand(0)) {
301 switch (ICI->getPredicate()) {
302 default: return SPF_UNKNOWN; // Equality.
303 case ICmpInst::ICMP_UGT:
304 case ICmpInst::ICMP_UGE: return SPF_UMIN;
305 case ICmpInst::ICMP_SGT:
306 case ICmpInst::ICMP_SGE: return SPF_SMIN;
307 case ICmpInst::ICMP_ULT:
308 case ICmpInst::ICMP_ULE: return SPF_UMAX;
309 case ICmpInst::ICMP_SLT:
310 case ICmpInst::ICMP_SLE: return SPF_SMAX;
311 }
312 }
313
314 // TODO: (X > 4) ? X : 5 --> (X >= 5) ? X : 5 --> MAX(X, 5)
315
316 return SPF_UNKNOWN;
317}
318
Chris Lattner6e060db2009-10-26 15:40:07 +0000319/// isFreeToInvert - Return true if the specified value is free to invert (apply
320/// ~ to). This happens in cases where the ~ can be eliminated.
321static inline bool isFreeToInvert(Value *V) {
322 // ~(~(X)) -> X.
Evan Cheng5d4a07e2009-10-26 03:51:32 +0000323 if (BinaryOperator::isNot(V))
Chris Lattner6e060db2009-10-26 15:40:07 +0000324 return true;
325
326 // Constants can be considered to be not'ed values.
327 if (isa<ConstantInt>(V))
328 return true;
329
330 // Compares can be inverted if they have a single use.
331 if (CmpInst *CI = dyn_cast<CmpInst>(V))
332 return CI->hasOneUse();
333
334 return false;
335}
336
337static inline Value *dyn_castNotVal(Value *V) {
338 // If this is not(not(x)) don't return that this is a not: we want the two
339 // not's to be folded first.
340 if (BinaryOperator::isNot(V)) {
341 Value *Operand = BinaryOperator::getNotArgument(V);
342 if (!isFreeToInvert(Operand))
343 return Operand;
344 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000345
346 // Constants can be considered to be not'ed values...
347 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
Dan Gohmanfe91cd62009-08-12 16:04:34 +0000348 return ConstantInt::get(C->getType(), ~C->getValue());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000349 return 0;
350}
351
Chris Lattner6e060db2009-10-26 15:40:07 +0000352
353
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000354// dyn_castFoldableMul - If this value is a multiply that can be folded into
355// other computations (because it has a constant operand), return the
356// non-constant operand of the multiply, and set CST to point to the multiplier.
357// Otherwise, return null.
358//
Dan Gohmanfe91cd62009-08-12 16:04:34 +0000359static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000360 if (V->hasOneUse() && V->getType()->isInteger())
361 if (Instruction *I = dyn_cast<Instruction>(V)) {
362 if (I->getOpcode() == Instruction::Mul)
363 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
364 return I->getOperand(0);
365 if (I->getOpcode() == Instruction::Shl)
366 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
367 // The multiplier is really 1 << CST.
368 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
369 uint32_t CSTVal = CST->getLimitedValue(BitWidth);
Dan Gohmanfe91cd62009-08-12 16:04:34 +0000370 CST = ConstantInt::get(V->getType()->getContext(),
371 APInt(BitWidth, 1).shl(CSTVal));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000372 return I->getOperand(0);
373 }
374 }
375 return 0;
376}
377
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000378/// AddOne - Add one to a ConstantInt
Dan Gohmanfe91cd62009-08-12 16:04:34 +0000379static Constant *AddOne(Constant *C) {
Chris Lattner63ac8422010-01-04 07:37:31 +0000380 return ConstantExpr::getAdd(C, ConstantInt::get(C->getType(), 1));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000381}
382/// SubOne - Subtract one from a ConstantInt
Dan Gohmanfe91cd62009-08-12 16:04:34 +0000383static Constant *SubOne(ConstantInt *C) {
Chris Lattner63ac8422010-01-04 07:37:31 +0000384 return ConstantExpr::getSub(C, ConstantInt::get(C->getType(), 1));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000385}
Nick Lewycky9d798f92008-02-18 22:48:05 +0000386/// MultiplyOverflows - True if the multiply can not be expressed in an int
387/// this size.
Dan Gohmanfe91cd62009-08-12 16:04:34 +0000388static bool MultiplyOverflows(ConstantInt *C1, ConstantInt *C2, bool sign) {
Nick Lewycky9d798f92008-02-18 22:48:05 +0000389 uint32_t W = C1->getBitWidth();
390 APInt LHSExt = C1->getValue(), RHSExt = C2->getValue();
391 if (sign) {
392 LHSExt.sext(W * 2);
393 RHSExt.sext(W * 2);
394 } else {
395 LHSExt.zext(W * 2);
396 RHSExt.zext(W * 2);
397 }
398
399 APInt MulExt = LHSExt * RHSExt;
400
Chris Lattner78500cb2009-12-21 06:03:05 +0000401 if (!sign)
Nick Lewycky9d798f92008-02-18 22:48:05 +0000402 return MulExt.ugt(APInt::getLowBitsSet(W * 2, W));
Chris Lattner78500cb2009-12-21 06:03:05 +0000403
404 APInt Min = APInt::getSignedMinValue(W).sext(W * 2);
405 APInt Max = APInt::getSignedMaxValue(W).sext(W * 2);
406 return MulExt.slt(Min) || MulExt.sgt(Max);
Nick Lewycky9d798f92008-02-18 22:48:05 +0000407}
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000408
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000409
Dan Gohman5d56fd42008-05-19 22:14:15 +0000410
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000411/// AssociativeOpt - Perform an optimization on an associative operator. This
412/// function is designed to check a chain of associative operators for a
413/// potential to apply a certain optimization. Since the optimization may be
414/// applicable if the expression was reassociated, this checks the chain, then
415/// reassociates the expression as necessary to expose the optimization
416/// opportunity. This makes use of a special Functor, which must define
417/// 'shouldApply' and 'apply' methods.
418///
419template<typename Functor>
Dan Gohmanfe91cd62009-08-12 16:04:34 +0000420static Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000421 unsigned Opcode = Root.getOpcode();
422 Value *LHS = Root.getOperand(0);
423
424 // Quick check, see if the immediate LHS matches...
425 if (F.shouldApply(LHS))
426 return F.apply(Root);
427
428 // Otherwise, if the LHS is not of the same opcode as the root, return.
429 Instruction *LHSI = dyn_cast<Instruction>(LHS);
430 while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
431 // Should we apply this transform to the RHS?
432 bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
433
434 // If not to the RHS, check to see if we should apply to the LHS...
435 if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
436 cast<BinaryOperator>(LHSI)->swapOperands(); // Make the LHS the RHS
437 ShouldApply = true;
438 }
439
440 // If the functor wants to apply the optimization to the RHS of LHSI,
441 // reassociate the expression from ((? op A) op B) to (? op (A op B))
442 if (ShouldApply) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000443 // Now all of the instructions are in the current basic block, go ahead
444 // and perform the reassociation.
445 Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
446
447 // First move the selected RHS to the LHS of the root...
448 Root.setOperand(0, LHSI->getOperand(1));
449
450 // Make what used to be the LHS of the root be the user of the root...
451 Value *ExtraOperand = TmpLHSI->getOperand(1);
452 if (&Root == TmpLHSI) {
Owen Andersonaac28372009-07-31 20:28:14 +0000453 Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000454 return 0;
455 }
456 Root.replaceAllUsesWith(TmpLHSI); // Users now use TmpLHSI
457 TmpLHSI->setOperand(1, &Root); // TmpLHSI now uses the root
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000458 BasicBlock::iterator ARI = &Root; ++ARI;
Dan Gohman0bb9a3d2008-06-19 17:47:47 +0000459 TmpLHSI->moveBefore(ARI); // Move TmpLHSI to after Root
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000460 ARI = Root;
461
462 // Now propagate the ExtraOperand down the chain of instructions until we
463 // get to LHSI.
464 while (TmpLHSI != LHSI) {
465 Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
466 // Move the instruction to immediately before the chain we are
467 // constructing to avoid breaking dominance properties.
Dan Gohman0bb9a3d2008-06-19 17:47:47 +0000468 NextLHSI->moveBefore(ARI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000469 ARI = NextLHSI;
470
471 Value *NextOp = NextLHSI->getOperand(1);
472 NextLHSI->setOperand(1, ExtraOperand);
473 TmpLHSI = NextLHSI;
474 ExtraOperand = NextOp;
475 }
476
477 // Now that the instructions are reassociated, have the functor perform
478 // the transformation...
479 return F.apply(Root);
480 }
481
482 LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
483 }
484 return 0;
485}
486
Dan Gohman089efff2008-05-13 00:00:25 +0000487namespace {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000488
Nick Lewycky27f6c132008-05-23 04:34:58 +0000489// AddRHS - Implements: X + X --> X << 1
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000490struct AddRHS {
491 Value *RHS;
Dan Gohmancdff2122009-08-12 16:23:25 +0000492 explicit AddRHS(Value *rhs) : RHS(rhs) {}
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000493 bool shouldApply(Value *LHS) const { return LHS == RHS; }
494 Instruction *apply(BinaryOperator &Add) const {
Nick Lewycky27f6c132008-05-23 04:34:58 +0000495 return BinaryOperator::CreateShl(Add.getOperand(0),
Owen Andersoneacb44d2009-07-24 23:12:02 +0000496 ConstantInt::get(Add.getType(), 1));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000497 }
498};
499
500// AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
501// iff C1&C2 == 0
502struct AddMaskingAnd {
503 Constant *C2;
Dan Gohmancdff2122009-08-12 16:23:25 +0000504 explicit AddMaskingAnd(Constant *c) : C2(c) {}
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000505 bool shouldApply(Value *LHS) const {
506 ConstantInt *C1;
Dan Gohmancdff2122009-08-12 16:23:25 +0000507 return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
Owen Anderson02b48c32009-07-29 18:55:55 +0000508 ConstantExpr::getAnd(C1, C2)->isNullValue();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000509 }
510 Instruction *apply(BinaryOperator &Add) const {
Gabor Greifa645dd32008-05-16 19:29:10 +0000511 return BinaryOperator::CreateOr(Add.getOperand(0), Add.getOperand(1));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000512 }
513};
514
Dan Gohman089efff2008-05-13 00:00:25 +0000515}
516
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000517static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
518 InstCombiner *IC) {
Chris Lattner78628292009-08-30 19:47:22 +0000519 if (CastInst *CI = dyn_cast<CastInst>(&I))
Chris Lattnerd6164c22009-08-30 20:01:10 +0000520 return IC->Builder->CreateCast(CI->getOpcode(), SO, I.getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000521
522 // Figure out if the constant is the left or the right argument.
523 bool ConstIsRHS = isa<Constant>(I.getOperand(1));
524 Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
525
526 if (Constant *SOC = dyn_cast<Constant>(SO)) {
527 if (ConstIsRHS)
Owen Anderson02b48c32009-07-29 18:55:55 +0000528 return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
529 return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000530 }
531
532 Value *Op0 = SO, *Op1 = ConstOperand;
533 if (!ConstIsRHS)
534 std::swap(Op0, Op1);
Chris Lattnerc7694852009-08-30 07:44:24 +0000535
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000536 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
Chris Lattnerc7694852009-08-30 07:44:24 +0000537 return IC->Builder->CreateBinOp(BO->getOpcode(), Op0, Op1,
538 SO->getName()+".op");
539 if (ICmpInst *CI = dyn_cast<ICmpInst>(&I))
540 return IC->Builder->CreateICmp(CI->getPredicate(), Op0, Op1,
541 SO->getName()+".cmp");
542 if (FCmpInst *CI = dyn_cast<FCmpInst>(&I))
543 return IC->Builder->CreateICmp(CI->getPredicate(), Op0, Op1,
544 SO->getName()+".cmp");
545 llvm_unreachable("Unknown binary instruction type!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000546}
547
548// FoldOpIntoSelect - Given an instruction with a select as one operand and a
549// constant as the other operand, try to fold the binary operator into the
550// select arguments. This also works for Cast instructions, which obviously do
551// not have a second operand.
552static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
553 InstCombiner *IC) {
554 // Don't modify shared select instructions
555 if (!SI->hasOneUse()) return 0;
556 Value *TV = SI->getOperand(1);
557 Value *FV = SI->getOperand(2);
558
559 if (isa<Constant>(TV) || isa<Constant>(FV)) {
560 // Bool selects with constant operands can be folded to logical ops.
Chris Lattner03a27b42010-01-04 07:02:48 +0000561 if (SI->getType() == Type::getInt1Ty(SI->getContext())) return 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000562
563 Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
564 Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
565
Gabor Greifd6da1d02008-04-06 20:25:17 +0000566 return SelectInst::Create(SI->getCondition(), SelectTrueVal,
567 SelectFalseVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000568 }
569 return 0;
570}
571
572
Chris Lattnerf7843b72009-09-27 19:57:57 +0000573/// FoldOpIntoPhi - Given a binary operator, cast instruction, or select which
574/// has a PHI node as operand #0, see if we can fold the instruction into the
575/// PHI (which is only possible if all operands to the PHI are constants).
Chris Lattner9b61abd2009-09-27 20:46:36 +0000576///
577/// If AllowAggressive is true, FoldOpIntoPhi will allow certain transforms
578/// that would normally be unprofitable because they strongly encourage jump
579/// threading.
580Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I,
581 bool AllowAggressive) {
582 AllowAggressive = false;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000583 PHINode *PN = cast<PHINode>(I.getOperand(0));
584 unsigned NumPHIValues = PN->getNumIncomingValues();
Chris Lattner9b61abd2009-09-27 20:46:36 +0000585 if (NumPHIValues == 0 ||
586 // We normally only transform phis with a single use, unless we're trying
587 // hard to make jump threading happen.
588 (!PN->hasOneUse() && !AllowAggressive))
589 return 0;
590
591
Chris Lattnerf7843b72009-09-27 19:57:57 +0000592 // Check to see if all of the operands of the PHI are simple constants
593 // (constantint/constantfp/undef). If there is one non-constant value,
Chris Lattnerff5cd9d2009-09-27 20:18:49 +0000594 // remember the BB it is in. If there is more than one or if *it* is a PHI,
595 // bail out. We don't do arbitrary constant expressions here because moving
596 // their computation can be expensive without a cost model.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000597 BasicBlock *NonConstBB = 0;
598 for (unsigned i = 0; i != NumPHIValues; ++i)
Chris Lattnerf7843b72009-09-27 19:57:57 +0000599 if (!isa<Constant>(PN->getIncomingValue(i)) ||
600 isa<ConstantExpr>(PN->getIncomingValue(i))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000601 if (NonConstBB) return 0; // More than one non-const value.
602 if (isa<PHINode>(PN->getIncomingValue(i))) return 0; // Itself a phi.
603 NonConstBB = PN->getIncomingBlock(i);
604
605 // If the incoming non-constant value is in I's block, we have an infinite
606 // loop.
607 if (NonConstBB == I.getParent())
608 return 0;
609 }
610
611 // If there is exactly one non-constant value, we can insert a copy of the
612 // operation in that block. However, if this is a critical edge, we would be
613 // inserting the computation one some other paths (e.g. inside a loop). Only
614 // do this if the pred block is unconditionally branching into the phi block.
Chris Lattner9b61abd2009-09-27 20:46:36 +0000615 if (NonConstBB != 0 && !AllowAggressive) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000616 BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
617 if (!BI || !BI->isUnconditional()) return 0;
618 }
619
620 // Okay, we can do the transformation: create the new PHI node.
Gabor Greifd6da1d02008-04-06 20:25:17 +0000621 PHINode *NewPN = PHINode::Create(I.getType(), "");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000622 NewPN->reserveOperandSpace(PN->getNumOperands()/2);
Chris Lattner3980f9b2009-10-21 23:41:58 +0000623 InsertNewInstBefore(NewPN, *PN);
624 NewPN->takeName(PN);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000625
626 // Next, add all of the operands to the PHI.
Chris Lattnerf7843b72009-09-27 19:57:57 +0000627 if (SelectInst *SI = dyn_cast<SelectInst>(&I)) {
628 // We only currently try to fold the condition of a select when it is a phi,
629 // not the true/false values.
Chris Lattnerff5cd9d2009-09-27 20:18:49 +0000630 Value *TrueV = SI->getTrueValue();
631 Value *FalseV = SI->getFalseValue();
Chris Lattnerda3ee9c2009-09-28 06:49:44 +0000632 BasicBlock *PhiTransBB = PN->getParent();
Chris Lattnerf7843b72009-09-27 19:57:57 +0000633 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattnerff5cd9d2009-09-27 20:18:49 +0000634 BasicBlock *ThisBB = PN->getIncomingBlock(i);
Chris Lattnerda3ee9c2009-09-28 06:49:44 +0000635 Value *TrueVInPred = TrueV->DoPHITranslation(PhiTransBB, ThisBB);
636 Value *FalseVInPred = FalseV->DoPHITranslation(PhiTransBB, ThisBB);
Chris Lattnerf7843b72009-09-27 19:57:57 +0000637 Value *InV = 0;
638 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Chris Lattnerff5cd9d2009-09-27 20:18:49 +0000639 InV = InC->isNullValue() ? FalseVInPred : TrueVInPred;
Chris Lattnerf7843b72009-09-27 19:57:57 +0000640 } else {
641 assert(PN->getIncomingBlock(i) == NonConstBB);
Chris Lattnerff5cd9d2009-09-27 20:18:49 +0000642 InV = SelectInst::Create(PN->getIncomingValue(i), TrueVInPred,
643 FalseVInPred,
Chris Lattnerf7843b72009-09-27 19:57:57 +0000644 "phitmp", NonConstBB->getTerminator());
Chris Lattner3980f9b2009-10-21 23:41:58 +0000645 Worklist.Add(cast<Instruction>(InV));
Chris Lattnerf7843b72009-09-27 19:57:57 +0000646 }
Chris Lattnerff5cd9d2009-09-27 20:18:49 +0000647 NewPN->addIncoming(InV, ThisBB);
Chris Lattnerf7843b72009-09-27 19:57:57 +0000648 }
649 } else if (I.getNumOperands() == 2) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000650 Constant *C = cast<Constant>(I.getOperand(1));
651 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattnerb933ea62007-08-05 08:47:58 +0000652 Value *InV = 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000653 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
654 if (CmpInst *CI = dyn_cast<CmpInst>(&I))
Owen Anderson02b48c32009-07-29 18:55:55 +0000655 InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000656 else
Owen Anderson02b48c32009-07-29 18:55:55 +0000657 InV = ConstantExpr::get(I.getOpcode(), InC, C);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000658 } else {
659 assert(PN->getIncomingBlock(i) == NonConstBB);
660 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
Gabor Greifa645dd32008-05-16 19:29:10 +0000661 InV = BinaryOperator::Create(BO->getOpcode(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000662 PN->getIncomingValue(i), C, "phitmp",
663 NonConstBB->getTerminator());
664 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
Dan Gohmane6803b82009-08-25 23:17:54 +0000665 InV = CmpInst::Create(CI->getOpcode(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000666 CI->getPredicate(),
667 PN->getIncomingValue(i), C, "phitmp",
668 NonConstBB->getTerminator());
669 else
Edwin Törökbd448e32009-07-14 16:55:14 +0000670 llvm_unreachable("Unknown binop!");
Chris Lattner3980f9b2009-10-21 23:41:58 +0000671
672 Worklist.Add(cast<Instruction>(InV));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000673 }
674 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
675 }
676 } else {
677 CastInst *CI = cast<CastInst>(&I);
678 const Type *RetTy = CI->getType();
679 for (unsigned i = 0; i != NumPHIValues; ++i) {
680 Value *InV;
681 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Owen Anderson02b48c32009-07-29 18:55:55 +0000682 InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000683 } else {
684 assert(PN->getIncomingBlock(i) == NonConstBB);
Gabor Greifa645dd32008-05-16 19:29:10 +0000685 InV = CastInst::Create(CI->getOpcode(), PN->getIncomingValue(i),
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000686 I.getType(), "phitmp",
687 NonConstBB->getTerminator());
Chris Lattner3980f9b2009-10-21 23:41:58 +0000688 Worklist.Add(cast<Instruction>(InV));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000689 }
690 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
691 }
692 }
693 return ReplaceInstUsesWith(I, NewPN);
694}
695
Chris Lattner55476162008-01-29 06:52:45 +0000696
Chris Lattner3554f972008-05-20 05:46:13 +0000697/// WillNotOverflowSignedAdd - Return true if we can prove that:
698/// (sext (add LHS, RHS)) === (add (sext LHS), (sext RHS))
699/// This basically requires proving that the add in the original type would not
700/// overflow to change the sign bit or have a carry out.
701bool InstCombiner::WillNotOverflowSignedAdd(Value *LHS, Value *RHS) {
702 // There are different heuristics we can use for this. Here are some simple
703 // ones.
704
705 // Add has the property that adding any two 2's complement numbers can only
706 // have one carry bit which can change a sign. As such, if LHS and RHS each
Chris Lattner96076f72009-11-27 17:42:22 +0000707 // have at least two sign bits, we know that the addition of the two values
708 // will sign extend fine.
Chris Lattner3554f972008-05-20 05:46:13 +0000709 if (ComputeNumSignBits(LHS) > 1 && ComputeNumSignBits(RHS) > 1)
710 return true;
711
712
713 // If one of the operands only has one non-zero bit, and if the other operand
714 // has a known-zero bit in a more significant place than it (not including the
715 // sign bit) the ripple may go up to and fill the zero, but won't change the
716 // sign. For example, (X & ~4) + 1.
717
718 // TODO: Implement.
719
720 return false;
721}
722
Chris Lattner55476162008-01-29 06:52:45 +0000723
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000724Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
725 bool Changed = SimplifyCommutative(I);
726 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
727
Chris Lattner96076f72009-11-27 17:42:22 +0000728 if (Value *V = SimplifyAddInst(LHS, RHS, I.hasNoSignedWrap(),
729 I.hasNoUnsignedWrap(), TD))
730 return ReplaceInstUsesWith(I, V);
731
732
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000733 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000734 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
735 // X + (signbit) --> X ^ signbit
736 const APInt& Val = CI->getValue();
737 uint32_t BitWidth = Val.getBitWidth();
738 if (Val == APInt::getSignBit(BitWidth))
Gabor Greifa645dd32008-05-16 19:29:10 +0000739 return BinaryOperator::CreateXor(LHS, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000740
741 // See if SimplifyDemandedBits can simplify this. This handles stuff like
742 // (X & 254)+1 -> (X&254)|1
Dan Gohman8fd520a2009-06-15 22:12:54 +0000743 if (SimplifyDemandedInstructionBits(I))
Chris Lattner676c78e2009-01-31 08:15:18 +0000744 return &I;
Dan Gohman35b76162008-10-30 20:40:10 +0000745
Eli Friedmana21526d2009-07-13 22:27:52 +0000746 // zext(bool) + C -> bool ? C + 1 : C
Dan Gohman35b76162008-10-30 20:40:10 +0000747 if (ZExtInst *ZI = dyn_cast<ZExtInst>(LHS))
Chris Lattner03a27b42010-01-04 07:02:48 +0000748 if (ZI->getSrcTy() == Type::getInt1Ty(I.getContext()))
Dan Gohmanfe91cd62009-08-12 16:04:34 +0000749 return SelectInst::Create(ZI->getOperand(0), AddOne(CI), CI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000750 }
751
752 if (isa<PHINode>(LHS))
753 if (Instruction *NV = FoldOpIntoPhi(I))
754 return NV;
755
756 ConstantInt *XorRHS = 0;
757 Value *XorLHS = 0;
758 if (isa<ConstantInt>(RHSC) &&
Dan Gohmancdff2122009-08-12 16:23:25 +0000759 match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
Dan Gohman8fd520a2009-06-15 22:12:54 +0000760 uint32_t TySizeBits = I.getType()->getScalarSizeInBits();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000761 const APInt& RHSVal = cast<ConstantInt>(RHSC)->getValue();
762
763 uint32_t Size = TySizeBits / 2;
764 APInt C0080Val(APInt(TySizeBits, 1ULL).shl(Size - 1));
765 APInt CFF80Val(-C0080Val);
766 do {
767 if (TySizeBits > Size) {
768 // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
769 // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
770 if ((RHSVal == CFF80Val && XorRHS->getValue() == C0080Val) ||
771 (RHSVal == C0080Val && XorRHS->getValue() == CFF80Val)) {
772 // This is a sign extend if the top bits are known zero.
773 if (!MaskedValueIsZero(XorLHS,
774 APInt::getHighBitsSet(TySizeBits, TySizeBits - Size)))
775 Size = 0; // Not a sign ext, but can't be any others either.
776 break;
777 }
778 }
779 Size >>= 1;
780 C0080Val = APIntOps::lshr(C0080Val, Size);
781 CFF80Val = APIntOps::ashr(CFF80Val, Size);
782 } while (Size >= 1);
783
784 // FIXME: This shouldn't be necessary. When the backends can handle types
Chris Lattnerdeef1a72008-05-19 20:25:04 +0000785 // with funny bit widths then this switch statement should be removed. It
786 // is just here to get the size of the "middle" type back up to something
787 // that the back ends can handle.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000788 const Type *MiddleType = 0;
789 switch (Size) {
790 default: break;
Chris Lattner03a27b42010-01-04 07:02:48 +0000791 case 32:
792 case 16:
793 case 8: MiddleType = IntegerType::get(I.getContext(), Size); break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000794 }
795 if (MiddleType) {
Chris Lattnerc7694852009-08-30 07:44:24 +0000796 Value *NewTrunc = Builder->CreateTrunc(XorLHS, MiddleType, "sext");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000797 return new SExtInst(NewTrunc, I.getType(), I.getName());
798 }
799 }
800 }
801
Chris Lattner03a27b42010-01-04 07:02:48 +0000802 if (I.getType() == Type::getInt1Ty(I.getContext()))
Nick Lewyckyd4b63672008-05-31 17:59:52 +0000803 return BinaryOperator::CreateXor(LHS, RHS);
804
Nick Lewycky4d474cd2008-05-23 04:39:38 +0000805 // X + X --> X << 1
Nick Lewyckyd4b63672008-05-31 17:59:52 +0000806 if (I.getType()->isInteger()) {
Dan Gohmancdff2122009-08-12 16:23:25 +0000807 if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS)))
Owen Anderson24be4c12009-07-03 00:17:18 +0000808 return Result;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000809
810 if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
811 if (RHSI->getOpcode() == Instruction::Sub)
812 if (LHS == RHSI->getOperand(1)) // A + (B - A) --> B
813 return ReplaceInstUsesWith(I, RHSI->getOperand(0));
814 }
815 if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
816 if (LHSI->getOpcode() == Instruction::Sub)
817 if (RHS == LHSI->getOperand(1)) // (B - A) + A --> B
818 return ReplaceInstUsesWith(I, LHSI->getOperand(0));
819 }
820 }
821
822 // -A + B --> B - A
Chris Lattner53c9fbf2008-02-17 21:03:36 +0000823 // -A + -B --> -(A + B)
Dan Gohmanfe91cd62009-08-12 16:04:34 +0000824 if (Value *LHSV = dyn_castNegVal(LHS)) {
Chris Lattner322a9192008-02-18 17:50:16 +0000825 if (LHS->getType()->isIntOrIntVector()) {
Dan Gohmanfe91cd62009-08-12 16:04:34 +0000826 if (Value *RHSV = dyn_castNegVal(RHS)) {
Chris Lattnerc7694852009-08-30 07:44:24 +0000827 Value *NewAdd = Builder->CreateAdd(LHSV, RHSV, "sum");
Dan Gohmancdff2122009-08-12 16:23:25 +0000828 return BinaryOperator::CreateNeg(NewAdd);
Chris Lattner322a9192008-02-18 17:50:16 +0000829 }
Chris Lattner53c9fbf2008-02-17 21:03:36 +0000830 }
831
Gabor Greifa645dd32008-05-16 19:29:10 +0000832 return BinaryOperator::CreateSub(RHS, LHSV);
Chris Lattner53c9fbf2008-02-17 21:03:36 +0000833 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000834
835 // A + -B --> A - B
836 if (!isa<Constant>(RHS))
Dan Gohmanfe91cd62009-08-12 16:04:34 +0000837 if (Value *V = dyn_castNegVal(RHS))
Gabor Greifa645dd32008-05-16 19:29:10 +0000838 return BinaryOperator::CreateSub(LHS, V);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000839
840
841 ConstantInt *C2;
Dan Gohmanfe91cd62009-08-12 16:04:34 +0000842 if (Value *X = dyn_castFoldableMul(LHS, C2)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000843 if (X == RHS) // X*C + X --> X * (C+1)
Dan Gohmanfe91cd62009-08-12 16:04:34 +0000844 return BinaryOperator::CreateMul(RHS, AddOne(C2));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000845
846 // X*C1 + X*C2 --> X * (C1+C2)
847 ConstantInt *C1;
Dan Gohmanfe91cd62009-08-12 16:04:34 +0000848 if (X == dyn_castFoldableMul(RHS, C1))
Owen Anderson02b48c32009-07-29 18:55:55 +0000849 return BinaryOperator::CreateMul(X, ConstantExpr::getAdd(C1, C2));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000850 }
851
852 // X + X*C --> X * (C+1)
Dan Gohmanfe91cd62009-08-12 16:04:34 +0000853 if (dyn_castFoldableMul(RHS, C2) == LHS)
854 return BinaryOperator::CreateMul(LHS, AddOne(C2));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000855
856 // X + ~X --> -1 since ~X = -X-1
Dan Gohmanfe91cd62009-08-12 16:04:34 +0000857 if (dyn_castNotVal(LHS) == RHS ||
858 dyn_castNotVal(RHS) == LHS)
Owen Andersonaac28372009-07-31 20:28:14 +0000859 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000860
861
862 // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
Dan Gohmancdff2122009-08-12 16:23:25 +0000863 if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
864 if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2)))
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000865 return R;
Chris Lattnerc1575ce2008-05-19 20:01:56 +0000866
867 // A+B --> A|B iff A and B have no bits set in common.
868 if (const IntegerType *IT = dyn_cast<IntegerType>(I.getType())) {
869 APInt Mask = APInt::getAllOnesValue(IT->getBitWidth());
870 APInt LHSKnownOne(IT->getBitWidth(), 0);
871 APInt LHSKnownZero(IT->getBitWidth(), 0);
872 ComputeMaskedBits(LHS, Mask, LHSKnownZero, LHSKnownOne);
873 if (LHSKnownZero != 0) {
874 APInt RHSKnownOne(IT->getBitWidth(), 0);
875 APInt RHSKnownZero(IT->getBitWidth(), 0);
876 ComputeMaskedBits(RHS, Mask, RHSKnownZero, RHSKnownOne);
877
878 // No bits in common -> bitwise or.
Chris Lattner130443c2008-05-19 20:03:53 +0000879 if ((LHSKnownZero|RHSKnownZero).isAllOnesValue())
Chris Lattnerc1575ce2008-05-19 20:01:56 +0000880 return BinaryOperator::CreateOr(LHS, RHS);
Chris Lattnerc1575ce2008-05-19 20:01:56 +0000881 }
882 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000883
Nick Lewycky83598a72008-02-03 07:42:09 +0000884 // W*X + Y*Z --> W * (X+Z) iff W == Y
Nick Lewycky5d03b512008-02-03 08:19:11 +0000885 if (I.getType()->isIntOrIntVector()) {
Nick Lewycky83598a72008-02-03 07:42:09 +0000886 Value *W, *X, *Y, *Z;
Dan Gohmancdff2122009-08-12 16:23:25 +0000887 if (match(LHS, m_Mul(m_Value(W), m_Value(X))) &&
888 match(RHS, m_Mul(m_Value(Y), m_Value(Z)))) {
Nick Lewycky83598a72008-02-03 07:42:09 +0000889 if (W != Y) {
890 if (W == Z) {
Bill Wendling44a36ea2008-02-26 10:53:30 +0000891 std::swap(Y, Z);
Nick Lewycky83598a72008-02-03 07:42:09 +0000892 } else if (Y == X) {
Bill Wendling44a36ea2008-02-26 10:53:30 +0000893 std::swap(W, X);
894 } else if (X == Z) {
Nick Lewycky83598a72008-02-03 07:42:09 +0000895 std::swap(Y, Z);
896 std::swap(W, X);
897 }
898 }
899
900 if (W == Y) {
Chris Lattnerc7694852009-08-30 07:44:24 +0000901 Value *NewAdd = Builder->CreateAdd(X, Z, LHS->getName());
Gabor Greifa645dd32008-05-16 19:29:10 +0000902 return BinaryOperator::CreateMul(W, NewAdd);
Nick Lewycky83598a72008-02-03 07:42:09 +0000903 }
904 }
905 }
906
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000907 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
908 Value *X = 0;
Dan Gohmancdff2122009-08-12 16:23:25 +0000909 if (match(LHS, m_Not(m_Value(X)))) // ~X + C --> (C-1) - X
Dan Gohmanfe91cd62009-08-12 16:04:34 +0000910 return BinaryOperator::CreateSub(SubOne(CRHS), X);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000911
912 // (X & FF00) + xx00 -> (X+xx00) & FF00
Owen Andersona21eb582009-07-10 17:35:01 +0000913 if (LHS->hasOneUse() &&
Dan Gohmancdff2122009-08-12 16:23:25 +0000914 match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
Owen Anderson02b48c32009-07-29 18:55:55 +0000915 Constant *Anded = ConstantExpr::getAnd(CRHS, C2);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000916 if (Anded == CRHS) {
917 // See if all bits from the first bit set in the Add RHS up are included
918 // in the mask. First, get the rightmost bit.
919 const APInt& AddRHSV = CRHS->getValue();
920
921 // Form a mask of all bits from the lowest bit added through the top.
922 APInt AddRHSHighBits(~((AddRHSV & -AddRHSV)-1));
923
924 // See if the and mask includes all of these bits.
925 APInt AddRHSHighBitsAnd(AddRHSHighBits & C2->getValue());
926
927 if (AddRHSHighBits == AddRHSHighBitsAnd) {
928 // Okay, the xform is safe. Insert the new add pronto.
Chris Lattnerc7694852009-08-30 07:44:24 +0000929 Value *NewAdd = Builder->CreateAdd(X, CRHS, LHS->getName());
Gabor Greifa645dd32008-05-16 19:29:10 +0000930 return BinaryOperator::CreateAnd(NewAdd, C2);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000931 }
932 }
933 }
934
935 // Try to fold constant add into select arguments.
936 if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
937 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
938 return R;
939 }
940
Chris Lattnerbf0c5f32007-12-20 01:56:58 +0000941 // add (select X 0 (sub n A)) A --> select X A n
Christopher Lamb244ec282007-12-18 09:34:41 +0000942 {
943 SelectInst *SI = dyn_cast<SelectInst>(LHS);
Chris Lattner641ea462008-11-16 04:46:19 +0000944 Value *A = RHS;
Christopher Lamb244ec282007-12-18 09:34:41 +0000945 if (!SI) {
946 SI = dyn_cast<SelectInst>(RHS);
Chris Lattner641ea462008-11-16 04:46:19 +0000947 A = LHS;
Christopher Lamb244ec282007-12-18 09:34:41 +0000948 }
Chris Lattnerbf0c5f32007-12-20 01:56:58 +0000949 if (SI && SI->hasOneUse()) {
Christopher Lamb244ec282007-12-18 09:34:41 +0000950 Value *TV = SI->getTrueValue();
951 Value *FV = SI->getFalseValue();
Chris Lattner641ea462008-11-16 04:46:19 +0000952 Value *N;
Christopher Lamb244ec282007-12-18 09:34:41 +0000953
954 // Can we fold the add into the argument of the select?
955 // We check both true and false select arguments for a matching subtract.
Dan Gohmancdff2122009-08-12 16:23:25 +0000956 if (match(FV, m_Zero()) &&
957 match(TV, m_Sub(m_Value(N), m_Specific(A))))
Chris Lattner641ea462008-11-16 04:46:19 +0000958 // Fold the add into the true select value.
Gabor Greifd6da1d02008-04-06 20:25:17 +0000959 return SelectInst::Create(SI->getCondition(), N, A);
Dan Gohmancdff2122009-08-12 16:23:25 +0000960 if (match(TV, m_Zero()) &&
961 match(FV, m_Sub(m_Value(N), m_Specific(A))))
Chris Lattner641ea462008-11-16 04:46:19 +0000962 // Fold the add into the false select value.
Gabor Greifd6da1d02008-04-06 20:25:17 +0000963 return SelectInst::Create(SI->getCondition(), A, N);
Christopher Lamb244ec282007-12-18 09:34:41 +0000964 }
965 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000966
Chris Lattner3554f972008-05-20 05:46:13 +0000967 // Check for (add (sext x), y), see if we can merge this into an
968 // integer add followed by a sext.
969 if (SExtInst *LHSConv = dyn_cast<SExtInst>(LHS)) {
970 // (add (sext x), cst) --> (sext (add x, cst'))
971 if (ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS)) {
972 Constant *CI =
Owen Anderson02b48c32009-07-29 18:55:55 +0000973 ConstantExpr::getTrunc(RHSC, LHSConv->getOperand(0)->getType());
Chris Lattner3554f972008-05-20 05:46:13 +0000974 if (LHSConv->hasOneUse() &&
Owen Anderson02b48c32009-07-29 18:55:55 +0000975 ConstantExpr::getSExt(CI, I.getType()) == RHSC &&
Chris Lattner3554f972008-05-20 05:46:13 +0000976 WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
977 // Insert the new, smaller add.
Dan Gohman4dcf7c02009-10-26 22:14:22 +0000978 Value *NewAdd = Builder->CreateNSWAdd(LHSConv->getOperand(0),
979 CI, "addconv");
Chris Lattner3554f972008-05-20 05:46:13 +0000980 return new SExtInst(NewAdd, I.getType());
981 }
982 }
983
984 // (add (sext x), (sext y)) --> (sext (add int x, y))
985 if (SExtInst *RHSConv = dyn_cast<SExtInst>(RHS)) {
986 // Only do this if x/y have the same type, if at last one of them has a
987 // single use (so we don't increase the number of sexts), and if the
988 // integer add will not overflow.
989 if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
990 (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
991 WillNotOverflowSignedAdd(LHSConv->getOperand(0),
992 RHSConv->getOperand(0))) {
993 // Insert the new integer add.
Dan Gohman4dcf7c02009-10-26 22:14:22 +0000994 Value *NewAdd = Builder->CreateNSWAdd(LHSConv->getOperand(0),
995 RHSConv->getOperand(0), "addconv");
Chris Lattner3554f972008-05-20 05:46:13 +0000996 return new SExtInst(NewAdd, I.getType());
997 }
998 }
999 }
Dan Gohman7ce405e2009-06-04 22:49:04 +00001000
1001 return Changed ? &I : 0;
1002}
1003
1004Instruction *InstCombiner::visitFAdd(BinaryOperator &I) {
1005 bool Changed = SimplifyCommutative(I);
1006 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
1007
1008 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
1009 // X + 0 --> X
1010 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
Owen Andersond363a0e2009-07-27 20:59:43 +00001011 if (CFP->isExactlyValue(ConstantFP::getNegativeZero
Dan Gohman7ce405e2009-06-04 22:49:04 +00001012 (I.getType())->getValueAPF()))
1013 return ReplaceInstUsesWith(I, LHS);
1014 }
1015
1016 if (isa<PHINode>(LHS))
1017 if (Instruction *NV = FoldOpIntoPhi(I))
1018 return NV;
1019 }
1020
1021 // -A + B --> B - A
1022 // -A + -B --> -(A + B)
Dan Gohmanfe91cd62009-08-12 16:04:34 +00001023 if (Value *LHSV = dyn_castFNegVal(LHS))
Dan Gohman7ce405e2009-06-04 22:49:04 +00001024 return BinaryOperator::CreateFSub(RHS, LHSV);
1025
1026 // A + -B --> A - B
1027 if (!isa<Constant>(RHS))
Dan Gohmanfe91cd62009-08-12 16:04:34 +00001028 if (Value *V = dyn_castFNegVal(RHS))
Dan Gohman7ce405e2009-06-04 22:49:04 +00001029 return BinaryOperator::CreateFSub(LHS, V);
1030
1031 // Check for X+0.0. Simplify it to X if we know X is not -0.0.
1032 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS))
1033 if (CFP->getValueAPF().isPosZero() && CannotBeNegativeZero(LHS))
1034 return ReplaceInstUsesWith(I, LHS);
1035
Chris Lattner3554f972008-05-20 05:46:13 +00001036 // Check for (add double (sitofp x), y), see if we can merge this into an
1037 // integer add followed by a promotion.
1038 if (SIToFPInst *LHSConv = dyn_cast<SIToFPInst>(LHS)) {
1039 // (add double (sitofp x), fpcst) --> (sitofp (add int x, intcst))
1040 // ... if the constant fits in the integer value. This is useful for things
1041 // like (double)(x & 1234) + 4.0 -> (double)((X & 1234)+4) which no longer
1042 // requires a constant pool load, and generally allows the add to be better
1043 // instcombined.
1044 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS)) {
1045 Constant *CI =
Owen Anderson02b48c32009-07-29 18:55:55 +00001046 ConstantExpr::getFPToSI(CFP, LHSConv->getOperand(0)->getType());
Chris Lattner3554f972008-05-20 05:46:13 +00001047 if (LHSConv->hasOneUse() &&
Owen Anderson02b48c32009-07-29 18:55:55 +00001048 ConstantExpr::getSIToFP(CI, I.getType()) == CFP &&
Chris Lattner3554f972008-05-20 05:46:13 +00001049 WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
1050 // Insert the new integer add.
Dan Gohman4dcf7c02009-10-26 22:14:22 +00001051 Value *NewAdd = Builder->CreateNSWAdd(LHSConv->getOperand(0),
1052 CI, "addconv");
Chris Lattner3554f972008-05-20 05:46:13 +00001053 return new SIToFPInst(NewAdd, I.getType());
1054 }
1055 }
1056
1057 // (add double (sitofp x), (sitofp y)) --> (sitofp (add int x, y))
1058 if (SIToFPInst *RHSConv = dyn_cast<SIToFPInst>(RHS)) {
1059 // Only do this if x/y have the same type, if at last one of them has a
1060 // single use (so we don't increase the number of int->fp conversions),
1061 // and if the integer add will not overflow.
1062 if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
1063 (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
1064 WillNotOverflowSignedAdd(LHSConv->getOperand(0),
1065 RHSConv->getOperand(0))) {
1066 // Insert the new integer add.
Dan Gohman4dcf7c02009-10-26 22:14:22 +00001067 Value *NewAdd = Builder->CreateNSWAdd(LHSConv->getOperand(0),
Chris Lattner93e6ff92009-11-04 08:05:20 +00001068 RHSConv->getOperand(0),"addconv");
Chris Lattner3554f972008-05-20 05:46:13 +00001069 return new SIToFPInst(NewAdd, I.getType());
1070 }
1071 }
1072 }
1073
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001074 return Changed ? &I : 0;
1075}
1076
Chris Lattner93e6ff92009-11-04 08:05:20 +00001077
1078/// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
1079/// code necessary to compute the offset from the base pointer (without adding
1080/// in the base pointer). Return the result as a signed integer of intptr size.
Chris Lattner63ac8422010-01-04 07:37:31 +00001081Value *InstCombiner::EmitGEPOffset(User *GEP) {
1082 TargetData &TD = *getTargetData();
Chris Lattner93e6ff92009-11-04 08:05:20 +00001083 gep_type_iterator GTI = gep_type_begin(GEP);
1084 const Type *IntPtrTy = TD.getIntPtrType(GEP->getContext());
1085 Value *Result = Constant::getNullValue(IntPtrTy);
1086
1087 // Build a mask for high order bits.
1088 unsigned IntPtrWidth = TD.getPointerSizeInBits();
1089 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
1090
1091 for (User::op_iterator i = GEP->op_begin() + 1, e = GEP->op_end(); i != e;
1092 ++i, ++GTI) {
1093 Value *Op = *i;
1094 uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType()) & PtrSizeMask;
1095 if (ConstantInt *OpC = dyn_cast<ConstantInt>(Op)) {
1096 if (OpC->isZero()) continue;
1097
1098 // Handle a struct index, which adds its field offset to the pointer.
1099 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
1100 Size = TD.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
1101
Chris Lattner63ac8422010-01-04 07:37:31 +00001102 Result = Builder->CreateAdd(Result,
1103 ConstantInt::get(IntPtrTy, Size),
1104 GEP->getName()+".offs");
Chris Lattner93e6ff92009-11-04 08:05:20 +00001105 continue;
1106 }
1107
1108 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
1109 Constant *OC =
1110 ConstantExpr::getIntegerCast(OpC, IntPtrTy, true /*SExt*/);
1111 Scale = ConstantExpr::getMul(OC, Scale);
1112 // Emit an add instruction.
Chris Lattner63ac8422010-01-04 07:37:31 +00001113 Result = Builder->CreateAdd(Result, Scale, GEP->getName()+".offs");
Chris Lattner93e6ff92009-11-04 08:05:20 +00001114 continue;
1115 }
1116 // Convert to correct type.
1117 if (Op->getType() != IntPtrTy)
Chris Lattner63ac8422010-01-04 07:37:31 +00001118 Op = Builder->CreateIntCast(Op, IntPtrTy, true, Op->getName()+".c");
Chris Lattner93e6ff92009-11-04 08:05:20 +00001119 if (Size != 1) {
1120 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
1121 // We'll let instcombine(mul) convert this to a shl if possible.
Chris Lattner63ac8422010-01-04 07:37:31 +00001122 Op = Builder->CreateMul(Op, Scale, GEP->getName()+".idx");
Chris Lattner93e6ff92009-11-04 08:05:20 +00001123 }
1124
1125 // Emit an add instruction.
Chris Lattner63ac8422010-01-04 07:37:31 +00001126 Result = Builder->CreateAdd(Op, Result, GEP->getName()+".offs");
Chris Lattner93e6ff92009-11-04 08:05:20 +00001127 }
1128 return Result;
1129}
1130
1131
Chris Lattner93e6ff92009-11-04 08:05:20 +00001132
1133
1134/// Optimize pointer differences into the same array into a size. Consider:
1135/// &A[10] - &A[0]: we should compile this to "10". LHS/RHS are the pointer
1136/// operands to the ptrtoint instructions for the LHS/RHS of the subtract.
1137///
1138Value *InstCombiner::OptimizePointerDifference(Value *LHS, Value *RHS,
1139 const Type *Ty) {
1140 assert(TD && "Must have target data info for this");
1141
1142 // If LHS is a gep based on RHS or RHS is a gep based on LHS, we can optimize
1143 // this.
1144 bool Swapped;
Chris Lattner08be8ff2010-01-01 22:42:29 +00001145 GetElementPtrInst *GEP = 0;
1146 ConstantExpr *CstGEP = 0;
Chris Lattner93e6ff92009-11-04 08:05:20 +00001147
Chris Lattner08be8ff2010-01-01 22:42:29 +00001148 // TODO: Could also optimize &A[i] - &A[j] -> "i-j", and "&A.foo[i] - &A.foo".
1149 // For now we require one side to be the base pointer "A" or a constant
1150 // expression derived from it.
1151 if (GetElementPtrInst *LHSGEP = dyn_cast<GetElementPtrInst>(LHS)) {
1152 // (gep X, ...) - X
1153 if (LHSGEP->getOperand(0) == RHS) {
1154 GEP = LHSGEP;
1155 Swapped = false;
1156 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(RHS)) {
1157 // (gep X, ...) - (ce_gep X, ...)
1158 if (CE->getOpcode() == Instruction::GetElementPtr &&
1159 LHSGEP->getOperand(0) == CE->getOperand(0)) {
1160 CstGEP = CE;
1161 GEP = LHSGEP;
1162 Swapped = false;
1163 }
1164 }
1165 }
1166
1167 if (GetElementPtrInst *RHSGEP = dyn_cast<GetElementPtrInst>(RHS)) {
1168 // X - (gep X, ...)
1169 if (RHSGEP->getOperand(0) == LHS) {
1170 GEP = RHSGEP;
1171 Swapped = true;
1172 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(LHS)) {
1173 // (ce_gep X, ...) - (gep X, ...)
1174 if (CE->getOpcode() == Instruction::GetElementPtr &&
1175 RHSGEP->getOperand(0) == CE->getOperand(0)) {
1176 CstGEP = CE;
1177 GEP = RHSGEP;
1178 Swapped = true;
1179 }
1180 }
1181 }
1182
1183 if (GEP == 0)
Chris Lattner93e6ff92009-11-04 08:05:20 +00001184 return 0;
1185
Chris Lattner93e6ff92009-11-04 08:05:20 +00001186 // Emit the offset of the GEP and an intptr_t.
Chris Lattner63ac8422010-01-04 07:37:31 +00001187 Value *Result = EmitGEPOffset(GEP);
Chris Lattner08be8ff2010-01-01 22:42:29 +00001188
1189 // If we had a constant expression GEP on the other side offsetting the
1190 // pointer, subtract it from the offset we have.
1191 if (CstGEP) {
Chris Lattner63ac8422010-01-04 07:37:31 +00001192 Value *CstOffset = EmitGEPOffset(CstGEP);
Chris Lattner08be8ff2010-01-01 22:42:29 +00001193 Result = Builder->CreateSub(Result, CstOffset);
1194 }
1195
Chris Lattner93e6ff92009-11-04 08:05:20 +00001196
1197 // If we have p - gep(p, ...) then we have to negate the result.
1198 if (Swapped)
1199 Result = Builder->CreateNeg(Result, "diff.neg");
1200
1201 return Builder->CreateIntCast(Result, Ty, true);
1202}
1203
1204
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001205Instruction *InstCombiner::visitSub(BinaryOperator &I) {
1206 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1207
Dan Gohman7ce405e2009-06-04 22:49:04 +00001208 if (Op0 == Op1) // sub X, X -> 0
Owen Andersonaac28372009-07-31 20:28:14 +00001209 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001210
Chris Lattnera54b96b2009-12-21 04:04:05 +00001211 // If this is a 'B = x-(-A)', change to B = x+A. This preserves NSW/NUW.
1212 if (Value *V = dyn_castNegVal(Op1)) {
1213 BinaryOperator *Res = BinaryOperator::CreateAdd(Op0, V);
1214 Res->setHasNoSignedWrap(I.hasNoSignedWrap());
1215 Res->setHasNoUnsignedWrap(I.hasNoUnsignedWrap());
1216 return Res;
1217 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001218
1219 if (isa<UndefValue>(Op0))
1220 return ReplaceInstUsesWith(I, Op0); // undef - X -> undef
1221 if (isa<UndefValue>(Op1))
1222 return ReplaceInstUsesWith(I, Op1); // X - undef -> undef
Chris Lattner03a27b42010-01-04 07:02:48 +00001223 if (I.getType() == Type::getInt1Ty(I.getContext()))
Chris Lattner93e6ff92009-11-04 08:05:20 +00001224 return BinaryOperator::CreateXor(Op0, Op1);
1225
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001226 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
Chris Lattner93e6ff92009-11-04 08:05:20 +00001227 // Replace (-1 - A) with (~A).
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001228 if (C->isAllOnesValue())
Dan Gohmancdff2122009-08-12 16:23:25 +00001229 return BinaryOperator::CreateNot(Op1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001230
1231 // C - ~X == X + (1+C)
1232 Value *X = 0;
Dan Gohmancdff2122009-08-12 16:23:25 +00001233 if (match(Op1, m_Not(m_Value(X))))
Dan Gohmanfe91cd62009-08-12 16:04:34 +00001234 return BinaryOperator::CreateAdd(X, AddOne(C));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001235
1236 // -(X >>u 31) -> (X >>s 31)
1237 // -(X >>s 31) -> (X >>u 31)
1238 if (C->isZero()) {
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00001239 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op1)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001240 if (SI->getOpcode() == Instruction::LShr) {
1241 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
1242 // Check to see if we are shifting out everything but the sign bit.
1243 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
1244 SI->getType()->getPrimitiveSizeInBits()-1) {
1245 // Ok, the transformation is safe. Insert AShr.
Gabor Greifa645dd32008-05-16 19:29:10 +00001246 return BinaryOperator::Create(Instruction::AShr,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001247 SI->getOperand(0), CU, SI->getName());
1248 }
1249 }
Chris Lattner93e6ff92009-11-04 08:05:20 +00001250 } else if (SI->getOpcode() == Instruction::AShr) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001251 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
1252 // Check to see if we are shifting out everything but the sign bit.
1253 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
1254 SI->getType()->getPrimitiveSizeInBits()-1) {
1255 // Ok, the transformation is safe. Insert LShr.
Gabor Greifa645dd32008-05-16 19:29:10 +00001256 return BinaryOperator::CreateLShr(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001257 SI->getOperand(0), CU, SI->getName());
1258 }
1259 }
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00001260 }
1261 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001262 }
1263
1264 // Try to fold constant sub into select arguments.
1265 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
1266 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
1267 return R;
Eli Friedmana21526d2009-07-13 22:27:52 +00001268
1269 // C - zext(bool) -> bool ? C - 1 : C
1270 if (ZExtInst *ZI = dyn_cast<ZExtInst>(Op1))
Chris Lattner03a27b42010-01-04 07:02:48 +00001271 if (ZI->getSrcTy() == Type::getInt1Ty(I.getContext()))
Dan Gohmanfe91cd62009-08-12 16:04:34 +00001272 return SelectInst::Create(ZI->getOperand(0), SubOne(C), C);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001273 }
1274
1275 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
Dan Gohman7ce405e2009-06-04 22:49:04 +00001276 if (Op1I->getOpcode() == Instruction::Add) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001277 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
Dan Gohmancdff2122009-08-12 16:23:25 +00001278 return BinaryOperator::CreateNeg(Op1I->getOperand(1),
Owen Anderson15b39322009-07-13 04:09:18 +00001279 I.getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001280 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
Dan Gohmancdff2122009-08-12 16:23:25 +00001281 return BinaryOperator::CreateNeg(Op1I->getOperand(0),
Owen Anderson15b39322009-07-13 04:09:18 +00001282 I.getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001283 else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
1284 if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
1285 // C1-(X+C2) --> (C1-C2)-X
Owen Anderson24be4c12009-07-03 00:17:18 +00001286 return BinaryOperator::CreateSub(
Owen Anderson02b48c32009-07-29 18:55:55 +00001287 ConstantExpr::getSub(CI1, CI2), Op1I->getOperand(0));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001288 }
1289 }
1290
1291 if (Op1I->hasOneUse()) {
1292 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
1293 // is not used by anyone else...
1294 //
Dan Gohman7ce405e2009-06-04 22:49:04 +00001295 if (Op1I->getOpcode() == Instruction::Sub) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001296 // Swap the two operands of the subexpr...
1297 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
1298 Op1I->setOperand(0, IIOp1);
1299 Op1I->setOperand(1, IIOp0);
1300
1301 // Create the new top level add instruction...
Gabor Greifa645dd32008-05-16 19:29:10 +00001302 return BinaryOperator::CreateAdd(Op0, Op1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001303 }
1304
1305 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
1306 //
1307 if (Op1I->getOpcode() == Instruction::And &&
1308 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
1309 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
1310
Chris Lattnerc7694852009-08-30 07:44:24 +00001311 Value *NewNot = Builder->CreateNot(OtherOp, "B.not");
Gabor Greifa645dd32008-05-16 19:29:10 +00001312 return BinaryOperator::CreateAnd(Op0, NewNot);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001313 }
1314
1315 // 0 - (X sdiv C) -> (X sdiv -C)
1316 if (Op1I->getOpcode() == Instruction::SDiv)
1317 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
1318 if (CSI->isZero())
1319 if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
Gabor Greifa645dd32008-05-16 19:29:10 +00001320 return BinaryOperator::CreateSDiv(Op1I->getOperand(0),
Owen Anderson02b48c32009-07-29 18:55:55 +00001321 ConstantExpr::getNeg(DivRHS));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001322
1323 // X - X*C --> X * (1-C)
1324 ConstantInt *C2 = 0;
Dan Gohmanfe91cd62009-08-12 16:04:34 +00001325 if (dyn_castFoldableMul(Op1I, C2) == Op0) {
Owen Anderson24be4c12009-07-03 00:17:18 +00001326 Constant *CP1 =
Owen Anderson02b48c32009-07-29 18:55:55 +00001327 ConstantExpr::getSub(ConstantInt::get(I.getType(), 1),
Dan Gohman8fd520a2009-06-15 22:12:54 +00001328 C2);
Gabor Greifa645dd32008-05-16 19:29:10 +00001329 return BinaryOperator::CreateMul(Op0, CP1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001330 }
1331 }
1332 }
1333
Dan Gohman7ce405e2009-06-04 22:49:04 +00001334 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
1335 if (Op0I->getOpcode() == Instruction::Add) {
1336 if (Op0I->getOperand(0) == Op1) // (Y+X)-Y == X
1337 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
1338 else if (Op0I->getOperand(1) == Op1) // (X+Y)-Y == X
1339 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
1340 } else if (Op0I->getOpcode() == Instruction::Sub) {
1341 if (Op0I->getOperand(0) == Op1) // (X-Y)-X == -Y
Dan Gohmancdff2122009-08-12 16:23:25 +00001342 return BinaryOperator::CreateNeg(Op0I->getOperand(1),
Owen Anderson15b39322009-07-13 04:09:18 +00001343 I.getName());
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00001344 }
Dan Gohman7ce405e2009-06-04 22:49:04 +00001345 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001346
1347 ConstantInt *C1;
Dan Gohmanfe91cd62009-08-12 16:04:34 +00001348 if (Value *X = dyn_castFoldableMul(Op0, C1)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001349 if (X == Op1) // X*C - X --> X * (C-1)
Dan Gohmanfe91cd62009-08-12 16:04:34 +00001350 return BinaryOperator::CreateMul(Op1, SubOne(C1));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001351
1352 ConstantInt *C2; // X*C1 - X*C2 -> X * (C1-C2)
Dan Gohmanfe91cd62009-08-12 16:04:34 +00001353 if (X == dyn_castFoldableMul(Op1, C2))
Owen Anderson02b48c32009-07-29 18:55:55 +00001354 return BinaryOperator::CreateMul(X, ConstantExpr::getSub(C1, C2));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001355 }
Chris Lattner93e6ff92009-11-04 08:05:20 +00001356
1357 // Optimize pointer differences into the same array into a size. Consider:
1358 // &A[10] - &A[0]: we should compile this to "10".
1359 if (TD) {
Chris Lattnerc49d68a2010-01-01 22:12:03 +00001360 Value *LHSOp, *RHSOp;
Chris Lattnerc93843f2010-01-01 22:29:12 +00001361 if (match(Op0, m_PtrToInt(m_Value(LHSOp))) &&
1362 match(Op1, m_PtrToInt(m_Value(RHSOp))))
Chris Lattnerc49d68a2010-01-01 22:12:03 +00001363 if (Value *Res = OptimizePointerDifference(LHSOp, RHSOp, I.getType()))
1364 return ReplaceInstUsesWith(I, Res);
Chris Lattner93e6ff92009-11-04 08:05:20 +00001365
1366 // trunc(p)-trunc(q) -> trunc(p-q)
Chris Lattnerc93843f2010-01-01 22:29:12 +00001367 if (match(Op0, m_Trunc(m_PtrToInt(m_Value(LHSOp)))) &&
1368 match(Op1, m_Trunc(m_PtrToInt(m_Value(RHSOp)))))
1369 if (Value *Res = OptimizePointerDifference(LHSOp, RHSOp, I.getType()))
1370 return ReplaceInstUsesWith(I, Res);
Chris Lattner93e6ff92009-11-04 08:05:20 +00001371 }
1372
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001373 return 0;
1374}
1375
Dan Gohman7ce405e2009-06-04 22:49:04 +00001376Instruction *InstCombiner::visitFSub(BinaryOperator &I) {
1377 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1378
1379 // If this is a 'B = x-(-A)', change to B = x+A...
Dan Gohmanfe91cd62009-08-12 16:04:34 +00001380 if (Value *V = dyn_castFNegVal(Op1))
Dan Gohman7ce405e2009-06-04 22:49:04 +00001381 return BinaryOperator::CreateFAdd(Op0, V);
1382
1383 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
1384 if (Op1I->getOpcode() == Instruction::FAdd) {
1385 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
Dan Gohmancdff2122009-08-12 16:23:25 +00001386 return BinaryOperator::CreateFNeg(Op1I->getOperand(1),
Owen Anderson15b39322009-07-13 04:09:18 +00001387 I.getName());
Dan Gohman7ce405e2009-06-04 22:49:04 +00001388 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
Dan Gohmancdff2122009-08-12 16:23:25 +00001389 return BinaryOperator::CreateFNeg(Op1I->getOperand(0),
Owen Anderson15b39322009-07-13 04:09:18 +00001390 I.getName());
Dan Gohman7ce405e2009-06-04 22:49:04 +00001391 }
Dan Gohman7ce405e2009-06-04 22:49:04 +00001392 }
1393
1394 return 0;
1395}
1396
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001397Instruction *InstCombiner::visitMul(BinaryOperator &I) {
1398 bool Changed = SimplifyCommutative(I);
Chris Lattner3508c5c2009-10-11 21:36:10 +00001399 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001400
Chris Lattner3508c5c2009-10-11 21:36:10 +00001401 if (isa<UndefValue>(Op1)) // undef * X -> 0
Owen Andersonaac28372009-07-31 20:28:14 +00001402 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001403
Chris Lattner6438c582009-10-11 07:53:15 +00001404 // Simplify mul instructions with a constant RHS.
Chris Lattner3508c5c2009-10-11 21:36:10 +00001405 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
1406 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1C)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001407
1408 // ((X << C1)*C2) == (X * (C2 << C1))
1409 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op0))
1410 if (SI->getOpcode() == Instruction::Shl)
1411 if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
Gabor Greifa645dd32008-05-16 19:29:10 +00001412 return BinaryOperator::CreateMul(SI->getOperand(0),
Owen Anderson02b48c32009-07-29 18:55:55 +00001413 ConstantExpr::getShl(CI, ShOp));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001414
1415 if (CI->isZero())
Chris Lattner3508c5c2009-10-11 21:36:10 +00001416 return ReplaceInstUsesWith(I, Op1C); // X * 0 == 0
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001417 if (CI->equalsInt(1)) // X * 1 == X
1418 return ReplaceInstUsesWith(I, Op0);
1419 if (CI->isAllOnesValue()) // X * -1 == 0 - X
Dan Gohmancdff2122009-08-12 16:23:25 +00001420 return BinaryOperator::CreateNeg(Op0, I.getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001421
1422 const APInt& Val = cast<ConstantInt>(CI)->getValue();
1423 if (Val.isPowerOf2()) { // Replace X*(2^C) with X << C
Gabor Greifa645dd32008-05-16 19:29:10 +00001424 return BinaryOperator::CreateShl(Op0,
Owen Andersoneacb44d2009-07-24 23:12:02 +00001425 ConstantInt::get(Op0->getType(), Val.logBase2()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001426 }
Chris Lattner3508c5c2009-10-11 21:36:10 +00001427 } else if (isa<VectorType>(Op1C->getType())) {
1428 if (Op1C->isNullValue())
1429 return ReplaceInstUsesWith(I, Op1C);
Nick Lewycky94418732008-11-27 20:21:08 +00001430
Chris Lattner3508c5c2009-10-11 21:36:10 +00001431 if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1C)) {
Nick Lewycky94418732008-11-27 20:21:08 +00001432 if (Op1V->isAllOnesValue()) // X * -1 == 0 - X
Dan Gohmancdff2122009-08-12 16:23:25 +00001433 return BinaryOperator::CreateNeg(Op0, I.getName());
Nick Lewycky94418732008-11-27 20:21:08 +00001434
1435 // As above, vector X*splat(1.0) -> X in all defined cases.
1436 if (Constant *Splat = Op1V->getSplatValue()) {
Nick Lewycky94418732008-11-27 20:21:08 +00001437 if (ConstantInt *CI = dyn_cast<ConstantInt>(Splat))
1438 if (CI->equalsInt(1))
1439 return ReplaceInstUsesWith(I, Op0);
1440 }
1441 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001442 }
1443
1444 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
1445 if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
Chris Lattner3508c5c2009-10-11 21:36:10 +00001446 isa<ConstantInt>(Op0I->getOperand(1)) && isa<ConstantInt>(Op1C)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001447 // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
Chris Lattner3508c5c2009-10-11 21:36:10 +00001448 Value *Add = Builder->CreateMul(Op0I->getOperand(0), Op1C, "tmp");
1449 Value *C1C2 = Builder->CreateMul(Op1C, Op0I->getOperand(1));
Gabor Greifa645dd32008-05-16 19:29:10 +00001450 return BinaryOperator::CreateAdd(Add, C1C2);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001451
1452 }
1453
1454 // Try to fold constant mul into select arguments.
1455 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
1456 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
1457 return R;
1458
1459 if (isa<PHINode>(Op0))
1460 if (Instruction *NV = FoldOpIntoPhi(I))
1461 return NV;
1462 }
1463
Dan Gohmanfe91cd62009-08-12 16:04:34 +00001464 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
Chris Lattner3508c5c2009-10-11 21:36:10 +00001465 if (Value *Op1v = dyn_castNegVal(Op1))
Gabor Greifa645dd32008-05-16 19:29:10 +00001466 return BinaryOperator::CreateMul(Op0v, Op1v);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001467
Nick Lewycky1c246402008-11-21 07:33:58 +00001468 // (X / Y) * Y = X - (X % Y)
1469 // (X / Y) * -Y = (X % Y) - X
1470 {
Chris Lattner3508c5c2009-10-11 21:36:10 +00001471 Value *Op1C = Op1;
Nick Lewycky1c246402008-11-21 07:33:58 +00001472 BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0);
1473 if (!BO ||
1474 (BO->getOpcode() != Instruction::UDiv &&
1475 BO->getOpcode() != Instruction::SDiv)) {
Chris Lattner3508c5c2009-10-11 21:36:10 +00001476 Op1C = Op0;
1477 BO = dyn_cast<BinaryOperator>(Op1);
Nick Lewycky1c246402008-11-21 07:33:58 +00001478 }
Chris Lattner3508c5c2009-10-11 21:36:10 +00001479 Value *Neg = dyn_castNegVal(Op1C);
Nick Lewycky1c246402008-11-21 07:33:58 +00001480 if (BO && BO->hasOneUse() &&
Chris Lattner3508c5c2009-10-11 21:36:10 +00001481 (BO->getOperand(1) == Op1C || BO->getOperand(1) == Neg) &&
Nick Lewycky1c246402008-11-21 07:33:58 +00001482 (BO->getOpcode() == Instruction::UDiv ||
1483 BO->getOpcode() == Instruction::SDiv)) {
1484 Value *Op0BO = BO->getOperand(0), *Op1BO = BO->getOperand(1);
1485
Dan Gohman07878902009-08-12 16:33:09 +00001486 // If the division is exact, X % Y is zero.
1487 if (SDivOperator *SDiv = dyn_cast<SDivOperator>(BO))
1488 if (SDiv->isExact()) {
Chris Lattner3508c5c2009-10-11 21:36:10 +00001489 if (Op1BO == Op1C)
Dan Gohman07878902009-08-12 16:33:09 +00001490 return ReplaceInstUsesWith(I, Op0BO);
Chris Lattner3508c5c2009-10-11 21:36:10 +00001491 return BinaryOperator::CreateNeg(Op0BO);
Dan Gohman07878902009-08-12 16:33:09 +00001492 }
1493
Chris Lattnerc7694852009-08-30 07:44:24 +00001494 Value *Rem;
Nick Lewycky1c246402008-11-21 07:33:58 +00001495 if (BO->getOpcode() == Instruction::UDiv)
Chris Lattnerc7694852009-08-30 07:44:24 +00001496 Rem = Builder->CreateURem(Op0BO, Op1BO);
Nick Lewycky1c246402008-11-21 07:33:58 +00001497 else
Chris Lattnerc7694852009-08-30 07:44:24 +00001498 Rem = Builder->CreateSRem(Op0BO, Op1BO);
Nick Lewycky1c246402008-11-21 07:33:58 +00001499 Rem->takeName(BO);
1500
Chris Lattner3508c5c2009-10-11 21:36:10 +00001501 if (Op1BO == Op1C)
Nick Lewycky1c246402008-11-21 07:33:58 +00001502 return BinaryOperator::CreateSub(Op0BO, Rem);
Chris Lattnerc7694852009-08-30 07:44:24 +00001503 return BinaryOperator::CreateSub(Rem, Op0BO);
Nick Lewycky1c246402008-11-21 07:33:58 +00001504 }
1505 }
1506
Chris Lattner6438c582009-10-11 07:53:15 +00001507 /// i1 mul -> i1 and.
Chris Lattner03a27b42010-01-04 07:02:48 +00001508 if (I.getType() == Type::getInt1Ty(I.getContext()))
Chris Lattner3508c5c2009-10-11 21:36:10 +00001509 return BinaryOperator::CreateAnd(Op0, Op1);
Nick Lewyckyd4b63672008-05-31 17:59:52 +00001510
Chris Lattner6438c582009-10-11 07:53:15 +00001511 // X*(1 << Y) --> X << Y
1512 // (1 << Y)*X --> X << Y
1513 {
1514 Value *Y;
1515 if (match(Op0, m_Shl(m_One(), m_Value(Y))))
Chris Lattner3508c5c2009-10-11 21:36:10 +00001516 return BinaryOperator::CreateShl(Op1, Y);
1517 if (match(Op1, m_Shl(m_One(), m_Value(Y))))
Chris Lattner6438c582009-10-11 07:53:15 +00001518 return BinaryOperator::CreateShl(Op0, Y);
1519 }
1520
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001521 // If one of the operands of the multiply is a cast from a boolean value, then
1522 // we know the bool is either zero or one, so this is a 'masking' multiply.
Chris Lattner4ca76f72009-10-11 21:29:45 +00001523 // X * Y (where Y is 0 or 1) -> X & (0-Y)
1524 if (!isa<VectorType>(I.getType())) {
1525 // -2 is "-1 << 1" so it is all bits set except the low one.
Dale Johannesenb5887062009-10-12 18:45:32 +00001526 APInt Negative2(I.getType()->getPrimitiveSizeInBits(), (uint64_t)-2, true);
Chris Lattner291872e2009-10-11 21:22:21 +00001527
Chris Lattner4ca76f72009-10-11 21:29:45 +00001528 Value *BoolCast = 0, *OtherOp = 0;
1529 if (MaskedValueIsZero(Op0, Negative2))
Chris Lattner3508c5c2009-10-11 21:36:10 +00001530 BoolCast = Op0, OtherOp = Op1;
1531 else if (MaskedValueIsZero(Op1, Negative2))
1532 BoolCast = Op1, OtherOp = Op0;
Chris Lattner4ca76f72009-10-11 21:29:45 +00001533
Chris Lattner291872e2009-10-11 21:22:21 +00001534 if (BoolCast) {
Chris Lattner291872e2009-10-11 21:22:21 +00001535 Value *V = Builder->CreateSub(Constant::getNullValue(I.getType()),
1536 BoolCast, "tmp");
1537 return BinaryOperator::CreateAnd(V, OtherOp);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001538 }
1539 }
1540
1541 return Changed ? &I : 0;
1542}
1543
Dan Gohman7ce405e2009-06-04 22:49:04 +00001544Instruction *InstCombiner::visitFMul(BinaryOperator &I) {
1545 bool Changed = SimplifyCommutative(I);
Chris Lattner3508c5c2009-10-11 21:36:10 +00001546 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Dan Gohman7ce405e2009-06-04 22:49:04 +00001547
1548 // Simplify mul instructions with a constant RHS...
Chris Lattner3508c5c2009-10-11 21:36:10 +00001549 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
1550 if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1C)) {
Dan Gohman7ce405e2009-06-04 22:49:04 +00001551 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
1552 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
1553 if (Op1F->isExactlyValue(1.0))
1554 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0'
Chris Lattner3508c5c2009-10-11 21:36:10 +00001555 } else if (isa<VectorType>(Op1C->getType())) {
1556 if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1C)) {
Dan Gohman7ce405e2009-06-04 22:49:04 +00001557 // As above, vector X*splat(1.0) -> X in all defined cases.
1558 if (Constant *Splat = Op1V->getSplatValue()) {
1559 if (ConstantFP *F = dyn_cast<ConstantFP>(Splat))
1560 if (F->isExactlyValue(1.0))
1561 return ReplaceInstUsesWith(I, Op0);
1562 }
1563 }
1564 }
1565
1566 // Try to fold constant mul into select arguments.
1567 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
1568 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
1569 return R;
1570
1571 if (isa<PHINode>(Op0))
1572 if (Instruction *NV = FoldOpIntoPhi(I))
1573 return NV;
1574 }
1575
Dan Gohmanfe91cd62009-08-12 16:04:34 +00001576 if (Value *Op0v = dyn_castFNegVal(Op0)) // -X * -Y = X*Y
Chris Lattner3508c5c2009-10-11 21:36:10 +00001577 if (Value *Op1v = dyn_castFNegVal(Op1))
Dan Gohman7ce405e2009-06-04 22:49:04 +00001578 return BinaryOperator::CreateFMul(Op0v, Op1v);
1579
1580 return Changed ? &I : 0;
1581}
1582
Chris Lattner76972db2008-07-14 00:15:52 +00001583/// SimplifyDivRemOfSelect - Try to fold a divide or remainder of a select
1584/// instruction.
1585bool InstCombiner::SimplifyDivRemOfSelect(BinaryOperator &I) {
1586 SelectInst *SI = cast<SelectInst>(I.getOperand(1));
1587
1588 // div/rem X, (Cond ? 0 : Y) -> div/rem X, Y
1589 int NonNullOperand = -1;
1590 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
1591 if (ST->isNullValue())
1592 NonNullOperand = 2;
1593 // div/rem X, (Cond ? Y : 0) -> div/rem X, Y
1594 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
1595 if (ST->isNullValue())
1596 NonNullOperand = 1;
1597
1598 if (NonNullOperand == -1)
1599 return false;
1600
1601 Value *SelectCond = SI->getOperand(0);
1602
1603 // Change the div/rem to use 'Y' instead of the select.
1604 I.setOperand(1, SI->getOperand(NonNullOperand));
1605
1606 // Okay, we know we replace the operand of the div/rem with 'Y' with no
1607 // problem. However, the select, or the condition of the select may have
1608 // multiple uses. Based on our knowledge that the operand must be non-zero,
1609 // propagate the known value for the select into other uses of it, and
1610 // propagate a known value of the condition into its other users.
1611
1612 // If the select and condition only have a single use, don't bother with this,
1613 // early exit.
1614 if (SI->use_empty() && SelectCond->hasOneUse())
1615 return true;
1616
1617 // Scan the current block backward, looking for other uses of SI.
1618 BasicBlock::iterator BBI = &I, BBFront = I.getParent()->begin();
1619
1620 while (BBI != BBFront) {
1621 --BBI;
1622 // If we found a call to a function, we can't assume it will return, so
1623 // information from below it cannot be propagated above it.
1624 if (isa<CallInst>(BBI) && !isa<IntrinsicInst>(BBI))
1625 break;
1626
1627 // Replace uses of the select or its condition with the known values.
1628 for (Instruction::op_iterator I = BBI->op_begin(), E = BBI->op_end();
1629 I != E; ++I) {
1630 if (*I == SI) {
1631 *I = SI->getOperand(NonNullOperand);
Chris Lattner3183fb62009-08-30 06:13:40 +00001632 Worklist.Add(BBI);
Chris Lattner76972db2008-07-14 00:15:52 +00001633 } else if (*I == SelectCond) {
Chris Lattner03a27b42010-01-04 07:02:48 +00001634 *I = NonNullOperand == 1 ? ConstantInt::getTrue(BBI->getContext()) :
1635 ConstantInt::getFalse(BBI->getContext());
Chris Lattner3183fb62009-08-30 06:13:40 +00001636 Worklist.Add(BBI);
Chris Lattner76972db2008-07-14 00:15:52 +00001637 }
1638 }
1639
1640 // If we past the instruction, quit looking for it.
1641 if (&*BBI == SI)
1642 SI = 0;
1643 if (&*BBI == SelectCond)
1644 SelectCond = 0;
1645
1646 // If we ran out of things to eliminate, break out of the loop.
1647 if (SelectCond == 0 && SI == 0)
1648 break;
1649
1650 }
1651 return true;
1652}
1653
1654
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001655/// This function implements the transforms on div instructions that work
1656/// regardless of the kind of div instruction it is (udiv, sdiv, or fdiv). It is
1657/// used by the visitors to those instructions.
1658/// @brief Transforms common to all three div instructions
1659Instruction *InstCombiner::commonDivTransforms(BinaryOperator &I) {
1660 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1661
Chris Lattner653ef3c2008-02-19 06:12:18 +00001662 // undef / X -> 0 for integer.
1663 // undef / X -> undef for FP (the undef could be a snan).
1664 if (isa<UndefValue>(Op0)) {
1665 if (Op0->getType()->isFPOrFPVector())
1666 return ReplaceInstUsesWith(I, Op0);
Owen Andersonaac28372009-07-31 20:28:14 +00001667 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner653ef3c2008-02-19 06:12:18 +00001668 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001669
1670 // X / undef -> undef
1671 if (isa<UndefValue>(Op1))
1672 return ReplaceInstUsesWith(I, Op1);
1673
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001674 return 0;
1675}
1676
1677/// This function implements the transforms common to both integer division
1678/// instructions (udiv and sdiv). It is called by the visitors to those integer
1679/// division instructions.
1680/// @brief Common integer divide transforms
1681Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
1682 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1683
Chris Lattnercefb36c2008-05-16 02:59:42 +00001684 // (sdiv X, X) --> 1 (udiv X, X) --> 1
Nick Lewycky386c0132008-05-23 03:26:47 +00001685 if (Op0 == Op1) {
1686 if (const VectorType *Ty = dyn_cast<VectorType>(I.getType())) {
Owen Andersoneacb44d2009-07-24 23:12:02 +00001687 Constant *CI = ConstantInt::get(Ty->getElementType(), 1);
Nick Lewycky386c0132008-05-23 03:26:47 +00001688 std::vector<Constant*> Elts(Ty->getNumElements(), CI);
Owen Anderson2f422e02009-07-28 21:19:26 +00001689 return ReplaceInstUsesWith(I, ConstantVector::get(Elts));
Nick Lewycky386c0132008-05-23 03:26:47 +00001690 }
1691
Owen Andersoneacb44d2009-07-24 23:12:02 +00001692 Constant *CI = ConstantInt::get(I.getType(), 1);
Nick Lewycky386c0132008-05-23 03:26:47 +00001693 return ReplaceInstUsesWith(I, CI);
1694 }
Chris Lattnercefb36c2008-05-16 02:59:42 +00001695
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001696 if (Instruction *Common = commonDivTransforms(I))
1697 return Common;
Chris Lattner76972db2008-07-14 00:15:52 +00001698
1699 // Handle cases involving: [su]div X, (select Cond, Y, Z)
1700 // This does not apply for fdiv.
1701 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
1702 return &I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001703
1704 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
1705 // div X, 1 == X
1706 if (RHS->equalsInt(1))
1707 return ReplaceInstUsesWith(I, Op0);
1708
1709 // (X / C1) / C2 -> X / (C1*C2)
1710 if (Instruction *LHS = dyn_cast<Instruction>(Op0))
1711 if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
1712 if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
Owen Anderson24be4c12009-07-03 00:17:18 +00001713 if (MultiplyOverflows(RHS, LHSRHS,
Dan Gohmanfe91cd62009-08-12 16:04:34 +00001714 I.getOpcode()==Instruction::SDiv))
Owen Andersonaac28372009-07-31 20:28:14 +00001715 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Nick Lewycky9d798f92008-02-18 22:48:05 +00001716 else
Gabor Greifa645dd32008-05-16 19:29:10 +00001717 return BinaryOperator::Create(I.getOpcode(), LHS->getOperand(0),
Owen Anderson02b48c32009-07-29 18:55:55 +00001718 ConstantExpr::getMul(RHS, LHSRHS));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001719 }
1720
1721 if (!RHS->isZero()) { // avoid X udiv 0
1722 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
1723 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
1724 return R;
1725 if (isa<PHINode>(Op0))
1726 if (Instruction *NV = FoldOpIntoPhi(I))
1727 return NV;
1728 }
1729 }
1730
1731 // 0 / X == 0, we don't need to preserve faults!
1732 if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
1733 if (LHS->equalsInt(0))
Owen Andersonaac28372009-07-31 20:28:14 +00001734 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001735
Nick Lewyckyd4b63672008-05-31 17:59:52 +00001736 // It can't be division by zero, hence it must be division by one.
Chris Lattner03a27b42010-01-04 07:02:48 +00001737 if (I.getType() == Type::getInt1Ty(I.getContext()))
Nick Lewyckyd4b63672008-05-31 17:59:52 +00001738 return ReplaceInstUsesWith(I, Op0);
1739
Nick Lewycky94418732008-11-27 20:21:08 +00001740 if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
1741 if (ConstantInt *X = cast_or_null<ConstantInt>(Op1V->getSplatValue()))
1742 // div X, 1 == X
1743 if (X->isOne())
1744 return ReplaceInstUsesWith(I, Op0);
1745 }
1746
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001747 return 0;
1748}
1749
1750Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
1751 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1752
1753 // Handle the integer div common cases
1754 if (Instruction *Common = commonIDivTransforms(I))
1755 return Common;
1756
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001757 if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
Nick Lewycky240182a2008-11-27 22:41:10 +00001758 // X udiv C^2 -> X >> C
1759 // Check to see if this is an unsigned division with an exact power of 2,
1760 // if so, convert to a right shift.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001761 if (C->getValue().isPowerOf2()) // 0 not included in isPowerOf2
Gabor Greifa645dd32008-05-16 19:29:10 +00001762 return BinaryOperator::CreateLShr(Op0,
Owen Andersoneacb44d2009-07-24 23:12:02 +00001763 ConstantInt::get(Op0->getType(), C->getValue().logBase2()));
Nick Lewycky240182a2008-11-27 22:41:10 +00001764
1765 // X udiv C, where C >= signbit
1766 if (C->getValue().isNegative()) {
Chris Lattnerc7694852009-08-30 07:44:24 +00001767 Value *IC = Builder->CreateICmpULT( Op0, C);
Owen Andersonaac28372009-07-31 20:28:14 +00001768 return SelectInst::Create(IC, Constant::getNullValue(I.getType()),
Owen Andersoneacb44d2009-07-24 23:12:02 +00001769 ConstantInt::get(I.getType(), 1));
Nick Lewycky240182a2008-11-27 22:41:10 +00001770 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001771 }
1772
1773 // X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2)
1774 if (BinaryOperator *RHSI = dyn_cast<BinaryOperator>(I.getOperand(1))) {
1775 if (RHSI->getOpcode() == Instruction::Shl &&
1776 isa<ConstantInt>(RHSI->getOperand(0))) {
1777 const APInt& C1 = cast<ConstantInt>(RHSI->getOperand(0))->getValue();
1778 if (C1.isPowerOf2()) {
1779 Value *N = RHSI->getOperand(1);
1780 const Type *NTy = N->getType();
Chris Lattnerc7694852009-08-30 07:44:24 +00001781 if (uint32_t C2 = C1.logBase2())
1782 N = Builder->CreateAdd(N, ConstantInt::get(NTy, C2), "tmp");
Gabor Greifa645dd32008-05-16 19:29:10 +00001783 return BinaryOperator::CreateLShr(Op0, N);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001784 }
1785 }
1786 }
1787
1788 // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
1789 // where C1&C2 are powers of two.
1790 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
1791 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
1792 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
1793 const APInt &TVA = STO->getValue(), &FVA = SFO->getValue();
1794 if (TVA.isPowerOf2() && FVA.isPowerOf2()) {
1795 // Compute the shift amounts
1796 uint32_t TSA = TVA.logBase2(), FSA = FVA.logBase2();
1797 // Construct the "on true" case of the select
Owen Andersoneacb44d2009-07-24 23:12:02 +00001798 Constant *TC = ConstantInt::get(Op0->getType(), TSA);
Chris Lattnerc7694852009-08-30 07:44:24 +00001799 Value *TSI = Builder->CreateLShr(Op0, TC, SI->getName()+".t");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001800
1801 // Construct the "on false" case of the select
Owen Andersoneacb44d2009-07-24 23:12:02 +00001802 Constant *FC = ConstantInt::get(Op0->getType(), FSA);
Chris Lattnerc7694852009-08-30 07:44:24 +00001803 Value *FSI = Builder->CreateLShr(Op0, FC, SI->getName()+".f");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001804
1805 // construct the select instruction and return it.
Gabor Greifd6da1d02008-04-06 20:25:17 +00001806 return SelectInst::Create(SI->getOperand(0), TSI, FSI, SI->getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001807 }
1808 }
1809 return 0;
1810}
1811
1812Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
1813 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1814
1815 // Handle the integer div common cases
1816 if (Instruction *Common = commonIDivTransforms(I))
1817 return Common;
1818
1819 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
1820 // sdiv X, -1 == -X
1821 if (RHS->isAllOnesValue())
Dan Gohmancdff2122009-08-12 16:23:25 +00001822 return BinaryOperator::CreateNeg(Op0);
Dan Gohman31b6b132009-08-11 20:47:47 +00001823
Dan Gohman07878902009-08-12 16:33:09 +00001824 // sdiv X, C --> ashr X, log2(C)
Dan Gohman31b6b132009-08-11 20:47:47 +00001825 if (cast<SDivOperator>(&I)->isExact() &&
1826 RHS->getValue().isNonNegative() &&
1827 RHS->getValue().isPowerOf2()) {
1828 Value *ShAmt = llvm::ConstantInt::get(RHS->getType(),
1829 RHS->getValue().exactLogBase2());
1830 return BinaryOperator::CreateAShr(Op0, ShAmt, I.getName());
1831 }
Dan Gohman5ce93b32009-08-12 16:37:02 +00001832
1833 // -X/C --> X/-C provided the negation doesn't overflow.
1834 if (SubOperator *Sub = dyn_cast<SubOperator>(Op0))
1835 if (isa<Constant>(Sub->getOperand(0)) &&
1836 cast<Constant>(Sub->getOperand(0))->isNullValue() &&
Dan Gohmanb5ed4492009-08-20 17:11:38 +00001837 Sub->hasNoSignedWrap())
Dan Gohman5ce93b32009-08-12 16:37:02 +00001838 return BinaryOperator::CreateSDiv(Sub->getOperand(1),
1839 ConstantExpr::getNeg(RHS));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001840 }
1841
1842 // If the sign bits of both operands are zero (i.e. we can prove they are
1843 // unsigned inputs), turn this into a udiv.
1844 if (I.getType()->isInteger()) {
1845 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
Eli Friedmana17b85f2009-07-18 09:53:21 +00001846 if (MaskedValueIsZero(Op0, Mask)) {
1847 if (MaskedValueIsZero(Op1, Mask)) {
1848 // X sdiv Y -> X udiv Y, iff X and Y don't have sign bit set
1849 return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
1850 }
1851 ConstantInt *ShiftedInt;
Dan Gohmancdff2122009-08-12 16:23:25 +00001852 if (match(Op1, m_Shl(m_ConstantInt(ShiftedInt), m_Value())) &&
Eli Friedmana17b85f2009-07-18 09:53:21 +00001853 ShiftedInt->getValue().isPowerOf2()) {
1854 // X sdiv (1 << Y) -> X udiv (1 << Y) ( -> X u>> Y)
1855 // Safe because the only negative value (1 << Y) can take on is
1856 // INT_MIN, and X sdiv INT_MIN == X udiv INT_MIN == 0 if X doesn't have
1857 // the sign bit set.
1858 return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
1859 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001860 }
Eli Friedmana17b85f2009-07-18 09:53:21 +00001861 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001862
1863 return 0;
1864}
1865
1866Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
1867 return commonDivTransforms(I);
1868}
1869
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001870/// This function implements the transforms on rem instructions that work
1871/// regardless of the kind of rem instruction it is (urem, srem, or frem). It
1872/// is used by the visitors to those instructions.
1873/// @brief Transforms common to all three rem instructions
1874Instruction *InstCombiner::commonRemTransforms(BinaryOperator &I) {
1875 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1876
Chris Lattner653ef3c2008-02-19 06:12:18 +00001877 if (isa<UndefValue>(Op0)) { // undef % X -> 0
1878 if (I.getType()->isFPOrFPVector())
1879 return ReplaceInstUsesWith(I, Op0); // X % undef -> undef (could be SNaN)
Owen Andersonaac28372009-07-31 20:28:14 +00001880 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner653ef3c2008-02-19 06:12:18 +00001881 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001882 if (isa<UndefValue>(Op1))
1883 return ReplaceInstUsesWith(I, Op1); // X % undef -> undef
1884
1885 // Handle cases involving: rem X, (select Cond, Y, Z)
Chris Lattner76972db2008-07-14 00:15:52 +00001886 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
1887 return &I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001888
1889 return 0;
1890}
1891
1892/// This function implements the transforms common to both integer remainder
1893/// instructions (urem and srem). It is called by the visitors to those integer
1894/// remainder instructions.
1895/// @brief Common integer remainder transforms
1896Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
1897 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1898
1899 if (Instruction *common = commonRemTransforms(I))
1900 return common;
1901
Dale Johannesena51f7372009-01-21 00:35:19 +00001902 // 0 % X == 0 for integer, we don't need to preserve faults!
1903 if (Constant *LHS = dyn_cast<Constant>(Op0))
1904 if (LHS->isNullValue())
Owen Andersonaac28372009-07-31 20:28:14 +00001905 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Dale Johannesena51f7372009-01-21 00:35:19 +00001906
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001907 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
1908 // X % 0 == undef, we don't need to preserve faults!
1909 if (RHS->equalsInt(0))
Owen Andersonb99ecca2009-07-30 23:03:37 +00001910 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001911
1912 if (RHS->equalsInt(1)) // X % 1 == 0
Owen Andersonaac28372009-07-31 20:28:14 +00001913 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001914
1915 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
1916 if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
1917 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
1918 return R;
1919 } else if (isa<PHINode>(Op0I)) {
1920 if (Instruction *NV = FoldOpIntoPhi(I))
1921 return NV;
1922 }
Nick Lewyckyc1372c82008-03-06 06:48:30 +00001923
1924 // See if we can fold away this rem instruction.
Chris Lattner676c78e2009-01-31 08:15:18 +00001925 if (SimplifyDemandedInstructionBits(I))
Nick Lewyckyc1372c82008-03-06 06:48:30 +00001926 return &I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001927 }
1928 }
1929
1930 return 0;
1931}
1932
1933Instruction *InstCombiner::visitURem(BinaryOperator &I) {
1934 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1935
1936 if (Instruction *common = commonIRemTransforms(I))
1937 return common;
1938
1939 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
1940 // X urem C^2 -> X and C
1941 // Check to see if this is an unsigned remainder with an exact power of 2,
1942 // if so, convert to a bitwise and.
1943 if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
1944 if (C->getValue().isPowerOf2())
Dan Gohmanfe91cd62009-08-12 16:04:34 +00001945 return BinaryOperator::CreateAnd(Op0, SubOne(C));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001946 }
1947
1948 if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
1949 // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)
1950 if (RHSI->getOpcode() == Instruction::Shl &&
1951 isa<ConstantInt>(RHSI->getOperand(0))) {
1952 if (cast<ConstantInt>(RHSI->getOperand(0))->getValue().isPowerOf2()) {
Owen Andersonaac28372009-07-31 20:28:14 +00001953 Constant *N1 = Constant::getAllOnesValue(I.getType());
Chris Lattnerc7694852009-08-30 07:44:24 +00001954 Value *Add = Builder->CreateAdd(RHSI, N1, "tmp");
Gabor Greifa645dd32008-05-16 19:29:10 +00001955 return BinaryOperator::CreateAnd(Op0, Add);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001956 }
1957 }
1958 }
1959
1960 // urem X, (select Cond, 2^C1, 2^C2) --> select Cond, (and X, C1), (and X, C2)
1961 // where C1&C2 are powers of two.
1962 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
1963 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
1964 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
1965 // STO == 0 and SFO == 0 handled above.
1966 if ((STO->getValue().isPowerOf2()) &&
1967 (SFO->getValue().isPowerOf2())) {
Chris Lattnerc7694852009-08-30 07:44:24 +00001968 Value *TrueAnd = Builder->CreateAnd(Op0, SubOne(STO),
1969 SI->getName()+".t");
1970 Value *FalseAnd = Builder->CreateAnd(Op0, SubOne(SFO),
1971 SI->getName()+".f");
Gabor Greifd6da1d02008-04-06 20:25:17 +00001972 return SelectInst::Create(SI->getOperand(0), TrueAnd, FalseAnd);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001973 }
1974 }
1975 }
1976
1977 return 0;
1978}
1979
1980Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
1981 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1982
Dan Gohmandb3dd962007-11-05 23:16:33 +00001983 // Handle the integer rem common cases
Chris Lattner4796b622009-08-30 06:22:51 +00001984 if (Instruction *Common = commonIRemTransforms(I))
1985 return Common;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001986
Dan Gohmanfe91cd62009-08-12 16:04:34 +00001987 if (Value *RHSNeg = dyn_castNegVal(Op1))
Nick Lewyckycfadfbd2008-09-03 06:24:21 +00001988 if (!isa<Constant>(RHSNeg) ||
1989 (isa<ConstantInt>(RHSNeg) &&
1990 cast<ConstantInt>(RHSNeg)->getValue().isStrictlyPositive())) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001991 // X % -Y -> X % Y
Chris Lattnerc5ad98f2009-08-30 06:27:41 +00001992 Worklist.AddValue(I.getOperand(1));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001993 I.setOperand(1, RHSNeg);
1994 return &I;
1995 }
Nick Lewycky5515c7a2008-09-30 06:08:34 +00001996
Dan Gohmandb3dd962007-11-05 23:16:33 +00001997 // If the sign bits of both operands are zero (i.e. we can prove they are
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001998 // unsigned inputs), turn this into a urem.
Dan Gohmandb3dd962007-11-05 23:16:33 +00001999 if (I.getType()->isInteger()) {
2000 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
2001 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
2002 // X srem Y -> X urem Y, iff X and Y don't have sign bit set
Gabor Greifa645dd32008-05-16 19:29:10 +00002003 return BinaryOperator::CreateURem(Op0, Op1, I.getName());
Dan Gohmandb3dd962007-11-05 23:16:33 +00002004 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002005 }
2006
Nick Lewyckyda9fa432008-12-18 06:31:11 +00002007 // If it's a constant vector, flip any negative values positive.
Nick Lewyckyfd746832008-12-20 16:48:00 +00002008 if (ConstantVector *RHSV = dyn_cast<ConstantVector>(Op1)) {
2009 unsigned VWidth = RHSV->getNumOperands();
Nick Lewyckyda9fa432008-12-18 06:31:11 +00002010
Nick Lewyckyfd746832008-12-20 16:48:00 +00002011 bool hasNegative = false;
2012 for (unsigned i = 0; !hasNegative && i != VWidth; ++i)
2013 if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i)))
2014 if (RHS->getValue().isNegative())
2015 hasNegative = true;
2016
2017 if (hasNegative) {
2018 std::vector<Constant *> Elts(VWidth);
Nick Lewyckyda9fa432008-12-18 06:31:11 +00002019 for (unsigned i = 0; i != VWidth; ++i) {
2020 if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i))) {
2021 if (RHS->getValue().isNegative())
Owen Anderson02b48c32009-07-29 18:55:55 +00002022 Elts[i] = cast<ConstantInt>(ConstantExpr::getNeg(RHS));
Nick Lewyckyda9fa432008-12-18 06:31:11 +00002023 else
2024 Elts[i] = RHS;
2025 }
2026 }
2027
Owen Anderson2f422e02009-07-28 21:19:26 +00002028 Constant *NewRHSV = ConstantVector::get(Elts);
Nick Lewyckyda9fa432008-12-18 06:31:11 +00002029 if (NewRHSV != RHSV) {
Chris Lattnerc5ad98f2009-08-30 06:27:41 +00002030 Worklist.AddValue(I.getOperand(1));
Nick Lewyckyda9fa432008-12-18 06:31:11 +00002031 I.setOperand(1, NewRHSV);
2032 return &I;
2033 }
2034 }
2035 }
2036
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002037 return 0;
2038}
2039
2040Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
2041 return commonRemTransforms(I);
2042}
2043
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002044// isOneBitSet - Return true if there is exactly one bit set in the specified
2045// constant.
2046static bool isOneBitSet(const ConstantInt *CI) {
2047 return CI->getValue().isPowerOf2();
2048}
2049
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002050/// getICmpCode - Encode a icmp predicate into a three bit mask. These bits
2051/// are carefully arranged to allow folding of expressions such as:
2052///
2053/// (A < B) | (A > B) --> (A != B)
2054///
2055/// Note that this is only valid if the first and second predicates have the
2056/// same sign. Is illegal to do: (A u< B) | (A s> B)
2057///
2058/// Three bits are used to represent the condition, as follows:
2059/// 0 A > B
2060/// 1 A == B
2061/// 2 A < B
2062///
2063/// <=> Value Definition
2064/// 000 0 Always false
2065/// 001 1 A > B
2066/// 010 2 A == B
2067/// 011 3 A >= B
2068/// 100 4 A < B
2069/// 101 5 A != B
2070/// 110 6 A <= B
2071/// 111 7 Always true
2072///
2073static unsigned getICmpCode(const ICmpInst *ICI) {
2074 switch (ICI->getPredicate()) {
2075 // False -> 0
2076 case ICmpInst::ICMP_UGT: return 1; // 001
2077 case ICmpInst::ICMP_SGT: return 1; // 001
2078 case ICmpInst::ICMP_EQ: return 2; // 010
2079 case ICmpInst::ICMP_UGE: return 3; // 011
2080 case ICmpInst::ICMP_SGE: return 3; // 011
2081 case ICmpInst::ICMP_ULT: return 4; // 100
2082 case ICmpInst::ICMP_SLT: return 4; // 100
2083 case ICmpInst::ICMP_NE: return 5; // 101
2084 case ICmpInst::ICMP_ULE: return 6; // 110
2085 case ICmpInst::ICMP_SLE: return 6; // 110
2086 // True -> 7
2087 default:
Edwin Törökbd448e32009-07-14 16:55:14 +00002088 llvm_unreachable("Invalid ICmp predicate!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002089 return 0;
2090 }
2091}
2092
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00002093/// getFCmpCode - Similar to getICmpCode but for FCmpInst. This encodes a fcmp
2094/// predicate into a three bit mask. It also returns whether it is an ordered
2095/// predicate by reference.
2096static unsigned getFCmpCode(FCmpInst::Predicate CC, bool &isOrdered) {
2097 isOrdered = false;
2098 switch (CC) {
2099 case FCmpInst::FCMP_ORD: isOrdered = true; return 0; // 000
2100 case FCmpInst::FCMP_UNO: return 0; // 000
Evan Chengf1f2cea2008-10-14 18:13:38 +00002101 case FCmpInst::FCMP_OGT: isOrdered = true; return 1; // 001
2102 case FCmpInst::FCMP_UGT: return 1; // 001
2103 case FCmpInst::FCMP_OEQ: isOrdered = true; return 2; // 010
2104 case FCmpInst::FCMP_UEQ: return 2; // 010
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00002105 case FCmpInst::FCMP_OGE: isOrdered = true; return 3; // 011
2106 case FCmpInst::FCMP_UGE: return 3; // 011
2107 case FCmpInst::FCMP_OLT: isOrdered = true; return 4; // 100
2108 case FCmpInst::FCMP_ULT: return 4; // 100
Evan Chengf1f2cea2008-10-14 18:13:38 +00002109 case FCmpInst::FCMP_ONE: isOrdered = true; return 5; // 101
2110 case FCmpInst::FCMP_UNE: return 5; // 101
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00002111 case FCmpInst::FCMP_OLE: isOrdered = true; return 6; // 110
2112 case FCmpInst::FCMP_ULE: return 6; // 110
Evan Cheng72988052008-10-14 18:44:08 +00002113 // True -> 7
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00002114 default:
2115 // Not expecting FCMP_FALSE and FCMP_TRUE;
Edwin Törökbd448e32009-07-14 16:55:14 +00002116 llvm_unreachable("Unexpected FCmp predicate!");
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00002117 return 0;
2118 }
2119}
2120
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002121/// getICmpValue - This is the complement of getICmpCode, which turns an
2122/// opcode and two operands into either a constant true or false, or a brand
Dan Gohmanda338742007-09-17 17:31:57 +00002123/// new ICmp instruction. The sign is passed in to determine which kind
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00002124/// of predicate to use in the new icmp instruction.
Chris Lattner03a27b42010-01-04 07:02:48 +00002125static Value *getICmpValue(bool sign, unsigned code, Value *LHS, Value *RHS) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002126 switch (code) {
Edwin Törökbd448e32009-07-14 16:55:14 +00002127 default: llvm_unreachable("Illegal ICmp code!");
Chris Lattner03a27b42010-01-04 07:02:48 +00002128 case 0: return ConstantInt::getFalse(LHS->getContext());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002129 case 1:
2130 if (sign)
Dan Gohmane6803b82009-08-25 23:17:54 +00002131 return new ICmpInst(ICmpInst::ICMP_SGT, LHS, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002132 else
Dan Gohmane6803b82009-08-25 23:17:54 +00002133 return new ICmpInst(ICmpInst::ICMP_UGT, LHS, RHS);
2134 case 2: return new ICmpInst(ICmpInst::ICMP_EQ, LHS, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002135 case 3:
2136 if (sign)
Dan Gohmane6803b82009-08-25 23:17:54 +00002137 return new ICmpInst(ICmpInst::ICMP_SGE, LHS, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002138 else
Dan Gohmane6803b82009-08-25 23:17:54 +00002139 return new ICmpInst(ICmpInst::ICMP_UGE, LHS, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002140 case 4:
2141 if (sign)
Dan Gohmane6803b82009-08-25 23:17:54 +00002142 return new ICmpInst(ICmpInst::ICMP_SLT, LHS, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002143 else
Dan Gohmane6803b82009-08-25 23:17:54 +00002144 return new ICmpInst(ICmpInst::ICMP_ULT, LHS, RHS);
2145 case 5: return new ICmpInst(ICmpInst::ICMP_NE, LHS, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002146 case 6:
2147 if (sign)
Dan Gohmane6803b82009-08-25 23:17:54 +00002148 return new ICmpInst(ICmpInst::ICMP_SLE, LHS, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002149 else
Dan Gohmane6803b82009-08-25 23:17:54 +00002150 return new ICmpInst(ICmpInst::ICMP_ULE, LHS, RHS);
Chris Lattner03a27b42010-01-04 07:02:48 +00002151 case 7: return ConstantInt::getTrue(LHS->getContext());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002152 }
2153}
2154
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00002155/// getFCmpValue - This is the complement of getFCmpCode, which turns an
2156/// opcode and two operands into either a FCmp instruction. isordered is passed
2157/// in to determine which kind of predicate to use in the new fcmp instruction.
2158static Value *getFCmpValue(bool isordered, unsigned code,
Chris Lattner03a27b42010-01-04 07:02:48 +00002159 Value *LHS, Value *RHS) {
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00002160 switch (code) {
Edwin Törökbd448e32009-07-14 16:55:14 +00002161 default: llvm_unreachable("Illegal FCmp code!");
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00002162 case 0:
2163 if (isordered)
Dan Gohmane6803b82009-08-25 23:17:54 +00002164 return new FCmpInst(FCmpInst::FCMP_ORD, LHS, RHS);
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00002165 else
Dan Gohmane6803b82009-08-25 23:17:54 +00002166 return new FCmpInst(FCmpInst::FCMP_UNO, LHS, RHS);
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00002167 case 1:
2168 if (isordered)
Dan Gohmane6803b82009-08-25 23:17:54 +00002169 return new FCmpInst(FCmpInst::FCMP_OGT, LHS, RHS);
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00002170 else
Dan Gohmane6803b82009-08-25 23:17:54 +00002171 return new FCmpInst(FCmpInst::FCMP_UGT, LHS, RHS);
Evan Chengf1f2cea2008-10-14 18:13:38 +00002172 case 2:
2173 if (isordered)
Dan Gohmane6803b82009-08-25 23:17:54 +00002174 return new FCmpInst(FCmpInst::FCMP_OEQ, LHS, RHS);
Evan Chengf1f2cea2008-10-14 18:13:38 +00002175 else
Dan Gohmane6803b82009-08-25 23:17:54 +00002176 return new FCmpInst(FCmpInst::FCMP_UEQ, LHS, RHS);
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00002177 case 3:
2178 if (isordered)
Dan Gohmane6803b82009-08-25 23:17:54 +00002179 return new FCmpInst(FCmpInst::FCMP_OGE, LHS, RHS);
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00002180 else
Dan Gohmane6803b82009-08-25 23:17:54 +00002181 return new FCmpInst(FCmpInst::FCMP_UGE, LHS, RHS);
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00002182 case 4:
2183 if (isordered)
Dan Gohmane6803b82009-08-25 23:17:54 +00002184 return new FCmpInst(FCmpInst::FCMP_OLT, LHS, RHS);
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00002185 else
Dan Gohmane6803b82009-08-25 23:17:54 +00002186 return new FCmpInst(FCmpInst::FCMP_ULT, LHS, RHS);
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00002187 case 5:
2188 if (isordered)
Dan Gohmane6803b82009-08-25 23:17:54 +00002189 return new FCmpInst(FCmpInst::FCMP_ONE, LHS, RHS);
Evan Chengf1f2cea2008-10-14 18:13:38 +00002190 else
Dan Gohmane6803b82009-08-25 23:17:54 +00002191 return new FCmpInst(FCmpInst::FCMP_UNE, LHS, RHS);
Evan Chengf1f2cea2008-10-14 18:13:38 +00002192 case 6:
2193 if (isordered)
Dan Gohmane6803b82009-08-25 23:17:54 +00002194 return new FCmpInst(FCmpInst::FCMP_OLE, LHS, RHS);
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00002195 else
Dan Gohmane6803b82009-08-25 23:17:54 +00002196 return new FCmpInst(FCmpInst::FCMP_ULE, LHS, RHS);
Chris Lattner03a27b42010-01-04 07:02:48 +00002197 case 7: return ConstantInt::getTrue(LHS->getContext());
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00002198 }
2199}
2200
Chris Lattner2972b822008-11-16 04:55:20 +00002201/// PredicatesFoldable - Return true if both predicates match sign or if at
2202/// least one of them is an equality comparison (which is signless).
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002203static bool PredicatesFoldable(ICmpInst::Predicate p1, ICmpInst::Predicate p2) {
Nick Lewyckyb0796c62009-10-25 05:20:17 +00002204 return (CmpInst::isSigned(p1) == CmpInst::isSigned(p2)) ||
2205 (CmpInst::isSigned(p1) && ICmpInst::isEquality(p2)) ||
2206 (CmpInst::isSigned(p2) && ICmpInst::isEquality(p1));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002207}
2208
2209namespace {
2210// FoldICmpLogical - Implements (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
2211struct FoldICmpLogical {
2212 InstCombiner &IC;
2213 Value *LHS, *RHS;
2214 ICmpInst::Predicate pred;
2215 FoldICmpLogical(InstCombiner &ic, ICmpInst *ICI)
2216 : IC(ic), LHS(ICI->getOperand(0)), RHS(ICI->getOperand(1)),
2217 pred(ICI->getPredicate()) {}
2218 bool shouldApply(Value *V) const {
2219 if (ICmpInst *ICI = dyn_cast<ICmpInst>(V))
2220 if (PredicatesFoldable(pred, ICI->getPredicate()))
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00002221 return ((ICI->getOperand(0) == LHS && ICI->getOperand(1) == RHS) ||
2222 (ICI->getOperand(0) == RHS && ICI->getOperand(1) == LHS));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002223 return false;
2224 }
2225 Instruction *apply(Instruction &Log) const {
2226 ICmpInst *ICI = cast<ICmpInst>(Log.getOperand(0));
2227 if (ICI->getOperand(0) != LHS) {
2228 assert(ICI->getOperand(1) == LHS);
2229 ICI->swapOperands(); // Swap the LHS and RHS of the ICmp
2230 }
2231
2232 ICmpInst *RHSICI = cast<ICmpInst>(Log.getOperand(1));
2233 unsigned LHSCode = getICmpCode(ICI);
2234 unsigned RHSCode = getICmpCode(RHSICI);
2235 unsigned Code;
2236 switch (Log.getOpcode()) {
2237 case Instruction::And: Code = LHSCode & RHSCode; break;
2238 case Instruction::Or: Code = LHSCode | RHSCode; break;
2239 case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
Edwin Törökbd448e32009-07-14 16:55:14 +00002240 default: llvm_unreachable("Illegal logical opcode!"); return 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002241 }
2242
Nick Lewyckyb0796c62009-10-25 05:20:17 +00002243 bool isSigned = RHSICI->isSigned() || ICI->isSigned();
Chris Lattner03a27b42010-01-04 07:02:48 +00002244 Value *RV = getICmpValue(isSigned, Code, LHS, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002245 if (Instruction *I = dyn_cast<Instruction>(RV))
2246 return I;
2247 // Otherwise, it's a constant boolean value...
2248 return IC.ReplaceInstUsesWith(Log, RV);
2249 }
2250};
2251} // end anonymous namespace
2252
2253// OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
2254// the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
2255// guaranteed to be a binary operator.
2256Instruction *InstCombiner::OptAndOp(Instruction *Op,
2257 ConstantInt *OpRHS,
2258 ConstantInt *AndRHS,
2259 BinaryOperator &TheAnd) {
2260 Value *X = Op->getOperand(0);
2261 Constant *Together = 0;
2262 if (!Op->isShift())
Owen Anderson02b48c32009-07-29 18:55:55 +00002263 Together = ConstantExpr::getAnd(AndRHS, OpRHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002264
2265 switch (Op->getOpcode()) {
2266 case Instruction::Xor:
2267 if (Op->hasOneUse()) {
2268 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
Chris Lattnerc7694852009-08-30 07:44:24 +00002269 Value *And = Builder->CreateAnd(X, AndRHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002270 And->takeName(Op);
Gabor Greifa645dd32008-05-16 19:29:10 +00002271 return BinaryOperator::CreateXor(And, Together);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002272 }
2273 break;
2274 case Instruction::Or:
2275 if (Together == AndRHS) // (X | C) & C --> C
2276 return ReplaceInstUsesWith(TheAnd, AndRHS);
2277
2278 if (Op->hasOneUse() && Together != OpRHS) {
2279 // (X | C1) & C2 --> (X | (C1&C2)) & C2
Chris Lattnerc7694852009-08-30 07:44:24 +00002280 Value *Or = Builder->CreateOr(X, Together);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002281 Or->takeName(Op);
Gabor Greifa645dd32008-05-16 19:29:10 +00002282 return BinaryOperator::CreateAnd(Or, AndRHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002283 }
2284 break;
2285 case Instruction::Add:
2286 if (Op->hasOneUse()) {
2287 // Adding a one to a single bit bit-field should be turned into an XOR
2288 // of the bit. First thing to check is to see if this AND is with a
2289 // single bit constant.
2290 const APInt& AndRHSV = cast<ConstantInt>(AndRHS)->getValue();
2291
2292 // If there is only one bit set...
2293 if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
2294 // Ok, at this point, we know that we are masking the result of the
2295 // ADD down to exactly one bit. If the constant we are adding has
2296 // no bits set below this bit, then we can eliminate the ADD.
2297 const APInt& AddRHS = cast<ConstantInt>(OpRHS)->getValue();
2298
2299 // Check to see if any bits below the one bit set in AndRHSV are set.
2300 if ((AddRHS & (AndRHSV-1)) == 0) {
2301 // If not, the only thing that can effect the output of the AND is
2302 // the bit specified by AndRHSV. If that bit is set, the effect of
2303 // the XOR is to toggle the bit. If it is clear, then the ADD has
2304 // no effect.
2305 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
2306 TheAnd.setOperand(0, X);
2307 return &TheAnd;
2308 } else {
2309 // Pull the XOR out of the AND.
Chris Lattnerc7694852009-08-30 07:44:24 +00002310 Value *NewAnd = Builder->CreateAnd(X, AndRHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002311 NewAnd->takeName(Op);
Gabor Greifa645dd32008-05-16 19:29:10 +00002312 return BinaryOperator::CreateXor(NewAnd, AndRHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002313 }
2314 }
2315 }
2316 }
2317 break;
2318
2319 case Instruction::Shl: {
2320 // We know that the AND will not produce any of the bits shifted in, so if
2321 // the anded constant includes them, clear them now!
2322 //
2323 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
2324 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
2325 APInt ShlMask(APInt::getHighBitsSet(BitWidth, BitWidth-OpRHSVal));
Chris Lattner03a27b42010-01-04 07:02:48 +00002326 ConstantInt *CI = ConstantInt::get(AndRHS->getContext(),
2327 AndRHS->getValue() & ShlMask);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002328
2329 if (CI->getValue() == ShlMask) {
2330 // Masking out bits that the shift already masks
2331 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
2332 } else if (CI != AndRHS) { // Reducing bits set in and.
2333 TheAnd.setOperand(1, CI);
2334 return &TheAnd;
2335 }
2336 break;
2337 }
Chris Lattner03a27b42010-01-04 07:02:48 +00002338 case Instruction::LShr: {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002339 // We know that the AND will not produce any of the bits shifted in, so if
2340 // the anded constant includes them, clear them now! This only applies to
2341 // unsigned shifts, because a signed shr may bring in set bits!
2342 //
2343 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
2344 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
2345 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
Chris Lattner03a27b42010-01-04 07:02:48 +00002346 ConstantInt *CI = ConstantInt::get(Op->getContext(),
2347 AndRHS->getValue() & ShrMask);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002348
2349 if (CI->getValue() == ShrMask) {
2350 // Masking out bits that the shift already masks.
2351 return ReplaceInstUsesWith(TheAnd, Op);
2352 } else if (CI != AndRHS) {
2353 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
2354 return &TheAnd;
2355 }
2356 break;
2357 }
2358 case Instruction::AShr:
2359 // Signed shr.
2360 // See if this is shifting in some sign extension, then masking it out
2361 // with an and.
2362 if (Op->hasOneUse()) {
2363 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
2364 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
2365 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
Chris Lattner03a27b42010-01-04 07:02:48 +00002366 Constant *C = ConstantInt::get(Op->getContext(),
2367 AndRHS->getValue() & ShrMask);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002368 if (C == AndRHS) { // Masking out bits shifted in.
2369 // (Val ashr C1) & C2 -> (Val lshr C1) & C2
2370 // Make the argument unsigned.
2371 Value *ShVal = Op->getOperand(0);
Chris Lattnerc7694852009-08-30 07:44:24 +00002372 ShVal = Builder->CreateLShr(ShVal, OpRHS, Op->getName());
Gabor Greifa645dd32008-05-16 19:29:10 +00002373 return BinaryOperator::CreateAnd(ShVal, AndRHS, TheAnd.getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002374 }
2375 }
2376 break;
2377 }
2378 return 0;
2379}
2380
2381
2382/// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
2383/// true, otherwise (V < Lo || V >= Hi). In pratice, we emit the more efficient
2384/// (V-Lo) <u Hi-Lo. This method expects that Lo <= Hi. isSigned indicates
2385/// whether to treat the V, Lo and HI as signed or not. IB is the location to
2386/// insert new instructions.
2387Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
2388 bool isSigned, bool Inside,
2389 Instruction &IB) {
Owen Anderson02b48c32009-07-29 18:55:55 +00002390 assert(cast<ConstantInt>(ConstantExpr::getICmp((isSigned ?
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002391 ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
2392 "Lo is not <= Hi in range emission code!");
2393
2394 if (Inside) {
2395 if (Lo == Hi) // Trivially false.
Dan Gohmane6803b82009-08-25 23:17:54 +00002396 return new ICmpInst(ICmpInst::ICMP_NE, V, V);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002397
2398 // V >= Min && V < Hi --> V < Hi
2399 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
2400 ICmpInst::Predicate pred = (isSigned ?
2401 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
Dan Gohmane6803b82009-08-25 23:17:54 +00002402 return new ICmpInst(pred, V, Hi);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002403 }
2404
2405 // Emit V-Lo <u Hi-Lo
Owen Anderson02b48c32009-07-29 18:55:55 +00002406 Constant *NegLo = ConstantExpr::getNeg(Lo);
Chris Lattnerc7694852009-08-30 07:44:24 +00002407 Value *Add = Builder->CreateAdd(V, NegLo, V->getName()+".off");
Owen Anderson02b48c32009-07-29 18:55:55 +00002408 Constant *UpperBound = ConstantExpr::getAdd(NegLo, Hi);
Dan Gohmane6803b82009-08-25 23:17:54 +00002409 return new ICmpInst(ICmpInst::ICMP_ULT, Add, UpperBound);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002410 }
2411
2412 if (Lo == Hi) // Trivially true.
Dan Gohmane6803b82009-08-25 23:17:54 +00002413 return new ICmpInst(ICmpInst::ICMP_EQ, V, V);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002414
2415 // V < Min || V >= Hi -> V > Hi-1
Dan Gohmanfe91cd62009-08-12 16:04:34 +00002416 Hi = SubOne(cast<ConstantInt>(Hi));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002417 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
2418 ICmpInst::Predicate pred = (isSigned ?
2419 ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
Dan Gohmane6803b82009-08-25 23:17:54 +00002420 return new ICmpInst(pred, V, Hi);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002421 }
2422
2423 // Emit V-Lo >u Hi-1-Lo
2424 // Note that Hi has already had one subtracted from it, above.
Owen Anderson02b48c32009-07-29 18:55:55 +00002425 ConstantInt *NegLo = cast<ConstantInt>(ConstantExpr::getNeg(Lo));
Chris Lattnerc7694852009-08-30 07:44:24 +00002426 Value *Add = Builder->CreateAdd(V, NegLo, V->getName()+".off");
Owen Anderson02b48c32009-07-29 18:55:55 +00002427 Constant *LowerBound = ConstantExpr::getAdd(NegLo, Hi);
Dan Gohmane6803b82009-08-25 23:17:54 +00002428 return new ICmpInst(ICmpInst::ICMP_UGT, Add, LowerBound);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002429}
2430
2431// isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
2432// any number of 0s on either side. The 1s are allowed to wrap from LSB to
2433// MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs. 0x0F0F0000 is
2434// not, since all 1s are not contiguous.
2435static bool isRunOfOnes(ConstantInt *Val, uint32_t &MB, uint32_t &ME) {
2436 const APInt& V = Val->getValue();
2437 uint32_t BitWidth = Val->getType()->getBitWidth();
2438 if (!APIntOps::isShiftedMask(BitWidth, V)) return false;
2439
2440 // look for the first zero bit after the run of ones
2441 MB = BitWidth - ((V - 1) ^ V).countLeadingZeros();
2442 // look for the first non-zero bit
2443 ME = V.getActiveBits();
2444 return true;
2445}
2446
2447/// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
2448/// where isSub determines whether the operator is a sub. If we can fold one of
2449/// the following xforms:
2450///
2451/// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
2452/// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
2453/// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
2454///
2455/// return (A +/- B).
2456///
2457Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
2458 ConstantInt *Mask, bool isSub,
2459 Instruction &I) {
2460 Instruction *LHSI = dyn_cast<Instruction>(LHS);
2461 if (!LHSI || LHSI->getNumOperands() != 2 ||
2462 !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
2463
2464 ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
2465
2466 switch (LHSI->getOpcode()) {
2467 default: return 0;
2468 case Instruction::And:
Owen Anderson02b48c32009-07-29 18:55:55 +00002469 if (ConstantExpr::getAnd(N, Mask) == Mask) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002470 // If the AndRHS is a power of two minus one (0+1+), this is simple.
2471 if ((Mask->getValue().countLeadingZeros() +
2472 Mask->getValue().countPopulation()) ==
2473 Mask->getValue().getBitWidth())
2474 break;
2475
2476 // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
2477 // part, we don't need any explicit masks to take them out of A. If that
2478 // is all N is, ignore it.
2479 uint32_t MB = 0, ME = 0;
2480 if (isRunOfOnes(Mask, MB, ME)) { // begin/end bit of run, inclusive
2481 uint32_t BitWidth = cast<IntegerType>(RHS->getType())->getBitWidth();
2482 APInt Mask(APInt::getLowBitsSet(BitWidth, MB-1));
2483 if (MaskedValueIsZero(RHS, Mask))
2484 break;
2485 }
2486 }
2487 return 0;
2488 case Instruction::Or:
2489 case Instruction::Xor:
2490 // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
2491 if ((Mask->getValue().countLeadingZeros() +
2492 Mask->getValue().countPopulation()) == Mask->getValue().getBitWidth()
Owen Anderson02b48c32009-07-29 18:55:55 +00002493 && ConstantExpr::getAnd(N, Mask)->isNullValue())
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002494 break;
2495 return 0;
2496 }
2497
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002498 if (isSub)
Chris Lattnerc7694852009-08-30 07:44:24 +00002499 return Builder->CreateSub(LHSI->getOperand(0), RHS, "fold");
2500 return Builder->CreateAdd(LHSI->getOperand(0), RHS, "fold");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002501}
2502
Chris Lattner0631ea72008-11-16 05:06:21 +00002503/// FoldAndOfICmps - Fold (icmp)&(icmp) if possible.
2504Instruction *InstCombiner::FoldAndOfICmps(Instruction &I,
2505 ICmpInst *LHS, ICmpInst *RHS) {
Chris Lattnerf3803482008-11-16 05:10:52 +00002506 Value *Val, *Val2;
Chris Lattner0631ea72008-11-16 05:06:21 +00002507 ConstantInt *LHSCst, *RHSCst;
2508 ICmpInst::Predicate LHSCC, RHSCC;
2509
Chris Lattnerf3803482008-11-16 05:10:52 +00002510 // This only handles icmp of constants: (icmp1 A, C1) & (icmp2 B, C2).
Owen Andersona21eb582009-07-10 17:35:01 +00002511 if (!match(LHS, m_ICmp(LHSCC, m_Value(Val),
Dan Gohmancdff2122009-08-12 16:23:25 +00002512 m_ConstantInt(LHSCst))) ||
Owen Andersona21eb582009-07-10 17:35:01 +00002513 !match(RHS, m_ICmp(RHSCC, m_Value(Val2),
Dan Gohmancdff2122009-08-12 16:23:25 +00002514 m_ConstantInt(RHSCst))))
Chris Lattner0631ea72008-11-16 05:06:21 +00002515 return 0;
Chris Lattnerf3803482008-11-16 05:10:52 +00002516
Chris Lattner163e6ab2009-11-29 00:51:17 +00002517 if (LHSCst == RHSCst && LHSCC == RHSCC) {
2518 // (icmp ult A, C) & (icmp ult B, C) --> (icmp ult (A|B), C)
2519 // where C is a power of 2
2520 if (LHSCC == ICmpInst::ICMP_ULT &&
2521 LHSCst->getValue().isPowerOf2()) {
2522 Value *NewOr = Builder->CreateOr(Val, Val2);
2523 return new ICmpInst(LHSCC, NewOr, LHSCst);
2524 }
2525
2526 // (icmp eq A, 0) & (icmp eq B, 0) --> (icmp eq (A|B), 0)
2527 if (LHSCC == ICmpInst::ICMP_EQ && LHSCst->isZero()) {
2528 Value *NewOr = Builder->CreateOr(Val, Val2);
2529 return new ICmpInst(LHSCC, NewOr, LHSCst);
2530 }
Chris Lattnerf3803482008-11-16 05:10:52 +00002531 }
2532
2533 // From here on, we only handle:
2534 // (icmp1 A, C1) & (icmp2 A, C2) --> something simpler.
2535 if (Val != Val2) return 0;
2536
Chris Lattner0631ea72008-11-16 05:06:21 +00002537 // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
2538 if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
2539 RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
2540 LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
2541 RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
2542 return 0;
2543
2544 // We can't fold (ugt x, C) & (sgt x, C2).
2545 if (!PredicatesFoldable(LHSCC, RHSCC))
2546 return 0;
2547
2548 // Ensure that the larger constant is on the RHS.
Chris Lattner665298f2008-11-16 05:14:43 +00002549 bool ShouldSwap;
Nick Lewyckyb0796c62009-10-25 05:20:17 +00002550 if (CmpInst::isSigned(LHSCC) ||
Chris Lattner0631ea72008-11-16 05:06:21 +00002551 (ICmpInst::isEquality(LHSCC) &&
Nick Lewyckyb0796c62009-10-25 05:20:17 +00002552 CmpInst::isSigned(RHSCC)))
Chris Lattner665298f2008-11-16 05:14:43 +00002553 ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
Chris Lattner0631ea72008-11-16 05:06:21 +00002554 else
Chris Lattner665298f2008-11-16 05:14:43 +00002555 ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
2556
2557 if (ShouldSwap) {
Chris Lattner0631ea72008-11-16 05:06:21 +00002558 std::swap(LHS, RHS);
2559 std::swap(LHSCst, RHSCst);
2560 std::swap(LHSCC, RHSCC);
2561 }
2562
2563 // At this point, we know we have have two icmp instructions
2564 // comparing a value against two constants and and'ing the result
2565 // together. Because of the above check, we know that we only have
2566 // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know
2567 // (from the FoldICmpLogical check above), that the two constants
2568 // are not equal and that the larger constant is on the RHS
2569 assert(LHSCst != RHSCst && "Compares not folded above?");
2570
2571 switch (LHSCC) {
Edwin Törökbd448e32009-07-14 16:55:14 +00002572 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner0631ea72008-11-16 05:06:21 +00002573 case ICmpInst::ICMP_EQ:
2574 switch (RHSCC) {
Edwin Törökbd448e32009-07-14 16:55:14 +00002575 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner0631ea72008-11-16 05:06:21 +00002576 case ICmpInst::ICMP_EQ: // (X == 13 & X == 15) -> false
2577 case ICmpInst::ICMP_UGT: // (X == 13 & X > 15) -> false
2578 case ICmpInst::ICMP_SGT: // (X == 13 & X > 15) -> false
Chris Lattner03a27b42010-01-04 07:02:48 +00002579 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getContext()));
Chris Lattner0631ea72008-11-16 05:06:21 +00002580 case ICmpInst::ICMP_NE: // (X == 13 & X != 15) -> X == 13
2581 case ICmpInst::ICMP_ULT: // (X == 13 & X < 15) -> X == 13
2582 case ICmpInst::ICMP_SLT: // (X == 13 & X < 15) -> X == 13
2583 return ReplaceInstUsesWith(I, LHS);
2584 }
2585 case ICmpInst::ICMP_NE:
2586 switch (RHSCC) {
Edwin Törökbd448e32009-07-14 16:55:14 +00002587 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner0631ea72008-11-16 05:06:21 +00002588 case ICmpInst::ICMP_ULT:
Dan Gohmanfe91cd62009-08-12 16:04:34 +00002589 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X u< 14) -> X < 13
Dan Gohmane6803b82009-08-25 23:17:54 +00002590 return new ICmpInst(ICmpInst::ICMP_ULT, Val, LHSCst);
Chris Lattner0631ea72008-11-16 05:06:21 +00002591 break; // (X != 13 & X u< 15) -> no change
2592 case ICmpInst::ICMP_SLT:
Dan Gohmanfe91cd62009-08-12 16:04:34 +00002593 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X s< 14) -> X < 13
Dan Gohmane6803b82009-08-25 23:17:54 +00002594 return new ICmpInst(ICmpInst::ICMP_SLT, Val, LHSCst);
Chris Lattner0631ea72008-11-16 05:06:21 +00002595 break; // (X != 13 & X s< 15) -> no change
2596 case ICmpInst::ICMP_EQ: // (X != 13 & X == 15) -> X == 15
2597 case ICmpInst::ICMP_UGT: // (X != 13 & X u> 15) -> X u> 15
2598 case ICmpInst::ICMP_SGT: // (X != 13 & X s> 15) -> X s> 15
2599 return ReplaceInstUsesWith(I, RHS);
2600 case ICmpInst::ICMP_NE:
Dan Gohmanfe91cd62009-08-12 16:04:34 +00002601 if (LHSCst == SubOne(RHSCst)){// (X != 13 & X != 14) -> X-13 >u 1
Owen Anderson02b48c32009-07-29 18:55:55 +00002602 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
Chris Lattnerc7694852009-08-30 07:44:24 +00002603 Value *Add = Builder->CreateAdd(Val, AddCST, Val->getName()+".off");
Dan Gohmane6803b82009-08-25 23:17:54 +00002604 return new ICmpInst(ICmpInst::ICMP_UGT, Add,
Owen Andersoneacb44d2009-07-24 23:12:02 +00002605 ConstantInt::get(Add->getType(), 1));
Chris Lattner0631ea72008-11-16 05:06:21 +00002606 }
2607 break; // (X != 13 & X != 15) -> no change
2608 }
2609 break;
2610 case ICmpInst::ICMP_ULT:
2611 switch (RHSCC) {
Edwin Törökbd448e32009-07-14 16:55:14 +00002612 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner0631ea72008-11-16 05:06:21 +00002613 case ICmpInst::ICMP_EQ: // (X u< 13 & X == 15) -> false
2614 case ICmpInst::ICMP_UGT: // (X u< 13 & X u> 15) -> false
Chris Lattner03a27b42010-01-04 07:02:48 +00002615 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getContext()));
Chris Lattner0631ea72008-11-16 05:06:21 +00002616 case ICmpInst::ICMP_SGT: // (X u< 13 & X s> 15) -> no change
2617 break;
2618 case ICmpInst::ICMP_NE: // (X u< 13 & X != 15) -> X u< 13
2619 case ICmpInst::ICMP_ULT: // (X u< 13 & X u< 15) -> X u< 13
2620 return ReplaceInstUsesWith(I, LHS);
2621 case ICmpInst::ICMP_SLT: // (X u< 13 & X s< 15) -> no change
2622 break;
2623 }
2624 break;
2625 case ICmpInst::ICMP_SLT:
2626 switch (RHSCC) {
Edwin Törökbd448e32009-07-14 16:55:14 +00002627 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner0631ea72008-11-16 05:06:21 +00002628 case ICmpInst::ICMP_EQ: // (X s< 13 & X == 15) -> false
2629 case ICmpInst::ICMP_SGT: // (X s< 13 & X s> 15) -> false
Chris Lattner03a27b42010-01-04 07:02:48 +00002630 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getContext()));
Chris Lattner0631ea72008-11-16 05:06:21 +00002631 case ICmpInst::ICMP_UGT: // (X s< 13 & X u> 15) -> no change
2632 break;
2633 case ICmpInst::ICMP_NE: // (X s< 13 & X != 15) -> X < 13
2634 case ICmpInst::ICMP_SLT: // (X s< 13 & X s< 15) -> X < 13
2635 return ReplaceInstUsesWith(I, LHS);
2636 case ICmpInst::ICMP_ULT: // (X s< 13 & X u< 15) -> no change
2637 break;
2638 }
2639 break;
2640 case ICmpInst::ICMP_UGT:
2641 switch (RHSCC) {
Edwin Törökbd448e32009-07-14 16:55:14 +00002642 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner0631ea72008-11-16 05:06:21 +00002643 case ICmpInst::ICMP_EQ: // (X u> 13 & X == 15) -> X == 15
2644 case ICmpInst::ICMP_UGT: // (X u> 13 & X u> 15) -> X u> 15
2645 return ReplaceInstUsesWith(I, RHS);
2646 case ICmpInst::ICMP_SGT: // (X u> 13 & X s> 15) -> no change
2647 break;
2648 case ICmpInst::ICMP_NE:
Dan Gohmanfe91cd62009-08-12 16:04:34 +00002649 if (RHSCst == AddOne(LHSCst)) // (X u> 13 & X != 14) -> X u> 14
Dan Gohmane6803b82009-08-25 23:17:54 +00002650 return new ICmpInst(LHSCC, Val, RHSCst);
Chris Lattner0631ea72008-11-16 05:06:21 +00002651 break; // (X u> 13 & X != 15) -> no change
Chris Lattner0c678e52008-11-16 05:20:07 +00002652 case ICmpInst::ICMP_ULT: // (X u> 13 & X u< 15) -> (X-14) <u 1
Dan Gohmanfe91cd62009-08-12 16:04:34 +00002653 return InsertRangeTest(Val, AddOne(LHSCst),
Owen Anderson24be4c12009-07-03 00:17:18 +00002654 RHSCst, false, true, I);
Chris Lattner0631ea72008-11-16 05:06:21 +00002655 case ICmpInst::ICMP_SLT: // (X u> 13 & X s< 15) -> no change
2656 break;
2657 }
2658 break;
2659 case ICmpInst::ICMP_SGT:
2660 switch (RHSCC) {
Edwin Törökbd448e32009-07-14 16:55:14 +00002661 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner0631ea72008-11-16 05:06:21 +00002662 case ICmpInst::ICMP_EQ: // (X s> 13 & X == 15) -> X == 15
2663 case ICmpInst::ICMP_SGT: // (X s> 13 & X s> 15) -> X s> 15
2664 return ReplaceInstUsesWith(I, RHS);
2665 case ICmpInst::ICMP_UGT: // (X s> 13 & X u> 15) -> no change
2666 break;
2667 case ICmpInst::ICMP_NE:
Dan Gohmanfe91cd62009-08-12 16:04:34 +00002668 if (RHSCst == AddOne(LHSCst)) // (X s> 13 & X != 14) -> X s> 14
Dan Gohmane6803b82009-08-25 23:17:54 +00002669 return new ICmpInst(LHSCC, Val, RHSCst);
Chris Lattner0631ea72008-11-16 05:06:21 +00002670 break; // (X s> 13 & X != 15) -> no change
Chris Lattner0c678e52008-11-16 05:20:07 +00002671 case ICmpInst::ICMP_SLT: // (X s> 13 & X s< 15) -> (X-14) s< 1
Dan Gohmanfe91cd62009-08-12 16:04:34 +00002672 return InsertRangeTest(Val, AddOne(LHSCst),
Owen Anderson24be4c12009-07-03 00:17:18 +00002673 RHSCst, true, true, I);
Chris Lattner0631ea72008-11-16 05:06:21 +00002674 case ICmpInst::ICMP_ULT: // (X s> 13 & X u< 15) -> no change
2675 break;
2676 }
2677 break;
2678 }
Chris Lattner0631ea72008-11-16 05:06:21 +00002679
2680 return 0;
2681}
2682
Chris Lattner93a359a2009-07-23 05:14:02 +00002683Instruction *InstCombiner::FoldAndOfFCmps(Instruction &I, FCmpInst *LHS,
2684 FCmpInst *RHS) {
2685
2686 if (LHS->getPredicate() == FCmpInst::FCMP_ORD &&
2687 RHS->getPredicate() == FCmpInst::FCMP_ORD) {
2688 // (fcmp ord x, c) & (fcmp ord y, c) -> (fcmp ord x, y)
2689 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
2690 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
2691 // If either of the constants are nans, then the whole thing returns
2692 // false.
2693 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Chris Lattner03a27b42010-01-04 07:02:48 +00002694 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getContext()));
Dan Gohmane6803b82009-08-25 23:17:54 +00002695 return new FCmpInst(FCmpInst::FCMP_ORD,
Chris Lattner93a359a2009-07-23 05:14:02 +00002696 LHS->getOperand(0), RHS->getOperand(0));
2697 }
Chris Lattnercf373552009-07-23 05:32:17 +00002698
2699 // Handle vector zeros. This occurs because the canonical form of
2700 // "fcmp ord x,x" is "fcmp ord x, 0".
2701 if (isa<ConstantAggregateZero>(LHS->getOperand(1)) &&
2702 isa<ConstantAggregateZero>(RHS->getOperand(1)))
Dan Gohmane6803b82009-08-25 23:17:54 +00002703 return new FCmpInst(FCmpInst::FCMP_ORD,
Chris Lattnercf373552009-07-23 05:32:17 +00002704 LHS->getOperand(0), RHS->getOperand(0));
Chris Lattner93a359a2009-07-23 05:14:02 +00002705 return 0;
2706 }
2707
2708 Value *Op0LHS = LHS->getOperand(0), *Op0RHS = LHS->getOperand(1);
2709 Value *Op1LHS = RHS->getOperand(0), *Op1RHS = RHS->getOperand(1);
2710 FCmpInst::Predicate Op0CC = LHS->getPredicate(), Op1CC = RHS->getPredicate();
2711
2712
2713 if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
2714 // Swap RHS operands to match LHS.
2715 Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
2716 std::swap(Op1LHS, Op1RHS);
2717 }
2718
2719 if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
2720 // Simplify (fcmp cc0 x, y) & (fcmp cc1 x, y).
2721 if (Op0CC == Op1CC)
Dan Gohmane6803b82009-08-25 23:17:54 +00002722 return new FCmpInst((FCmpInst::Predicate)Op0CC, Op0LHS, Op0RHS);
Chris Lattner93a359a2009-07-23 05:14:02 +00002723
2724 if (Op0CC == FCmpInst::FCMP_FALSE || Op1CC == FCmpInst::FCMP_FALSE)
Chris Lattner03a27b42010-01-04 07:02:48 +00002725 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getContext()));
Chris Lattner93a359a2009-07-23 05:14:02 +00002726 if (Op0CC == FCmpInst::FCMP_TRUE)
2727 return ReplaceInstUsesWith(I, RHS);
2728 if (Op1CC == FCmpInst::FCMP_TRUE)
2729 return ReplaceInstUsesWith(I, LHS);
2730
2731 bool Op0Ordered;
2732 bool Op1Ordered;
2733 unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
2734 unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
2735 if (Op1Pred == 0) {
2736 std::swap(LHS, RHS);
2737 std::swap(Op0Pred, Op1Pred);
2738 std::swap(Op0Ordered, Op1Ordered);
2739 }
2740 if (Op0Pred == 0) {
2741 // uno && ueq -> uno && (uno || eq) -> ueq
2742 // ord && olt -> ord && (ord && lt) -> olt
2743 if (Op0Ordered == Op1Ordered)
2744 return ReplaceInstUsesWith(I, RHS);
2745
2746 // uno && oeq -> uno && (ord && eq) -> false
2747 // uno && ord -> false
2748 if (!Op0Ordered)
Chris Lattner03a27b42010-01-04 07:02:48 +00002749 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getContext()));
Chris Lattner93a359a2009-07-23 05:14:02 +00002750 // ord && ueq -> ord && (uno || eq) -> oeq
Chris Lattner03a27b42010-01-04 07:02:48 +00002751 return cast<Instruction>(getFCmpValue(true, Op1Pred, Op0LHS, Op0RHS));
Chris Lattner93a359a2009-07-23 05:14:02 +00002752 }
2753 }
2754
2755 return 0;
2756}
2757
Chris Lattner0631ea72008-11-16 05:06:21 +00002758
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002759Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
2760 bool Changed = SimplifyCommutative(I);
2761 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2762
Chris Lattnera3e46f62009-11-10 00:55:12 +00002763 if (Value *V = SimplifyAndInst(Op0, Op1, TD))
2764 return ReplaceInstUsesWith(I, V);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002765
2766 // See if we can simplify any instructions used by the instruction whose sole
2767 // purpose is to compute bits we don't care about.
Dan Gohman8fd520a2009-06-15 22:12:54 +00002768 if (SimplifyDemandedInstructionBits(I))
Nick Lewycky72c812c2010-01-02 15:25:44 +00002769 return &I;
Dan Gohman8fd520a2009-06-15 22:12:54 +00002770
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002771 if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner4580d452009-10-11 22:00:32 +00002772 const APInt &AndRHSMask = AndRHS->getValue();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002773 APInt NotAndRHS(~AndRHSMask);
2774
2775 // Optimize a variety of ((val OP C1) & C2) combinations...
Chris Lattner4580d452009-10-11 22:00:32 +00002776 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002777 Value *Op0LHS = Op0I->getOperand(0);
2778 Value *Op0RHS = Op0I->getOperand(1);
2779 switch (Op0I->getOpcode()) {
Chris Lattner4580d452009-10-11 22:00:32 +00002780 default: break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002781 case Instruction::Xor:
2782 case Instruction::Or:
2783 // If the mask is only needed on one incoming arm, push it up.
Chris Lattner4580d452009-10-11 22:00:32 +00002784 if (!Op0I->hasOneUse()) break;
2785
2786 if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
2787 // Not masking anything out for the LHS, move to RHS.
2788 Value *NewRHS = Builder->CreateAnd(Op0RHS, AndRHS,
2789 Op0RHS->getName()+".masked");
2790 return BinaryOperator::Create(Op0I->getOpcode(), Op0LHS, NewRHS);
2791 }
2792 if (!isa<Constant>(Op0RHS) &&
2793 MaskedValueIsZero(Op0RHS, NotAndRHS)) {
2794 // Not masking anything out for the RHS, move to LHS.
2795 Value *NewLHS = Builder->CreateAnd(Op0LHS, AndRHS,
2796 Op0LHS->getName()+".masked");
2797 return BinaryOperator::Create(Op0I->getOpcode(), NewLHS, Op0RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002798 }
2799
2800 break;
2801 case Instruction::Add:
2802 // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
2803 // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
2804 // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
2805 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
Gabor Greifa645dd32008-05-16 19:29:10 +00002806 return BinaryOperator::CreateAnd(V, AndRHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002807 if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
Gabor Greifa645dd32008-05-16 19:29:10 +00002808 return BinaryOperator::CreateAnd(V, AndRHS); // Add commutes
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002809 break;
2810
2811 case Instruction::Sub:
2812 // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
2813 // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
2814 // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
2815 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
Gabor Greifa645dd32008-05-16 19:29:10 +00002816 return BinaryOperator::CreateAnd(V, AndRHS);
Nick Lewyckyffed71b2008-07-09 04:32:37 +00002817
Nick Lewyckya349ba42008-07-10 05:51:40 +00002818 // (A - N) & AndRHS -> -N & AndRHS iff A&AndRHS==0 and AndRHS
2819 // has 1's for all bits that the subtraction with A might affect.
2820 if (Op0I->hasOneUse()) {
2821 uint32_t BitWidth = AndRHSMask.getBitWidth();
2822 uint32_t Zeros = AndRHSMask.countLeadingZeros();
2823 APInt Mask = APInt::getLowBitsSet(BitWidth, BitWidth - Zeros);
2824
Nick Lewyckyffed71b2008-07-09 04:32:37 +00002825 ConstantInt *A = dyn_cast<ConstantInt>(Op0LHS);
Nick Lewyckya349ba42008-07-10 05:51:40 +00002826 if (!(A && A->isZero()) && // avoid infinite recursion.
2827 MaskedValueIsZero(Op0LHS, Mask)) {
Chris Lattnerc7694852009-08-30 07:44:24 +00002828 Value *NewNeg = Builder->CreateNeg(Op0RHS);
Nick Lewyckyffed71b2008-07-09 04:32:37 +00002829 return BinaryOperator::CreateAnd(NewNeg, AndRHS);
2830 }
2831 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002832 break;
Nick Lewycky659ed4d2008-07-09 05:20:13 +00002833
2834 case Instruction::Shl:
2835 case Instruction::LShr:
2836 // (1 << x) & 1 --> zext(x == 0)
2837 // (1 >> x) & 1 --> zext(x == 0)
Nick Lewyckyf1b12222008-07-09 07:35:26 +00002838 if (AndRHSMask == 1 && Op0LHS == AndRHS) {
Chris Lattnerc7694852009-08-30 07:44:24 +00002839 Value *NewICmp =
2840 Builder->CreateICmpEQ(Op0RHS, Constant::getNullValue(I.getType()));
Nick Lewycky659ed4d2008-07-09 05:20:13 +00002841 return new ZExtInst(NewICmp, I.getType());
2842 }
2843 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002844 }
2845
2846 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
2847 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
2848 return Res;
2849 } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
2850 // If this is an integer truncation or change from signed-to-unsigned, and
2851 // if the source is an and/or with immediate, transform it. This
2852 // frequently occurs for bitfield accesses.
2853 if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
2854 if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
2855 CastOp->getNumOperands() == 2)
Chris Lattner6e060db2009-10-26 15:40:07 +00002856 if (ConstantInt *AndCI =dyn_cast<ConstantInt>(CastOp->getOperand(1))){
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002857 if (CastOp->getOpcode() == Instruction::And) {
2858 // Change: and (cast (and X, C1) to T), C2
2859 // into : and (cast X to T), trunc_or_bitcast(C1)&C2
2860 // This will fold the two constants together, which may allow
2861 // other simplifications.
Chris Lattnerc7694852009-08-30 07:44:24 +00002862 Value *NewCast = Builder->CreateTruncOrBitCast(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002863 CastOp->getOperand(0), I.getType(),
2864 CastOp->getName()+".shrunk");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002865 // trunc_or_bitcast(C1)&C2
Chris Lattnerc7694852009-08-30 07:44:24 +00002866 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
Owen Anderson02b48c32009-07-29 18:55:55 +00002867 C3 = ConstantExpr::getAnd(C3, AndRHS);
Gabor Greifa645dd32008-05-16 19:29:10 +00002868 return BinaryOperator::CreateAnd(NewCast, C3);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002869 } else if (CastOp->getOpcode() == Instruction::Or) {
2870 // Change: and (cast (or X, C1) to T), C2
2871 // into : trunc(C1)&C2 iff trunc(C1)&C2 == C2
Chris Lattnerc7694852009-08-30 07:44:24 +00002872 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
Owen Anderson02b48c32009-07-29 18:55:55 +00002873 if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS)
Owen Anderson24be4c12009-07-03 00:17:18 +00002874 // trunc(C1)&C2
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002875 return ReplaceInstUsesWith(I, AndRHS);
2876 }
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00002877 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002878 }
2879 }
2880
2881 // Try to fold constant and into select arguments.
2882 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2883 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2884 return R;
2885 if (isa<PHINode>(Op0))
2886 if (Instruction *NV = FoldOpIntoPhi(I))
2887 return NV;
2888 }
2889
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002890
2891 // (~A & ~B) == (~(A | B)) - De Morgan's Law
Chris Lattnera3e46f62009-11-10 00:55:12 +00002892 if (Value *Op0NotVal = dyn_castNotVal(Op0))
2893 if (Value *Op1NotVal = dyn_castNotVal(Op1))
2894 if (Op0->hasOneUse() && Op1->hasOneUse()) {
2895 Value *Or = Builder->CreateOr(Op0NotVal, Op1NotVal,
2896 I.getName()+".demorgan");
2897 return BinaryOperator::CreateNot(Or);
2898 }
2899
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002900 {
2901 Value *A = 0, *B = 0, *C = 0, *D = 0;
Chris Lattnera3e46f62009-11-10 00:55:12 +00002902 // (A|B) & ~(A&B) -> A^B
2903 if (match(Op0, m_Or(m_Value(A), m_Value(B))) &&
2904 match(Op1, m_Not(m_And(m_Value(C), m_Value(D)))) &&
2905 ((A == C && B == D) || (A == D && B == C)))
2906 return BinaryOperator::CreateXor(A, B);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002907
Chris Lattnera3e46f62009-11-10 00:55:12 +00002908 // ~(A&B) & (A|B) -> A^B
2909 if (match(Op1, m_Or(m_Value(A), m_Value(B))) &&
2910 match(Op0, m_Not(m_And(m_Value(C), m_Value(D)))) &&
2911 ((A == C && B == D) || (A == D && B == C)))
2912 return BinaryOperator::CreateXor(A, B);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002913
2914 if (Op0->hasOneUse() &&
Dan Gohmancdff2122009-08-12 16:23:25 +00002915 match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002916 if (A == Op1) { // (A^B)&A -> A&(A^B)
2917 I.swapOperands(); // Simplify below
2918 std::swap(Op0, Op1);
2919 } else if (B == Op1) { // (A^B)&B -> B&(B^A)
2920 cast<BinaryOperator>(Op0)->swapOperands();
2921 I.swapOperands(); // Simplify below
2922 std::swap(Op0, Op1);
2923 }
2924 }
Bill Wendlingce5e0af2008-11-30 13:08:13 +00002925
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002926 if (Op1->hasOneUse() &&
Dan Gohmancdff2122009-08-12 16:23:25 +00002927 match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002928 if (B == Op0) { // B&(A^B) -> B&(B^A)
2929 cast<BinaryOperator>(Op1)->swapOperands();
2930 std::swap(A, B);
2931 }
Chris Lattnerc7694852009-08-30 07:44:24 +00002932 if (A == Op0) // A&(A^B) -> A & ~B
2933 return BinaryOperator::CreateAnd(A, Builder->CreateNot(B, "tmp"));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002934 }
Bill Wendlingce5e0af2008-11-30 13:08:13 +00002935
2936 // (A&((~A)|B)) -> A&B
Dan Gohmancdff2122009-08-12 16:23:25 +00002937 if (match(Op0, m_Or(m_Not(m_Specific(Op1)), m_Value(A))) ||
2938 match(Op0, m_Or(m_Value(A), m_Not(m_Specific(Op1)))))
Chris Lattner9db479f2008-12-01 05:16:26 +00002939 return BinaryOperator::CreateAnd(A, Op1);
Dan Gohmancdff2122009-08-12 16:23:25 +00002940 if (match(Op1, m_Or(m_Not(m_Specific(Op0)), m_Value(A))) ||
2941 match(Op1, m_Or(m_Value(A), m_Not(m_Specific(Op0)))))
Chris Lattner9db479f2008-12-01 05:16:26 +00002942 return BinaryOperator::CreateAnd(A, Op0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002943 }
2944
2945 if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1)) {
2946 // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
Dan Gohmanfe91cd62009-08-12 16:04:34 +00002947 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002948 return R;
2949
Chris Lattner0631ea72008-11-16 05:06:21 +00002950 if (ICmpInst *LHS = dyn_cast<ICmpInst>(Op0))
2951 if (Instruction *Res = FoldAndOfICmps(I, LHS, RHS))
2952 return Res;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002953 }
2954
2955 // fold (and (cast A), (cast B)) -> (cast (and A, B))
2956 if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
2957 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
2958 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind ?
2959 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattnercf373552009-07-23 05:32:17 +00002960 if (SrcTy == Op1C->getOperand(0)->getType() &&
2961 SrcTy->isIntOrIntVector() &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002962 // Only do this if the casts both really cause code to be generated.
2963 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
2964 I.getType(), TD) &&
2965 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
2966 I.getType(), TD)) {
Chris Lattnerc7694852009-08-30 07:44:24 +00002967 Value *NewOp = Builder->CreateAnd(Op0C->getOperand(0),
2968 Op1C->getOperand(0), I.getName());
Gabor Greifa645dd32008-05-16 19:29:10 +00002969 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002970 }
2971 }
2972
2973 // (X >> Z) & (Y >> Z) -> (X&Y) >> Z for all shifts.
2974 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
2975 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
2976 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
2977 SI0->getOperand(1) == SI1->getOperand(1) &&
2978 (SI0->hasOneUse() || SI1->hasOneUse())) {
Chris Lattnerc7694852009-08-30 07:44:24 +00002979 Value *NewOp =
2980 Builder->CreateAnd(SI0->getOperand(0), SI1->getOperand(0),
2981 SI0->getName());
Gabor Greifa645dd32008-05-16 19:29:10 +00002982 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002983 SI1->getOperand(1));
2984 }
2985 }
2986
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00002987 // If and'ing two fcmp, try combine them into one.
Chris Lattner91882432007-10-24 05:38:08 +00002988 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
Chris Lattner93a359a2009-07-23 05:14:02 +00002989 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
2990 if (Instruction *Res = FoldAndOfFCmps(I, LHS, RHS))
2991 return Res;
Chris Lattner91882432007-10-24 05:38:08 +00002992 }
Nick Lewyckyffed71b2008-07-09 04:32:37 +00002993
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002994 return Changed ? &I : 0;
2995}
2996
Chris Lattner567f5112008-10-05 02:13:19 +00002997/// CollectBSwapParts - Analyze the specified subexpression and see if it is
2998/// capable of providing pieces of a bswap. The subexpression provides pieces
2999/// of a bswap if it is proven that each of the non-zero bytes in the output of
3000/// the expression came from the corresponding "byte swapped" byte in some other
3001/// value. For example, if the current subexpression is "(shl i32 %X, 24)" then
3002/// we know that the expression deposits the low byte of %X into the high byte
3003/// of the bswap result and that all other bytes are zero. This expression is
3004/// accepted, the high byte of ByteValues is set to X to indicate a correct
3005/// match.
3006///
3007/// This function returns true if the match was unsuccessful and false if so.
3008/// On entry to the function the "OverallLeftShift" is a signed integer value
3009/// indicating the number of bytes that the subexpression is later shifted. For
3010/// example, if the expression is later right shifted by 16 bits, the
3011/// OverallLeftShift value would be -2 on entry. This is used to specify which
3012/// byte of ByteValues is actually being set.
3013///
3014/// Similarly, ByteMask is a bitmask where a bit is clear if its corresponding
3015/// byte is masked to zero by a user. For example, in (X & 255), X will be
3016/// processed with a bytemask of 1. Because bytemask is 32-bits, this limits
3017/// this function to working on up to 32-byte (256 bit) values. ByteMask is
3018/// always in the local (OverallLeftShift) coordinate space.
3019///
3020static bool CollectBSwapParts(Value *V, int OverallLeftShift, uint32_t ByteMask,
3021 SmallVector<Value*, 8> &ByteValues) {
3022 if (Instruction *I = dyn_cast<Instruction>(V)) {
3023 // If this is an or instruction, it may be an inner node of the bswap.
3024 if (I->getOpcode() == Instruction::Or) {
3025 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
3026 ByteValues) ||
3027 CollectBSwapParts(I->getOperand(1), OverallLeftShift, ByteMask,
3028 ByteValues);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003029 }
Chris Lattner567f5112008-10-05 02:13:19 +00003030
3031 // If this is a logical shift by a constant multiple of 8, recurse with
3032 // OverallLeftShift and ByteMask adjusted.
3033 if (I->isLogicalShift() && isa<ConstantInt>(I->getOperand(1))) {
3034 unsigned ShAmt =
3035 cast<ConstantInt>(I->getOperand(1))->getLimitedValue(~0U);
3036 // Ensure the shift amount is defined and of a byte value.
3037 if ((ShAmt & 7) || (ShAmt > 8*ByteValues.size()))
3038 return true;
3039
3040 unsigned ByteShift = ShAmt >> 3;
3041 if (I->getOpcode() == Instruction::Shl) {
3042 // X << 2 -> collect(X, +2)
3043 OverallLeftShift += ByteShift;
3044 ByteMask >>= ByteShift;
3045 } else {
3046 // X >>u 2 -> collect(X, -2)
3047 OverallLeftShift -= ByteShift;
3048 ByteMask <<= ByteShift;
Chris Lattner44448592008-10-08 06:42:28 +00003049 ByteMask &= (~0U >> (32-ByteValues.size()));
Chris Lattner567f5112008-10-05 02:13:19 +00003050 }
3051
3052 if (OverallLeftShift >= (int)ByteValues.size()) return true;
3053 if (OverallLeftShift <= -(int)ByteValues.size()) return true;
3054
3055 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
3056 ByteValues);
3057 }
3058
3059 // If this is a logical 'and' with a mask that clears bytes, clear the
3060 // corresponding bytes in ByteMask.
3061 if (I->getOpcode() == Instruction::And &&
3062 isa<ConstantInt>(I->getOperand(1))) {
3063 // Scan every byte of the and mask, seeing if the byte is either 0 or 255.
3064 unsigned NumBytes = ByteValues.size();
3065 APInt Byte(I->getType()->getPrimitiveSizeInBits(), 255);
3066 const APInt &AndMask = cast<ConstantInt>(I->getOperand(1))->getValue();
3067
3068 for (unsigned i = 0; i != NumBytes; ++i, Byte <<= 8) {
3069 // If this byte is masked out by a later operation, we don't care what
3070 // the and mask is.
3071 if ((ByteMask & (1 << i)) == 0)
3072 continue;
3073
3074 // If the AndMask is all zeros for this byte, clear the bit.
3075 APInt MaskB = AndMask & Byte;
3076 if (MaskB == 0) {
3077 ByteMask &= ~(1U << i);
3078 continue;
3079 }
3080
3081 // If the AndMask is not all ones for this byte, it's not a bytezap.
3082 if (MaskB != Byte)
3083 return true;
3084
3085 // Otherwise, this byte is kept.
3086 }
3087
3088 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
3089 ByteValues);
3090 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003091 }
3092
Chris Lattner567f5112008-10-05 02:13:19 +00003093 // Okay, we got to something that isn't a shift, 'or' or 'and'. This must be
3094 // the input value to the bswap. Some observations: 1) if more than one byte
3095 // is demanded from this input, then it could not be successfully assembled
3096 // into a byteswap. At least one of the two bytes would not be aligned with
3097 // their ultimate destination.
3098 if (!isPowerOf2_32(ByteMask)) return true;
3099 unsigned InputByteNo = CountTrailingZeros_32(ByteMask);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003100
Chris Lattner567f5112008-10-05 02:13:19 +00003101 // 2) The input and ultimate destinations must line up: if byte 3 of an i32
3102 // is demanded, it needs to go into byte 0 of the result. This means that the
3103 // byte needs to be shifted until it lands in the right byte bucket. The
3104 // shift amount depends on the position: if the byte is coming from the high
3105 // part of the value (e.g. byte 3) then it must be shifted right. If from the
3106 // low part, it must be shifted left.
3107 unsigned DestByteNo = InputByteNo + OverallLeftShift;
3108 if (InputByteNo < ByteValues.size()/2) {
3109 if (ByteValues.size()-1-DestByteNo != InputByteNo)
3110 return true;
3111 } else {
3112 if (ByteValues.size()-1-DestByteNo != InputByteNo)
3113 return true;
3114 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003115
3116 // If the destination byte value is already defined, the values are or'd
3117 // together, which isn't a bswap (unless it's an or of the same bits).
Chris Lattner567f5112008-10-05 02:13:19 +00003118 if (ByteValues[DestByteNo] && ByteValues[DestByteNo] != V)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003119 return true;
Chris Lattner567f5112008-10-05 02:13:19 +00003120 ByteValues[DestByteNo] = V;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003121 return false;
3122}
3123
3124/// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
3125/// If so, insert the new bswap intrinsic and return it.
3126Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
3127 const IntegerType *ITy = dyn_cast<IntegerType>(I.getType());
Chris Lattner567f5112008-10-05 02:13:19 +00003128 if (!ITy || ITy->getBitWidth() % 16 ||
3129 // ByteMask only allows up to 32-byte values.
3130 ITy->getBitWidth() > 32*8)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003131 return 0; // Can only bswap pairs of bytes. Can't do vectors.
3132
3133 /// ByteValues - For each byte of the result, we keep track of which value
3134 /// defines each byte.
3135 SmallVector<Value*, 8> ByteValues;
3136 ByteValues.resize(ITy->getBitWidth()/8);
3137
3138 // Try to find all the pieces corresponding to the bswap.
Chris Lattner567f5112008-10-05 02:13:19 +00003139 uint32_t ByteMask = ~0U >> (32-ByteValues.size());
3140 if (CollectBSwapParts(&I, 0, ByteMask, ByteValues))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003141 return 0;
3142
3143 // Check to see if all of the bytes come from the same value.
3144 Value *V = ByteValues[0];
3145 if (V == 0) return 0; // Didn't find a byte? Must be zero.
3146
3147 // Check to make sure that all of the bytes come from the same value.
3148 for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
3149 if (ByteValues[i] != V)
3150 return 0;
Chandler Carrutha228e392007-08-04 01:51:18 +00003151 const Type *Tys[] = { ITy };
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003152 Module *M = I.getParent()->getParent()->getParent();
Chandler Carrutha228e392007-08-04 01:51:18 +00003153 Function *F = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 1);
Gabor Greifd6da1d02008-04-06 20:25:17 +00003154 return CallInst::Create(F, V);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003155}
3156
Chris Lattnerdd7772b2008-11-16 04:24:12 +00003157/// MatchSelectFromAndOr - We have an expression of the form (A&C)|(B&D). Check
3158/// If A is (cond?-1:0) and either B or D is ~(cond?-1,0) or (cond?0,-1), then
3159/// we can simplify this expression to "cond ? C : D or B".
3160static Instruction *MatchSelectFromAndOr(Value *A, Value *B,
Chris Lattner03a27b42010-01-04 07:02:48 +00003161 Value *C, Value *D) {
Chris Lattnerd09b5ba2008-11-16 04:26:55 +00003162 // If A is not a select of -1/0, this cannot match.
Chris Lattner641ea462008-11-16 04:46:19 +00003163 Value *Cond = 0;
Dan Gohmancdff2122009-08-12 16:23:25 +00003164 if (!match(A, m_SelectCst<-1, 0>(m_Value(Cond))))
Chris Lattnerdd7772b2008-11-16 04:24:12 +00003165 return 0;
3166
Chris Lattnerd09b5ba2008-11-16 04:26:55 +00003167 // ((cond?-1:0)&C) | (B&(cond?0:-1)) -> cond ? C : B.
Dan Gohmancdff2122009-08-12 16:23:25 +00003168 if (match(D, m_SelectCst<0, -1>(m_Specific(Cond))))
Chris Lattnerd09b5ba2008-11-16 04:26:55 +00003169 return SelectInst::Create(Cond, C, B);
Dan Gohmancdff2122009-08-12 16:23:25 +00003170 if (match(D, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond)))))
Chris Lattnerd09b5ba2008-11-16 04:26:55 +00003171 return SelectInst::Create(Cond, C, B);
3172 // ((cond?-1:0)&C) | ((cond?0:-1)&D) -> cond ? C : D.
Dan Gohmancdff2122009-08-12 16:23:25 +00003173 if (match(B, m_SelectCst<0, -1>(m_Specific(Cond))))
Chris Lattnerd09b5ba2008-11-16 04:26:55 +00003174 return SelectInst::Create(Cond, C, D);
Dan Gohmancdff2122009-08-12 16:23:25 +00003175 if (match(B, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond)))))
Chris Lattnerd09b5ba2008-11-16 04:26:55 +00003176 return SelectInst::Create(Cond, C, D);
Chris Lattnerdd7772b2008-11-16 04:24:12 +00003177 return 0;
3178}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003179
Chris Lattner0c678e52008-11-16 05:20:07 +00003180/// FoldOrOfICmps - Fold (icmp)|(icmp) if possible.
3181Instruction *InstCombiner::FoldOrOfICmps(Instruction &I,
3182 ICmpInst *LHS, ICmpInst *RHS) {
3183 Value *Val, *Val2;
3184 ConstantInt *LHSCst, *RHSCst;
3185 ICmpInst::Predicate LHSCC, RHSCC;
3186
3187 // This only handles icmp of constants: (icmp1 A, C1) | (icmp2 B, C2).
Chris Lattner163e6ab2009-11-29 00:51:17 +00003188 if (!match(LHS, m_ICmp(LHSCC, m_Value(Val), m_ConstantInt(LHSCst))) ||
3189 !match(RHS, m_ICmp(RHSCC, m_Value(Val2), m_ConstantInt(RHSCst))))
Chris Lattner0c678e52008-11-16 05:20:07 +00003190 return 0;
Chris Lattner163e6ab2009-11-29 00:51:17 +00003191
3192
3193 // (icmp ne A, 0) | (icmp ne B, 0) --> (icmp ne (A|B), 0)
3194 if (LHSCst == RHSCst && LHSCC == RHSCC &&
3195 LHSCC == ICmpInst::ICMP_NE && LHSCst->isZero()) {
3196 Value *NewOr = Builder->CreateOr(Val, Val2);
3197 return new ICmpInst(LHSCC, NewOr, LHSCst);
3198 }
Chris Lattner0c678e52008-11-16 05:20:07 +00003199
3200 // From here on, we only handle:
3201 // (icmp1 A, C1) | (icmp2 A, C2) --> something simpler.
3202 if (Val != Val2) return 0;
3203
3204 // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
3205 if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
3206 RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
3207 LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
3208 RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
3209 return 0;
3210
3211 // We can't fold (ugt x, C) | (sgt x, C2).
3212 if (!PredicatesFoldable(LHSCC, RHSCC))
3213 return 0;
3214
3215 // Ensure that the larger constant is on the RHS.
3216 bool ShouldSwap;
Nick Lewyckyb0796c62009-10-25 05:20:17 +00003217 if (CmpInst::isSigned(LHSCC) ||
Chris Lattner0c678e52008-11-16 05:20:07 +00003218 (ICmpInst::isEquality(LHSCC) &&
Nick Lewyckyb0796c62009-10-25 05:20:17 +00003219 CmpInst::isSigned(RHSCC)))
Chris Lattner0c678e52008-11-16 05:20:07 +00003220 ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
3221 else
3222 ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
3223
3224 if (ShouldSwap) {
3225 std::swap(LHS, RHS);
3226 std::swap(LHSCst, RHSCst);
3227 std::swap(LHSCC, RHSCC);
3228 }
3229
3230 // At this point, we know we have have two icmp instructions
3231 // comparing a value against two constants and or'ing the result
3232 // together. Because of the above check, we know that we only have
3233 // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
3234 // FoldICmpLogical check above), that the two constants are not
3235 // equal.
3236 assert(LHSCst != RHSCst && "Compares not folded above?");
3237
3238 switch (LHSCC) {
Edwin Törökbd448e32009-07-14 16:55:14 +00003239 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner0c678e52008-11-16 05:20:07 +00003240 case ICmpInst::ICMP_EQ:
3241 switch (RHSCC) {
Edwin Törökbd448e32009-07-14 16:55:14 +00003242 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner0c678e52008-11-16 05:20:07 +00003243 case ICmpInst::ICMP_EQ:
Dan Gohmanfe91cd62009-08-12 16:04:34 +00003244 if (LHSCst == SubOne(RHSCst)) {
Owen Anderson24be4c12009-07-03 00:17:18 +00003245 // (X == 13 | X == 14) -> X-13 <u 2
Owen Anderson02b48c32009-07-29 18:55:55 +00003246 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
Chris Lattnerc7694852009-08-30 07:44:24 +00003247 Value *Add = Builder->CreateAdd(Val, AddCST, Val->getName()+".off");
Dan Gohmanfe91cd62009-08-12 16:04:34 +00003248 AddCST = ConstantExpr::getSub(AddOne(RHSCst), LHSCst);
Dan Gohmane6803b82009-08-25 23:17:54 +00003249 return new ICmpInst(ICmpInst::ICMP_ULT, Add, AddCST);
Chris Lattner0c678e52008-11-16 05:20:07 +00003250 }
3251 break; // (X == 13 | X == 15) -> no change
3252 case ICmpInst::ICMP_UGT: // (X == 13 | X u> 14) -> no change
3253 case ICmpInst::ICMP_SGT: // (X == 13 | X s> 14) -> no change
3254 break;
3255 case ICmpInst::ICMP_NE: // (X == 13 | X != 15) -> X != 15
3256 case ICmpInst::ICMP_ULT: // (X == 13 | X u< 15) -> X u< 15
3257 case ICmpInst::ICMP_SLT: // (X == 13 | X s< 15) -> X s< 15
3258 return ReplaceInstUsesWith(I, RHS);
3259 }
3260 break;
3261 case ICmpInst::ICMP_NE:
3262 switch (RHSCC) {
Edwin Törökbd448e32009-07-14 16:55:14 +00003263 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner0c678e52008-11-16 05:20:07 +00003264 case ICmpInst::ICMP_EQ: // (X != 13 | X == 15) -> X != 13
3265 case ICmpInst::ICMP_UGT: // (X != 13 | X u> 15) -> X != 13
3266 case ICmpInst::ICMP_SGT: // (X != 13 | X s> 15) -> X != 13
3267 return ReplaceInstUsesWith(I, LHS);
3268 case ICmpInst::ICMP_NE: // (X != 13 | X != 15) -> true
3269 case ICmpInst::ICMP_ULT: // (X != 13 | X u< 15) -> true
3270 case ICmpInst::ICMP_SLT: // (X != 13 | X s< 15) -> true
Chris Lattner03a27b42010-01-04 07:02:48 +00003271 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getContext()));
Chris Lattner0c678e52008-11-16 05:20:07 +00003272 }
3273 break;
3274 case ICmpInst::ICMP_ULT:
3275 switch (RHSCC) {
Edwin Törökbd448e32009-07-14 16:55:14 +00003276 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner0c678e52008-11-16 05:20:07 +00003277 case ICmpInst::ICMP_EQ: // (X u< 13 | X == 14) -> no change
3278 break;
3279 case ICmpInst::ICMP_UGT: // (X u< 13 | X u> 15) -> (X-13) u> 2
3280 // If RHSCst is [us]MAXINT, it is always false. Not handling
3281 // this can cause overflow.
3282 if (RHSCst->isMaxValue(false))
3283 return ReplaceInstUsesWith(I, LHS);
Dan Gohmanfe91cd62009-08-12 16:04:34 +00003284 return InsertRangeTest(Val, LHSCst, AddOne(RHSCst),
Owen Anderson24be4c12009-07-03 00:17:18 +00003285 false, false, I);
Chris Lattner0c678e52008-11-16 05:20:07 +00003286 case ICmpInst::ICMP_SGT: // (X u< 13 | X s> 15) -> no change
3287 break;
3288 case ICmpInst::ICMP_NE: // (X u< 13 | X != 15) -> X != 15
3289 case ICmpInst::ICMP_ULT: // (X u< 13 | X u< 15) -> X u< 15
3290 return ReplaceInstUsesWith(I, RHS);
3291 case ICmpInst::ICMP_SLT: // (X u< 13 | X s< 15) -> no change
3292 break;
3293 }
3294 break;
3295 case ICmpInst::ICMP_SLT:
3296 switch (RHSCC) {
Edwin Törökbd448e32009-07-14 16:55:14 +00003297 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner0c678e52008-11-16 05:20:07 +00003298 case ICmpInst::ICMP_EQ: // (X s< 13 | X == 14) -> no change
3299 break;
3300 case ICmpInst::ICMP_SGT: // (X s< 13 | X s> 15) -> (X-13) s> 2
3301 // If RHSCst is [us]MAXINT, it is always false. Not handling
3302 // this can cause overflow.
3303 if (RHSCst->isMaxValue(true))
3304 return ReplaceInstUsesWith(I, LHS);
Dan Gohmanfe91cd62009-08-12 16:04:34 +00003305 return InsertRangeTest(Val, LHSCst, AddOne(RHSCst),
Owen Anderson24be4c12009-07-03 00:17:18 +00003306 true, false, I);
Chris Lattner0c678e52008-11-16 05:20:07 +00003307 case ICmpInst::ICMP_UGT: // (X s< 13 | X u> 15) -> no change
3308 break;
3309 case ICmpInst::ICMP_NE: // (X s< 13 | X != 15) -> X != 15
3310 case ICmpInst::ICMP_SLT: // (X s< 13 | X s< 15) -> X s< 15
3311 return ReplaceInstUsesWith(I, RHS);
3312 case ICmpInst::ICMP_ULT: // (X s< 13 | X u< 15) -> no change
3313 break;
3314 }
3315 break;
3316 case ICmpInst::ICMP_UGT:
3317 switch (RHSCC) {
Edwin Törökbd448e32009-07-14 16:55:14 +00003318 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner0c678e52008-11-16 05:20:07 +00003319 case ICmpInst::ICMP_EQ: // (X u> 13 | X == 15) -> X u> 13
3320 case ICmpInst::ICMP_UGT: // (X u> 13 | X u> 15) -> X u> 13
3321 return ReplaceInstUsesWith(I, LHS);
3322 case ICmpInst::ICMP_SGT: // (X u> 13 | X s> 15) -> no change
3323 break;
3324 case ICmpInst::ICMP_NE: // (X u> 13 | X != 15) -> true
3325 case ICmpInst::ICMP_ULT: // (X u> 13 | X u< 15) -> true
Chris Lattner03a27b42010-01-04 07:02:48 +00003326 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getContext()));
Chris Lattner0c678e52008-11-16 05:20:07 +00003327 case ICmpInst::ICMP_SLT: // (X u> 13 | X s< 15) -> no change
3328 break;
3329 }
3330 break;
3331 case ICmpInst::ICMP_SGT:
3332 switch (RHSCC) {
Edwin Törökbd448e32009-07-14 16:55:14 +00003333 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner0c678e52008-11-16 05:20:07 +00003334 case ICmpInst::ICMP_EQ: // (X s> 13 | X == 15) -> X > 13
3335 case ICmpInst::ICMP_SGT: // (X s> 13 | X s> 15) -> X > 13
3336 return ReplaceInstUsesWith(I, LHS);
3337 case ICmpInst::ICMP_UGT: // (X s> 13 | X u> 15) -> no change
3338 break;
3339 case ICmpInst::ICMP_NE: // (X s> 13 | X != 15) -> true
3340 case ICmpInst::ICMP_SLT: // (X s> 13 | X s< 15) -> true
Chris Lattner03a27b42010-01-04 07:02:48 +00003341 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getContext()));
Chris Lattner0c678e52008-11-16 05:20:07 +00003342 case ICmpInst::ICMP_ULT: // (X s> 13 | X u< 15) -> no change
3343 break;
3344 }
3345 break;
3346 }
3347 return 0;
3348}
3349
Chris Lattner57e66fa2009-07-23 05:46:22 +00003350Instruction *InstCombiner::FoldOrOfFCmps(Instruction &I, FCmpInst *LHS,
3351 FCmpInst *RHS) {
3352 if (LHS->getPredicate() == FCmpInst::FCMP_UNO &&
3353 RHS->getPredicate() == FCmpInst::FCMP_UNO &&
3354 LHS->getOperand(0)->getType() == RHS->getOperand(0)->getType()) {
3355 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
3356 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
3357 // If either of the constants are nans, then the whole thing returns
3358 // true.
3359 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Chris Lattner03a27b42010-01-04 07:02:48 +00003360 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getContext()));
Chris Lattner57e66fa2009-07-23 05:46:22 +00003361
3362 // Otherwise, no need to compare the two constants, compare the
3363 // rest.
Dan Gohmane6803b82009-08-25 23:17:54 +00003364 return new FCmpInst(FCmpInst::FCMP_UNO,
Chris Lattner57e66fa2009-07-23 05:46:22 +00003365 LHS->getOperand(0), RHS->getOperand(0));
3366 }
3367
3368 // Handle vector zeros. This occurs because the canonical form of
3369 // "fcmp uno x,x" is "fcmp uno x, 0".
3370 if (isa<ConstantAggregateZero>(LHS->getOperand(1)) &&
3371 isa<ConstantAggregateZero>(RHS->getOperand(1)))
Dan Gohmane6803b82009-08-25 23:17:54 +00003372 return new FCmpInst(FCmpInst::FCMP_UNO,
Chris Lattner57e66fa2009-07-23 05:46:22 +00003373 LHS->getOperand(0), RHS->getOperand(0));
3374
3375 return 0;
3376 }
3377
3378 Value *Op0LHS = LHS->getOperand(0), *Op0RHS = LHS->getOperand(1);
3379 Value *Op1LHS = RHS->getOperand(0), *Op1RHS = RHS->getOperand(1);
3380 FCmpInst::Predicate Op0CC = LHS->getPredicate(), Op1CC = RHS->getPredicate();
3381
3382 if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
3383 // Swap RHS operands to match LHS.
3384 Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
3385 std::swap(Op1LHS, Op1RHS);
3386 }
3387 if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
3388 // Simplify (fcmp cc0 x, y) | (fcmp cc1 x, y).
3389 if (Op0CC == Op1CC)
Dan Gohmane6803b82009-08-25 23:17:54 +00003390 return new FCmpInst((FCmpInst::Predicate)Op0CC,
Chris Lattner57e66fa2009-07-23 05:46:22 +00003391 Op0LHS, Op0RHS);
3392 if (Op0CC == FCmpInst::FCMP_TRUE || Op1CC == FCmpInst::FCMP_TRUE)
Chris Lattner03a27b42010-01-04 07:02:48 +00003393 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getContext()));
Chris Lattner57e66fa2009-07-23 05:46:22 +00003394 if (Op0CC == FCmpInst::FCMP_FALSE)
3395 return ReplaceInstUsesWith(I, RHS);
3396 if (Op1CC == FCmpInst::FCMP_FALSE)
3397 return ReplaceInstUsesWith(I, LHS);
3398 bool Op0Ordered;
3399 bool Op1Ordered;
3400 unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
3401 unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
3402 if (Op0Ordered == Op1Ordered) {
3403 // If both are ordered or unordered, return a new fcmp with
3404 // or'ed predicates.
Chris Lattner03a27b42010-01-04 07:02:48 +00003405 Value *RV = getFCmpValue(Op0Ordered, Op0Pred|Op1Pred, Op0LHS, Op0RHS);
Chris Lattner57e66fa2009-07-23 05:46:22 +00003406 if (Instruction *I = dyn_cast<Instruction>(RV))
3407 return I;
3408 // Otherwise, it's a constant boolean value...
3409 return ReplaceInstUsesWith(I, RV);
3410 }
3411 }
3412 return 0;
3413}
3414
Bill Wendlingdae376a2008-12-01 08:23:25 +00003415/// FoldOrWithConstants - This helper function folds:
3416///
Bill Wendling236a1192008-12-02 05:09:00 +00003417/// ((A | B) & C1) | (B & C2)
Bill Wendlingdae376a2008-12-01 08:23:25 +00003418///
3419/// into:
3420///
Bill Wendling236a1192008-12-02 05:09:00 +00003421/// (A & C1) | B
Bill Wendling9912f712008-12-01 08:32:40 +00003422///
Bill Wendling236a1192008-12-02 05:09:00 +00003423/// when the XOR of the two constants is "all ones" (-1).
Bill Wendling9912f712008-12-01 08:32:40 +00003424Instruction *InstCombiner::FoldOrWithConstants(BinaryOperator &I, Value *Op,
Bill Wendlingdae376a2008-12-01 08:23:25 +00003425 Value *A, Value *B, Value *C) {
Bill Wendlingfc5b8e62008-12-02 05:06:43 +00003426 ConstantInt *CI1 = dyn_cast<ConstantInt>(C);
3427 if (!CI1) return 0;
Bill Wendlingdae376a2008-12-01 08:23:25 +00003428
Bill Wendling0a0dcaf2008-12-02 06:24:20 +00003429 Value *V1 = 0;
3430 ConstantInt *CI2 = 0;
Dan Gohmancdff2122009-08-12 16:23:25 +00003431 if (!match(Op, m_And(m_Value(V1), m_ConstantInt(CI2)))) return 0;
Bill Wendlingdae376a2008-12-01 08:23:25 +00003432
Bill Wendling86ee3162008-12-02 06:18:11 +00003433 APInt Xor = CI1->getValue() ^ CI2->getValue();
3434 if (!Xor.isAllOnesValue()) return 0;
3435
Bill Wendling0a0dcaf2008-12-02 06:24:20 +00003436 if (V1 == A || V1 == B) {
Chris Lattnerc7694852009-08-30 07:44:24 +00003437 Value *NewOp = Builder->CreateAnd((V1 == A) ? B : A, CI1);
Bill Wendling6c8ecbb2008-12-02 06:22:04 +00003438 return BinaryOperator::CreateOr(NewOp, V1);
Bill Wendlingdae376a2008-12-01 08:23:25 +00003439 }
3440
3441 return 0;
3442}
3443
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003444Instruction *InstCombiner::visitOr(BinaryOperator &I) {
3445 bool Changed = SimplifyCommutative(I);
3446 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3447
Chris Lattnera3e46f62009-11-10 00:55:12 +00003448 if (Value *V = SimplifyOrInst(Op0, Op1, TD))
3449 return ReplaceInstUsesWith(I, V);
3450
3451
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003452 // See if we can simplify any instructions used by the instruction whose sole
3453 // purpose is to compute bits we don't care about.
Dan Gohman8fd520a2009-06-15 22:12:54 +00003454 if (SimplifyDemandedInstructionBits(I))
3455 return &I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003456
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003457 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3458 ConstantInt *C1 = 0; Value *X = 0;
3459 // (X & C1) | C2 --> (X | C2) & (C1|C2)
Dan Gohmancdff2122009-08-12 16:23:25 +00003460 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) &&
Owen Andersona21eb582009-07-10 17:35:01 +00003461 isOnlyUse(Op0)) {
Chris Lattnerc7694852009-08-30 07:44:24 +00003462 Value *Or = Builder->CreateOr(X, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003463 Or->takeName(Op0);
Gabor Greifa645dd32008-05-16 19:29:10 +00003464 return BinaryOperator::CreateAnd(Or,
Chris Lattner03a27b42010-01-04 07:02:48 +00003465 ConstantInt::get(I.getContext(),
3466 RHS->getValue() | C1->getValue()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003467 }
3468
3469 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
Dan Gohmancdff2122009-08-12 16:23:25 +00003470 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) &&
Owen Andersona21eb582009-07-10 17:35:01 +00003471 isOnlyUse(Op0)) {
Chris Lattnerc7694852009-08-30 07:44:24 +00003472 Value *Or = Builder->CreateOr(X, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003473 Or->takeName(Op0);
Gabor Greifa645dd32008-05-16 19:29:10 +00003474 return BinaryOperator::CreateXor(Or,
Chris Lattner03a27b42010-01-04 07:02:48 +00003475 ConstantInt::get(I.getContext(),
3476 C1->getValue() & ~RHS->getValue()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003477 }
3478
3479 // Try to fold constant and into select arguments.
3480 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
3481 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3482 return R;
3483 if (isa<PHINode>(Op0))
3484 if (Instruction *NV = FoldOpIntoPhi(I))
3485 return NV;
3486 }
3487
3488 Value *A = 0, *B = 0;
3489 ConstantInt *C1 = 0, *C2 = 0;
3490
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003491 // (A | B) | C and A | (B | C) -> bswap if possible.
3492 // (A >> B) | (C << D) and (A << B) | (B >> C) -> bswap if possible.
Dan Gohmancdff2122009-08-12 16:23:25 +00003493 if (match(Op0, m_Or(m_Value(), m_Value())) ||
3494 match(Op1, m_Or(m_Value(), m_Value())) ||
3495 (match(Op0, m_Shift(m_Value(), m_Value())) &&
3496 match(Op1, m_Shift(m_Value(), m_Value())))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003497 if (Instruction *BSwap = MatchBSwap(I))
3498 return BSwap;
3499 }
3500
3501 // (X^C)|Y -> (X|Y)^C iff Y&C == 0
Owen Andersona21eb582009-07-10 17:35:01 +00003502 if (Op0->hasOneUse() &&
Dan Gohmancdff2122009-08-12 16:23:25 +00003503 match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003504 MaskedValueIsZero(Op1, C1->getValue())) {
Chris Lattnerc7694852009-08-30 07:44:24 +00003505 Value *NOr = Builder->CreateOr(A, Op1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003506 NOr->takeName(Op0);
Gabor Greifa645dd32008-05-16 19:29:10 +00003507 return BinaryOperator::CreateXor(NOr, C1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003508 }
3509
3510 // Y|(X^C) -> (X|Y)^C iff Y&C == 0
Owen Andersona21eb582009-07-10 17:35:01 +00003511 if (Op1->hasOneUse() &&
Dan Gohmancdff2122009-08-12 16:23:25 +00003512 match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003513 MaskedValueIsZero(Op0, C1->getValue())) {
Chris Lattnerc7694852009-08-30 07:44:24 +00003514 Value *NOr = Builder->CreateOr(A, Op0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003515 NOr->takeName(Op0);
Gabor Greifa645dd32008-05-16 19:29:10 +00003516 return BinaryOperator::CreateXor(NOr, C1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003517 }
3518
3519 // (A & C)|(B & D)
3520 Value *C = 0, *D = 0;
Dan Gohmancdff2122009-08-12 16:23:25 +00003521 if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
3522 match(Op1, m_And(m_Value(B), m_Value(D)))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003523 Value *V1 = 0, *V2 = 0, *V3 = 0;
3524 C1 = dyn_cast<ConstantInt>(C);
3525 C2 = dyn_cast<ConstantInt>(D);
3526 if (C1 && C2) { // (A & C1)|(B & C2)
3527 // If we have: ((V + N) & C1) | (V & C2)
3528 // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
3529 // replace with V+N.
3530 if (C1->getValue() == ~C2->getValue()) {
3531 if ((C2->getValue() & (C2->getValue()+1)) == 0 && // C2 == 0+1+
Dan Gohmancdff2122009-08-12 16:23:25 +00003532 match(A, m_Add(m_Value(V1), m_Value(V2)))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003533 // Add commutes, try both ways.
3534 if (V1 == B && MaskedValueIsZero(V2, C2->getValue()))
3535 return ReplaceInstUsesWith(I, A);
3536 if (V2 == B && MaskedValueIsZero(V1, C2->getValue()))
3537 return ReplaceInstUsesWith(I, A);
3538 }
3539 // Or commutes, try both ways.
3540 if ((C1->getValue() & (C1->getValue()+1)) == 0 &&
Dan Gohmancdff2122009-08-12 16:23:25 +00003541 match(B, m_Add(m_Value(V1), m_Value(V2)))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003542 // Add commutes, try both ways.
3543 if (V1 == A && MaskedValueIsZero(V2, C1->getValue()))
3544 return ReplaceInstUsesWith(I, B);
3545 if (V2 == A && MaskedValueIsZero(V1, C1->getValue()))
3546 return ReplaceInstUsesWith(I, B);
3547 }
3548 }
Chris Lattner4fcef8a2010-01-04 06:03:59 +00003549
3550 // ((V | N) & C1) | (V & C2) --> (V|N) & (C1|C2)
3551 // iff (C1&C2) == 0 and (N&~C1) == 0
3552 if ((C1->getValue() & C2->getValue()) == 0) {
3553 if (match(A, m_Or(m_Value(V1), m_Value(V2))) &&
3554 ((V1 == B && MaskedValueIsZero(V2, ~C1->getValue())) || // (V|N)
3555 (V2 == B && MaskedValueIsZero(V1, ~C1->getValue())))) // (N|V)
3556 return BinaryOperator::CreateAnd(A,
3557 ConstantInt::get(A->getContext(),
3558 C1->getValue()|C2->getValue()));
3559 // Or commutes, try both ways.
3560 if (match(B, m_Or(m_Value(V1), m_Value(V2))) &&
3561 ((V1 == A && MaskedValueIsZero(V2, ~C2->getValue())) || // (V|N)
3562 (V2 == A && MaskedValueIsZero(V1, ~C2->getValue())))) // (N|V)
3563 return BinaryOperator::CreateAnd(B,
3564 ConstantInt::get(B->getContext(),
3565 C1->getValue()|C2->getValue()));
3566 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003567 }
3568
3569 // Check to see if we have any common things being and'ed. If so, find the
3570 // terms for V1 & (V2|V3).
3571 if (isOnlyUse(Op0) || isOnlyUse(Op1)) {
Chris Lattner4fcef8a2010-01-04 06:03:59 +00003572 V1 = 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003573 if (A == B) // (A & C)|(A & D) == A & (C|D)
3574 V1 = A, V2 = C, V3 = D;
3575 else if (A == D) // (A & C)|(B & A) == A & (B|C)
3576 V1 = A, V2 = B, V3 = C;
3577 else if (C == B) // (A & C)|(C & D) == C & (A|D)
3578 V1 = C, V2 = A, V3 = D;
3579 else if (C == D) // (A & C)|(B & C) == C & (A|B)
3580 V1 = C, V2 = A, V3 = B;
3581
3582 if (V1) {
Chris Lattnerc7694852009-08-30 07:44:24 +00003583 Value *Or = Builder->CreateOr(V2, V3, "tmp");
Gabor Greifa645dd32008-05-16 19:29:10 +00003584 return BinaryOperator::CreateAnd(V1, Or);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003585 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003586 }
Dan Gohman279952c2008-10-28 22:38:57 +00003587
Dan Gohman35b76162008-10-30 20:40:10 +00003588 // (A & (C0?-1:0)) | (B & ~(C0?-1:0)) -> C0 ? A : B, and commuted variants
Chris Lattner03a27b42010-01-04 07:02:48 +00003589 if (Instruction *Match = MatchSelectFromAndOr(A, B, C, D))
Chris Lattnerdd7772b2008-11-16 04:24:12 +00003590 return Match;
Chris Lattner03a27b42010-01-04 07:02:48 +00003591 if (Instruction *Match = MatchSelectFromAndOr(B, A, D, C))
Chris Lattnerdd7772b2008-11-16 04:24:12 +00003592 return Match;
Chris Lattner03a27b42010-01-04 07:02:48 +00003593 if (Instruction *Match = MatchSelectFromAndOr(C, B, A, D))
Chris Lattnerdd7772b2008-11-16 04:24:12 +00003594 return Match;
Chris Lattner03a27b42010-01-04 07:02:48 +00003595 if (Instruction *Match = MatchSelectFromAndOr(D, A, B, C))
Chris Lattnerdd7772b2008-11-16 04:24:12 +00003596 return Match;
Bill Wendling22ca8352008-11-30 13:52:49 +00003597
Bill Wendling22ca8352008-11-30 13:52:49 +00003598 // ((A&~B)|(~A&B)) -> A^B
Dan Gohmancdff2122009-08-12 16:23:25 +00003599 if ((match(C, m_Not(m_Specific(D))) &&
3600 match(B, m_Not(m_Specific(A)))))
Bill Wendlingc1f31132008-12-01 08:09:47 +00003601 return BinaryOperator::CreateXor(A, D);
Bill Wendling22ca8352008-11-30 13:52:49 +00003602 // ((~B&A)|(~A&B)) -> A^B
Dan Gohmancdff2122009-08-12 16:23:25 +00003603 if ((match(A, m_Not(m_Specific(D))) &&
3604 match(B, m_Not(m_Specific(C)))))
Bill Wendlingc1f31132008-12-01 08:09:47 +00003605 return BinaryOperator::CreateXor(C, D);
Bill Wendling22ca8352008-11-30 13:52:49 +00003606 // ((A&~B)|(B&~A)) -> A^B
Dan Gohmancdff2122009-08-12 16:23:25 +00003607 if ((match(C, m_Not(m_Specific(B))) &&
3608 match(D, m_Not(m_Specific(A)))))
Bill Wendlingc1f31132008-12-01 08:09:47 +00003609 return BinaryOperator::CreateXor(A, B);
Bill Wendling22ca8352008-11-30 13:52:49 +00003610 // ((~B&A)|(B&~A)) -> A^B
Dan Gohmancdff2122009-08-12 16:23:25 +00003611 if ((match(A, m_Not(m_Specific(B))) &&
3612 match(D, m_Not(m_Specific(C)))))
Bill Wendlingc1f31132008-12-01 08:09:47 +00003613 return BinaryOperator::CreateXor(C, B);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003614 }
3615
3616 // (X >> Z) | (Y >> Z) -> (X|Y) >> Z for all shifts.
3617 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
3618 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
3619 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
3620 SI0->getOperand(1) == SI1->getOperand(1) &&
3621 (SI0->hasOneUse() || SI1->hasOneUse())) {
Chris Lattnerc7694852009-08-30 07:44:24 +00003622 Value *NewOp = Builder->CreateOr(SI0->getOperand(0), SI1->getOperand(0),
3623 SI0->getName());
Gabor Greifa645dd32008-05-16 19:29:10 +00003624 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003625 SI1->getOperand(1));
3626 }
3627 }
3628
Bill Wendlingd8ce2372008-12-01 01:07:11 +00003629 // ((A|B)&1)|(B&-2) -> (A&1) | B
Dan Gohmancdff2122009-08-12 16:23:25 +00003630 if (match(Op0, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C))) ||
3631 match(Op0, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))))) {
Bill Wendling9912f712008-12-01 08:32:40 +00003632 Instruction *Ret = FoldOrWithConstants(I, Op1, A, B, C);
Bill Wendlingdae376a2008-12-01 08:23:25 +00003633 if (Ret) return Ret;
Bill Wendlingd8ce2372008-12-01 01:07:11 +00003634 }
3635 // (B&-2)|((A|B)&1) -> (A&1) | B
Dan Gohmancdff2122009-08-12 16:23:25 +00003636 if (match(Op1, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C))) ||
3637 match(Op1, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))))) {
Bill Wendling9912f712008-12-01 08:32:40 +00003638 Instruction *Ret = FoldOrWithConstants(I, Op0, A, B, C);
Bill Wendlingdae376a2008-12-01 08:23:25 +00003639 if (Ret) return Ret;
Bill Wendlingd8ce2372008-12-01 01:07:11 +00003640 }
3641
Chris Lattnera3e46f62009-11-10 00:55:12 +00003642 // (~A | ~B) == (~(A & B)) - De Morgan's Law
3643 if (Value *Op0NotVal = dyn_castNotVal(Op0))
3644 if (Value *Op1NotVal = dyn_castNotVal(Op1))
3645 if (Op0->hasOneUse() && Op1->hasOneUse()) {
3646 Value *And = Builder->CreateAnd(Op0NotVal, Op1NotVal,
3647 I.getName()+".demorgan");
3648 return BinaryOperator::CreateNot(And);
3649 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003650
3651 // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
3652 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1))) {
Dan Gohmanfe91cd62009-08-12 16:04:34 +00003653 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003654 return R;
3655
Chris Lattner0c678e52008-11-16 05:20:07 +00003656 if (ICmpInst *LHS = dyn_cast<ICmpInst>(I.getOperand(0)))
3657 if (Instruction *Res = FoldOrOfICmps(I, LHS, RHS))
3658 return Res;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003659 }
3660
3661 // fold (or (cast A), (cast B)) -> (cast (or A, B))
Chris Lattner91882432007-10-24 05:38:08 +00003662 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003663 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
3664 if (Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
Evan Chenge3779cf2008-03-24 00:21:34 +00003665 if (!isa<ICmpInst>(Op0C->getOperand(0)) ||
3666 !isa<ICmpInst>(Op1C->getOperand(0))) {
3667 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattnercf373552009-07-23 05:32:17 +00003668 if (SrcTy == Op1C->getOperand(0)->getType() &&
3669 SrcTy->isIntOrIntVector() &&
Evan Chenge3779cf2008-03-24 00:21:34 +00003670 // Only do this if the casts both really cause code to be
3671 // generated.
3672 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
3673 I.getType(), TD) &&
3674 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
3675 I.getType(), TD)) {
Chris Lattnerc7694852009-08-30 07:44:24 +00003676 Value *NewOp = Builder->CreateOr(Op0C->getOperand(0),
3677 Op1C->getOperand(0), I.getName());
Gabor Greifa645dd32008-05-16 19:29:10 +00003678 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Evan Chenge3779cf2008-03-24 00:21:34 +00003679 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003680 }
3681 }
Chris Lattner91882432007-10-24 05:38:08 +00003682 }
3683
3684
3685 // (fcmp uno x, c) | (fcmp uno y, c) -> (fcmp uno x, y)
3686 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
Chris Lattner57e66fa2009-07-23 05:46:22 +00003687 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
3688 if (Instruction *Res = FoldOrOfFCmps(I, LHS, RHS))
3689 return Res;
Chris Lattner91882432007-10-24 05:38:08 +00003690 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003691
3692 return Changed ? &I : 0;
3693}
3694
Dan Gohman089efff2008-05-13 00:00:25 +00003695namespace {
3696
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003697// XorSelf - Implements: X ^ X --> 0
3698struct XorSelf {
3699 Value *RHS;
3700 XorSelf(Value *rhs) : RHS(rhs) {}
3701 bool shouldApply(Value *LHS) const { return LHS == RHS; }
3702 Instruction *apply(BinaryOperator &Xor) const {
3703 return &Xor;
3704 }
3705};
3706
Dan Gohman089efff2008-05-13 00:00:25 +00003707}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003708
3709Instruction *InstCombiner::visitXor(BinaryOperator &I) {
3710 bool Changed = SimplifyCommutative(I);
3711 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3712
Evan Chenge5cd8032008-03-25 20:07:13 +00003713 if (isa<UndefValue>(Op1)) {
3714 if (isa<UndefValue>(Op0))
3715 // Handle undef ^ undef -> 0 special case. This is a common
3716 // idiom (misuse).
Owen Andersonaac28372009-07-31 20:28:14 +00003717 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003718 return ReplaceInstUsesWith(I, Op1); // X ^ undef -> undef
Evan Chenge5cd8032008-03-25 20:07:13 +00003719 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003720
3721 // xor X, X = 0, even if X is nested in a sequence of Xor's.
Dan Gohmanfe91cd62009-08-12 16:04:34 +00003722 if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
Chris Lattnerb933ea62007-08-05 08:47:58 +00003723 assert(Result == &I && "AssociativeOpt didn't work?"); Result=Result;
Owen Andersonaac28372009-07-31 20:28:14 +00003724 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003725 }
3726
3727 // See if we can simplify any instructions used by the instruction whose sole
3728 // purpose is to compute bits we don't care about.
Dan Gohman8fd520a2009-06-15 22:12:54 +00003729 if (SimplifyDemandedInstructionBits(I))
3730 return &I;
3731 if (isa<VectorType>(I.getType()))
3732 if (isa<ConstantAggregateZero>(Op1))
3733 return ReplaceInstUsesWith(I, Op0); // X ^ <0,0> -> X
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003734
3735 // Is this a ~ operation?
Dan Gohmanfe91cd62009-08-12 16:04:34 +00003736 if (Value *NotOp = dyn_castNotVal(&I)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003737 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(NotOp)) {
3738 if (Op0I->getOpcode() == Instruction::And ||
3739 Op0I->getOpcode() == Instruction::Or) {
Chris Lattner6e060db2009-10-26 15:40:07 +00003740 // ~(~X & Y) --> (X | ~Y) - De Morgan's Law
3741 // ~(~X | Y) === (X & ~Y) - De Morgan's Law
3742 if (dyn_castNotVal(Op0I->getOperand(1)))
3743 Op0I->swapOperands();
Dan Gohmanfe91cd62009-08-12 16:04:34 +00003744 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
Chris Lattnerc7694852009-08-30 07:44:24 +00003745 Value *NotY =
3746 Builder->CreateNot(Op0I->getOperand(1),
3747 Op0I->getOperand(1)->getName()+".not");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003748 if (Op0I->getOpcode() == Instruction::And)
Gabor Greifa645dd32008-05-16 19:29:10 +00003749 return BinaryOperator::CreateOr(Op0NotVal, NotY);
Chris Lattnerc7694852009-08-30 07:44:24 +00003750 return BinaryOperator::CreateAnd(Op0NotVal, NotY);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003751 }
Chris Lattner6e060db2009-10-26 15:40:07 +00003752
3753 // ~(X & Y) --> (~X | ~Y) - De Morgan's Law
3754 // ~(X | Y) === (~X & ~Y) - De Morgan's Law
3755 if (isFreeToInvert(Op0I->getOperand(0)) &&
3756 isFreeToInvert(Op0I->getOperand(1))) {
3757 Value *NotX =
3758 Builder->CreateNot(Op0I->getOperand(0), "notlhs");
3759 Value *NotY =
3760 Builder->CreateNot(Op0I->getOperand(1), "notrhs");
3761 if (Op0I->getOpcode() == Instruction::And)
3762 return BinaryOperator::CreateOr(NotX, NotY);
3763 return BinaryOperator::CreateAnd(NotX, NotY);
3764 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003765 }
3766 }
3767 }
3768
3769
3770 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner4580d452009-10-11 22:00:32 +00003771 if (RHS->isOne() && Op0->hasOneUse()) {
Bill Wendling61741952009-01-01 01:18:23 +00003772 // xor (cmp A, B), true = not (cmp A, B) = !cmp A, B
Nick Lewycky1405e922007-08-06 20:04:16 +00003773 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Op0))
Dan Gohmane6803b82009-08-25 23:17:54 +00003774 return new ICmpInst(ICI->getInversePredicate(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003775 ICI->getOperand(0), ICI->getOperand(1));
3776
Nick Lewycky1405e922007-08-06 20:04:16 +00003777 if (FCmpInst *FCI = dyn_cast<FCmpInst>(Op0))
Dan Gohmane6803b82009-08-25 23:17:54 +00003778 return new FCmpInst(FCI->getInversePredicate(),
Nick Lewycky1405e922007-08-06 20:04:16 +00003779 FCI->getOperand(0), FCI->getOperand(1));
3780 }
3781
Nick Lewycky0aa63aa2008-05-31 19:01:33 +00003782 // fold (xor(zext(cmp)), 1) and (xor(sext(cmp)), -1) to ext(!cmp).
3783 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
3784 if (CmpInst *CI = dyn_cast<CmpInst>(Op0C->getOperand(0))) {
3785 if (CI->hasOneUse() && Op0C->hasOneUse()) {
3786 Instruction::CastOps Opcode = Op0C->getOpcode();
Chris Lattnerc7694852009-08-30 07:44:24 +00003787 if ((Opcode == Instruction::ZExt || Opcode == Instruction::SExt) &&
3788 (RHS == ConstantExpr::getCast(Opcode,
Chris Lattner03a27b42010-01-04 07:02:48 +00003789 ConstantInt::getTrue(I.getContext()),
Chris Lattnerc7694852009-08-30 07:44:24 +00003790 Op0C->getDestTy()))) {
3791 CI->setPredicate(CI->getInversePredicate());
3792 return CastInst::Create(Opcode, CI, Op0C->getType());
Nick Lewycky0aa63aa2008-05-31 19:01:33 +00003793 }
3794 }
3795 }
3796 }
3797
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003798 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
3799 // ~(c-X) == X-c-1 == X+(-c-1)
3800 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
3801 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
Owen Anderson02b48c32009-07-29 18:55:55 +00003802 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
3803 Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
Owen Andersoneacb44d2009-07-24 23:12:02 +00003804 ConstantInt::get(I.getType(), 1));
Gabor Greifa645dd32008-05-16 19:29:10 +00003805 return BinaryOperator::CreateAdd(Op0I->getOperand(1), ConstantRHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003806 }
3807
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00003808 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003809 if (Op0I->getOpcode() == Instruction::Add) {
3810 // ~(X-c) --> (-c-1)-X
3811 if (RHS->isAllOnesValue()) {
Owen Anderson02b48c32009-07-29 18:55:55 +00003812 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
Gabor Greifa645dd32008-05-16 19:29:10 +00003813 return BinaryOperator::CreateSub(
Owen Anderson02b48c32009-07-29 18:55:55 +00003814 ConstantExpr::getSub(NegOp0CI,
Owen Andersoneacb44d2009-07-24 23:12:02 +00003815 ConstantInt::get(I.getType(), 1)),
Owen Anderson24be4c12009-07-03 00:17:18 +00003816 Op0I->getOperand(0));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003817 } else if (RHS->getValue().isSignBit()) {
3818 // (X + C) ^ signbit -> (X + C + signbit)
Chris Lattner03a27b42010-01-04 07:02:48 +00003819 Constant *C = ConstantInt::get(I.getContext(),
Owen Andersoneacb44d2009-07-24 23:12:02 +00003820 RHS->getValue() + Op0CI->getValue());
Gabor Greifa645dd32008-05-16 19:29:10 +00003821 return BinaryOperator::CreateAdd(Op0I->getOperand(0), C);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003822
3823 }
3824 } else if (Op0I->getOpcode() == Instruction::Or) {
3825 // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
3826 if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue())) {
Owen Anderson02b48c32009-07-29 18:55:55 +00003827 Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003828 // Anything in both C1 and C2 is known to be zero, remove it from
3829 // NewRHS.
Owen Anderson02b48c32009-07-29 18:55:55 +00003830 Constant *CommonBits = ConstantExpr::getAnd(Op0CI, RHS);
3831 NewRHS = ConstantExpr::getAnd(NewRHS,
3832 ConstantExpr::getNot(CommonBits));
Chris Lattner3183fb62009-08-30 06:13:40 +00003833 Worklist.Add(Op0I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003834 I.setOperand(0, Op0I->getOperand(0));
3835 I.setOperand(1, NewRHS);
3836 return &I;
3837 }
3838 }
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00003839 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003840 }
3841
3842 // Try to fold constant and into select arguments.
3843 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
3844 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3845 return R;
3846 if (isa<PHINode>(Op0))
3847 if (Instruction *NV = FoldOpIntoPhi(I))
3848 return NV;
3849 }
3850
Dan Gohmanfe91cd62009-08-12 16:04:34 +00003851 if (Value *X = dyn_castNotVal(Op0)) // ~A ^ A == -1
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003852 if (X == Op1)
Owen Andersonaac28372009-07-31 20:28:14 +00003853 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003854
Dan Gohmanfe91cd62009-08-12 16:04:34 +00003855 if (Value *X = dyn_castNotVal(Op1)) // A ^ ~A == -1
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003856 if (X == Op0)
Owen Andersonaac28372009-07-31 20:28:14 +00003857 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003858
3859
3860 BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1);
3861 if (Op1I) {
3862 Value *A, *B;
Dan Gohmancdff2122009-08-12 16:23:25 +00003863 if (match(Op1I, m_Or(m_Value(A), m_Value(B)))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003864 if (A == Op0) { // B^(B|A) == (A|B)^B
3865 Op1I->swapOperands();
3866 I.swapOperands();
3867 std::swap(Op0, Op1);
3868 } else if (B == Op0) { // B^(A|B) == (A|B)^B
3869 I.swapOperands(); // Simplified below.
3870 std::swap(Op0, Op1);
3871 }
Dan Gohmancdff2122009-08-12 16:23:25 +00003872 } else if (match(Op1I, m_Xor(m_Specific(Op0), m_Value(B)))) {
Chris Lattner3b874082008-11-16 05:38:51 +00003873 return ReplaceInstUsesWith(I, B); // A^(A^B) == B
Dan Gohmancdff2122009-08-12 16:23:25 +00003874 } else if (match(Op1I, m_Xor(m_Value(A), m_Specific(Op0)))) {
Chris Lattner3b874082008-11-16 05:38:51 +00003875 return ReplaceInstUsesWith(I, A); // A^(B^A) == B
Dan Gohmancdff2122009-08-12 16:23:25 +00003876 } else if (match(Op1I, m_And(m_Value(A), m_Value(B))) &&
Owen Andersona21eb582009-07-10 17:35:01 +00003877 Op1I->hasOneUse()){
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003878 if (A == Op0) { // A^(A&B) -> A^(B&A)
3879 Op1I->swapOperands();
3880 std::swap(A, B);
3881 }
3882 if (B == Op0) { // A^(B&A) -> (B&A)^A
3883 I.swapOperands(); // Simplified below.
3884 std::swap(Op0, Op1);
3885 }
3886 }
3887 }
3888
3889 BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0);
3890 if (Op0I) {
3891 Value *A, *B;
Dan Gohmancdff2122009-08-12 16:23:25 +00003892 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
Owen Andersona21eb582009-07-10 17:35:01 +00003893 Op0I->hasOneUse()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003894 if (A == Op1) // (B|A)^B == (A|B)^B
3895 std::swap(A, B);
Chris Lattnerc7694852009-08-30 07:44:24 +00003896 if (B == Op1) // (A|B)^B == A & ~B
3897 return BinaryOperator::CreateAnd(A, Builder->CreateNot(Op1, "tmp"));
Dan Gohmancdff2122009-08-12 16:23:25 +00003898 } else if (match(Op0I, m_Xor(m_Specific(Op1), m_Value(B)))) {
Chris Lattner3b874082008-11-16 05:38:51 +00003899 return ReplaceInstUsesWith(I, B); // (A^B)^A == B
Dan Gohmancdff2122009-08-12 16:23:25 +00003900 } else if (match(Op0I, m_Xor(m_Value(A), m_Specific(Op1)))) {
Chris Lattner3b874082008-11-16 05:38:51 +00003901 return ReplaceInstUsesWith(I, A); // (B^A)^A == B
Dan Gohmancdff2122009-08-12 16:23:25 +00003902 } else if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
Owen Andersona21eb582009-07-10 17:35:01 +00003903 Op0I->hasOneUse()){
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003904 if (A == Op1) // (A&B)^A -> (B&A)^A
3905 std::swap(A, B);
3906 if (B == Op1 && // (B&A)^A == ~B & A
3907 !isa<ConstantInt>(Op1)) { // Canonical form is (B&C)^C
Chris Lattnerc7694852009-08-30 07:44:24 +00003908 return BinaryOperator::CreateAnd(Builder->CreateNot(A, "tmp"), Op1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003909 }
3910 }
3911 }
3912
3913 // (X >> Z) ^ (Y >> Z) -> (X^Y) >> Z for all shifts.
3914 if (Op0I && Op1I && Op0I->isShift() &&
3915 Op0I->getOpcode() == Op1I->getOpcode() &&
3916 Op0I->getOperand(1) == Op1I->getOperand(1) &&
3917 (Op1I->hasOneUse() || Op1I->hasOneUse())) {
Chris Lattnerc7694852009-08-30 07:44:24 +00003918 Value *NewOp =
3919 Builder->CreateXor(Op0I->getOperand(0), Op1I->getOperand(0),
3920 Op0I->getName());
Gabor Greifa645dd32008-05-16 19:29:10 +00003921 return BinaryOperator::Create(Op1I->getOpcode(), NewOp,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003922 Op1I->getOperand(1));
3923 }
3924
3925 if (Op0I && Op1I) {
3926 Value *A, *B, *C, *D;
3927 // (A & B)^(A | B) -> A ^ B
Dan Gohmancdff2122009-08-12 16:23:25 +00003928 if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
3929 match(Op1I, m_Or(m_Value(C), m_Value(D)))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003930 if ((A == C && B == D) || (A == D && B == C))
Gabor Greifa645dd32008-05-16 19:29:10 +00003931 return BinaryOperator::CreateXor(A, B);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003932 }
3933 // (A | B)^(A & B) -> A ^ B
Dan Gohmancdff2122009-08-12 16:23:25 +00003934 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
3935 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003936 if ((A == C && B == D) || (A == D && B == C))
Gabor Greifa645dd32008-05-16 19:29:10 +00003937 return BinaryOperator::CreateXor(A, B);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003938 }
3939
3940 // (A & B)^(C & D)
3941 if ((Op0I->hasOneUse() || Op1I->hasOneUse()) &&
Dan Gohmancdff2122009-08-12 16:23:25 +00003942 match(Op0I, m_And(m_Value(A), m_Value(B))) &&
3943 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003944 // (X & Y)^(X & Y) -> (Y^Z) & X
3945 Value *X = 0, *Y = 0, *Z = 0;
3946 if (A == C)
3947 X = A, Y = B, Z = D;
3948 else if (A == D)
3949 X = A, Y = B, Z = C;
3950 else if (B == C)
3951 X = B, Y = A, Z = D;
3952 else if (B == D)
3953 X = B, Y = A, Z = C;
3954
3955 if (X) {
Chris Lattnerc7694852009-08-30 07:44:24 +00003956 Value *NewOp = Builder->CreateXor(Y, Z, Op0->getName());
Gabor Greifa645dd32008-05-16 19:29:10 +00003957 return BinaryOperator::CreateAnd(NewOp, X);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003958 }
3959 }
3960 }
3961
3962 // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
3963 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
Dan Gohmanfe91cd62009-08-12 16:04:34 +00003964 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003965 return R;
3966
3967 // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
Chris Lattner91882432007-10-24 05:38:08 +00003968 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003969 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
3970 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
3971 const Type *SrcTy = Op0C->getOperand(0)->getType();
3972 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
3973 // Only do this if the casts both really cause code to be generated.
3974 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
3975 I.getType(), TD) &&
3976 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
3977 I.getType(), TD)) {
Chris Lattnerc7694852009-08-30 07:44:24 +00003978 Value *NewOp = Builder->CreateXor(Op0C->getOperand(0),
3979 Op1C->getOperand(0), I.getName());
Gabor Greifa645dd32008-05-16 19:29:10 +00003980 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003981 }
3982 }
Chris Lattner91882432007-10-24 05:38:08 +00003983 }
Nick Lewycky0aa63aa2008-05-31 19:01:33 +00003984
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003985 return Changed ? &I : 0;
3986}
3987
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003988
3989Instruction *InstCombiner::visitShl(BinaryOperator &I) {
3990 return commonShiftTransforms(I);
3991}
3992
3993Instruction *InstCombiner::visitLShr(BinaryOperator &I) {
3994 return commonShiftTransforms(I);
3995}
3996
3997Instruction *InstCombiner::visitAShr(BinaryOperator &I) {
Chris Lattnere3c504f2007-12-06 01:59:46 +00003998 if (Instruction *R = commonShiftTransforms(I))
3999 return R;
4000
4001 Value *Op0 = I.getOperand(0);
4002
4003 // ashr int -1, X = -1 (for any arithmetic shift rights of ~0)
4004 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
4005 if (CSI->isAllOnesValue())
4006 return ReplaceInstUsesWith(I, CSI);
Dan Gohman843649e2009-02-24 02:00:40 +00004007
Dan Gohman2526aea2009-06-16 19:55:29 +00004008 // See if we can turn a signed shr into an unsigned shr.
4009 if (MaskedValueIsZero(Op0,
4010 APInt::getSignBit(I.getType()->getScalarSizeInBits())))
4011 return BinaryOperator::CreateLShr(Op0, I.getOperand(1));
4012
4013 // Arithmetic shifting an all-sign-bit value is a no-op.
4014 unsigned NumSignBits = ComputeNumSignBits(Op0);
4015 if (NumSignBits == Op0->getType()->getScalarSizeInBits())
4016 return ReplaceInstUsesWith(I, Op0);
Dan Gohman843649e2009-02-24 02:00:40 +00004017
Chris Lattnere3c504f2007-12-06 01:59:46 +00004018 return 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004019}
4020
4021Instruction *InstCombiner::commonShiftTransforms(BinaryOperator &I) {
4022 assert(I.getOperand(1)->getType() == I.getOperand(0)->getType());
4023 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4024
4025 // shl X, 0 == X and shr X, 0 == X
4026 // shl 0, X == 0 and shr 0, X == 0
Owen Andersonaac28372009-07-31 20:28:14 +00004027 if (Op1 == Constant::getNullValue(Op1->getType()) ||
4028 Op0 == Constant::getNullValue(Op0->getType()))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004029 return ReplaceInstUsesWith(I, Op0);
4030
4031 if (isa<UndefValue>(Op0)) {
4032 if (I.getOpcode() == Instruction::AShr) // undef >>s X -> undef
4033 return ReplaceInstUsesWith(I, Op0);
4034 else // undef << X -> 0, undef >>u X -> 0
Owen Andersonaac28372009-07-31 20:28:14 +00004035 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004036 }
4037 if (isa<UndefValue>(Op1)) {
4038 if (I.getOpcode() == Instruction::AShr) // X >>s undef -> X
4039 return ReplaceInstUsesWith(I, Op0);
4040 else // X << undef, X >>u undef -> 0
Owen Andersonaac28372009-07-31 20:28:14 +00004041 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004042 }
4043
Dan Gohman2bc21562009-05-21 02:28:33 +00004044 // See if we can fold away this shift.
Dan Gohman8fd520a2009-06-15 22:12:54 +00004045 if (SimplifyDemandedInstructionBits(I))
Dan Gohman2bc21562009-05-21 02:28:33 +00004046 return &I;
4047
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004048 // Try to fold constant and into select arguments.
4049 if (isa<Constant>(Op0))
4050 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
4051 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
4052 return R;
4053
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004054 if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
4055 if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
4056 return Res;
4057 return 0;
4058}
4059
4060Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
4061 BinaryOperator &I) {
Chris Lattner08817332009-01-31 08:24:16 +00004062 bool isLeftShift = I.getOpcode() == Instruction::Shl;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004063
4064 // See if we can simplify any instructions used by the instruction whose sole
4065 // purpose is to compute bits we don't care about.
Dan Gohman2526aea2009-06-16 19:55:29 +00004066 uint32_t TypeBits = Op0->getType()->getScalarSizeInBits();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004067
Dan Gohman9e1657f2009-06-14 23:30:43 +00004068 // shl i32 X, 32 = 0 and srl i8 Y, 9 = 0, ... just don't eliminate
4069 // a signed shift.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004070 //
4071 if (Op1->uge(TypeBits)) {
4072 if (I.getOpcode() != Instruction::AShr)
Owen Andersonaac28372009-07-31 20:28:14 +00004073 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004074 else {
Owen Andersoneacb44d2009-07-24 23:12:02 +00004075 I.setOperand(1, ConstantInt::get(I.getType(), TypeBits-1));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004076 return &I;
4077 }
4078 }
4079
4080 // ((X*C1) << C2) == (X * (C1 << C2))
4081 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
4082 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
4083 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
Gabor Greifa645dd32008-05-16 19:29:10 +00004084 return BinaryOperator::CreateMul(BO->getOperand(0),
Owen Anderson02b48c32009-07-29 18:55:55 +00004085 ConstantExpr::getShl(BOOp, Op1));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004086
4087 // Try to fold constant and into select arguments.
4088 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
4089 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
4090 return R;
4091 if (isa<PHINode>(Op0))
4092 if (Instruction *NV = FoldOpIntoPhi(I))
4093 return NV;
4094
Chris Lattnerc6d1f642007-12-22 09:07:47 +00004095 // Fold shift2(trunc(shift1(x,c1)), c2) -> trunc(shift2(shift1(x,c1),c2))
4096 if (TruncInst *TI = dyn_cast<TruncInst>(Op0)) {
4097 Instruction *TrOp = dyn_cast<Instruction>(TI->getOperand(0));
4098 // If 'shift2' is an ashr, we would have to get the sign bit into a funny
4099 // place. Don't try to do this transformation in this case. Also, we
4100 // require that the input operand is a shift-by-constant so that we have
4101 // confidence that the shifts will get folded together. We could do this
4102 // xform in more cases, but it is unlikely to be profitable.
4103 if (TrOp && I.isLogicalShift() && TrOp->isShift() &&
4104 isa<ConstantInt>(TrOp->getOperand(1))) {
4105 // Okay, we'll do this xform. Make the shift of shift.
Owen Anderson02b48c32009-07-29 18:55:55 +00004106 Constant *ShAmt = ConstantExpr::getZExt(Op1, TrOp->getType());
Chris Lattnerc7694852009-08-30 07:44:24 +00004107 // (shift2 (shift1 & 0x00FF), c2)
4108 Value *NSh = Builder->CreateBinOp(I.getOpcode(), TrOp, ShAmt,I.getName());
Chris Lattnerc6d1f642007-12-22 09:07:47 +00004109
4110 // For logical shifts, the truncation has the effect of making the high
4111 // part of the register be zeros. Emulate this by inserting an AND to
4112 // clear the top bits as needed. This 'and' will usually be zapped by
4113 // other xforms later if dead.
Dan Gohman2526aea2009-06-16 19:55:29 +00004114 unsigned SrcSize = TrOp->getType()->getScalarSizeInBits();
4115 unsigned DstSize = TI->getType()->getScalarSizeInBits();
Chris Lattnerc6d1f642007-12-22 09:07:47 +00004116 APInt MaskV(APInt::getLowBitsSet(SrcSize, DstSize));
4117
4118 // The mask we constructed says what the trunc would do if occurring
4119 // between the shifts. We want to know the effect *after* the second
4120 // shift. We know that it is a logical shift by a constant, so adjust the
4121 // mask as appropriate.
4122 if (I.getOpcode() == Instruction::Shl)
4123 MaskV <<= Op1->getZExtValue();
4124 else {
4125 assert(I.getOpcode() == Instruction::LShr && "Unknown logical shift");
4126 MaskV = MaskV.lshr(Op1->getZExtValue());
4127 }
4128
Chris Lattnerc7694852009-08-30 07:44:24 +00004129 // shift1 & 0x00FF
Chris Lattner03a27b42010-01-04 07:02:48 +00004130 Value *And = Builder->CreateAnd(NSh,
4131 ConstantInt::get(I.getContext(), MaskV),
Chris Lattnerc7694852009-08-30 07:44:24 +00004132 TI->getName());
Chris Lattnerc6d1f642007-12-22 09:07:47 +00004133
4134 // Return the value truncated to the interesting size.
4135 return new TruncInst(And, I.getType());
4136 }
4137 }
4138
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004139 if (Op0->hasOneUse()) {
4140 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
4141 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
4142 Value *V1, *V2;
4143 ConstantInt *CC;
4144 switch (Op0BO->getOpcode()) {
4145 default: break;
4146 case Instruction::Add:
4147 case Instruction::And:
4148 case Instruction::Or:
4149 case Instruction::Xor: {
4150 // These operators commute.
4151 // Turn (Y + (X >> C)) << C -> (X + (Y << C)) & (~0 << C)
4152 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
Owen Andersona21eb582009-07-10 17:35:01 +00004153 match(Op0BO->getOperand(1), m_Shr(m_Value(V1),
Chris Lattnerad7516a2009-08-30 18:50:58 +00004154 m_Specific(Op1)))) {
4155 Value *YS = // (Y << C)
4156 Builder->CreateShl(Op0BO->getOperand(0), Op1, Op0BO->getName());
4157 // (X + (Y << C))
4158 Value *X = Builder->CreateBinOp(Op0BO->getOpcode(), YS, V1,
4159 Op0BO->getOperand(1)->getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004160 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
Chris Lattner03a27b42010-01-04 07:02:48 +00004161 return BinaryOperator::CreateAnd(X, ConstantInt::get(I.getContext(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004162 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
4163 }
4164
4165 // Turn (Y + ((X >> C) & CC)) << C -> ((X & (CC << C)) + (Y << C))
4166 Value *Op0BOOp1 = Op0BO->getOperand(1);
4167 if (isLeftShift && Op0BOOp1->hasOneUse() &&
4168 match(Op0BOOp1,
Chris Lattner3b874082008-11-16 05:38:51 +00004169 m_And(m_Shr(m_Value(V1), m_Specific(Op1)),
Dan Gohmancdff2122009-08-12 16:23:25 +00004170 m_ConstantInt(CC))) &&
Chris Lattner3b874082008-11-16 05:38:51 +00004171 cast<BinaryOperator>(Op0BOOp1)->getOperand(0)->hasOneUse()) {
Chris Lattnerad7516a2009-08-30 18:50:58 +00004172 Value *YS = // (Y << C)
4173 Builder->CreateShl(Op0BO->getOperand(0), Op1,
4174 Op0BO->getName());
4175 // X & (CC << C)
4176 Value *XM = Builder->CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
4177 V1->getName()+".mask");
Gabor Greifa645dd32008-05-16 19:29:10 +00004178 return BinaryOperator::Create(Op0BO->getOpcode(), YS, XM);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004179 }
4180 }
4181
4182 // FALL THROUGH.
4183 case Instruction::Sub: {
4184 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
4185 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
Owen Andersona21eb582009-07-10 17:35:01 +00004186 match(Op0BO->getOperand(0), m_Shr(m_Value(V1),
Dan Gohmancdff2122009-08-12 16:23:25 +00004187 m_Specific(Op1)))) {
Chris Lattnerad7516a2009-08-30 18:50:58 +00004188 Value *YS = // (Y << C)
4189 Builder->CreateShl(Op0BO->getOperand(1), Op1, Op0BO->getName());
4190 // (X + (Y << C))
4191 Value *X = Builder->CreateBinOp(Op0BO->getOpcode(), V1, YS,
4192 Op0BO->getOperand(0)->getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004193 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
Chris Lattner03a27b42010-01-04 07:02:48 +00004194 return BinaryOperator::CreateAnd(X, ConstantInt::get(I.getContext(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004195 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
4196 }
4197
4198 // Turn (((X >> C)&CC) + Y) << C -> (X + (Y << C)) & (CC << C)
4199 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
4200 match(Op0BO->getOperand(0),
4201 m_And(m_Shr(m_Value(V1), m_Value(V2)),
Dan Gohmancdff2122009-08-12 16:23:25 +00004202 m_ConstantInt(CC))) && V2 == Op1 &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004203 cast<BinaryOperator>(Op0BO->getOperand(0))
4204 ->getOperand(0)->hasOneUse()) {
Chris Lattnerad7516a2009-08-30 18:50:58 +00004205 Value *YS = // (Y << C)
4206 Builder->CreateShl(Op0BO->getOperand(1), Op1, Op0BO->getName());
4207 // X & (CC << C)
4208 Value *XM = Builder->CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
4209 V1->getName()+".mask");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004210
Gabor Greifa645dd32008-05-16 19:29:10 +00004211 return BinaryOperator::Create(Op0BO->getOpcode(), XM, YS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004212 }
4213
4214 break;
4215 }
4216 }
4217
4218
4219 // If the operand is an bitwise operator with a constant RHS, and the
4220 // shift is the only use, we can pull it out of the shift.
4221 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
4222 bool isValid = true; // Valid only for And, Or, Xor
4223 bool highBitSet = false; // Transform if high bit of constant set?
4224
4225 switch (Op0BO->getOpcode()) {
4226 default: isValid = false; break; // Do not perform transform!
4227 case Instruction::Add:
4228 isValid = isLeftShift;
4229 break;
4230 case Instruction::Or:
4231 case Instruction::Xor:
4232 highBitSet = false;
4233 break;
4234 case Instruction::And:
4235 highBitSet = true;
4236 break;
4237 }
4238
4239 // If this is a signed shift right, and the high bit is modified
4240 // by the logical operation, do not perform the transformation.
4241 // The highBitSet boolean indicates the value of the high bit of
4242 // the constant which would cause it to be modified for this
4243 // operation.
4244 //
Chris Lattner15b76e32007-12-06 06:25:04 +00004245 if (isValid && I.getOpcode() == Instruction::AShr)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004246 isValid = Op0C->getValue()[TypeBits-1] == highBitSet;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004247
4248 if (isValid) {
Owen Anderson02b48c32009-07-29 18:55:55 +00004249 Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004250
Chris Lattnerad7516a2009-08-30 18:50:58 +00004251 Value *NewShift =
4252 Builder->CreateBinOp(I.getOpcode(), Op0BO->getOperand(0), Op1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004253 NewShift->takeName(Op0BO);
4254
Gabor Greifa645dd32008-05-16 19:29:10 +00004255 return BinaryOperator::Create(Op0BO->getOpcode(), NewShift,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004256 NewRHS);
4257 }
4258 }
4259 }
4260 }
4261
4262 // Find out if this is a shift of a shift by a constant.
4263 BinaryOperator *ShiftOp = dyn_cast<BinaryOperator>(Op0);
4264 if (ShiftOp && !ShiftOp->isShift())
4265 ShiftOp = 0;
4266
4267 if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
4268 ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
4269 uint32_t ShiftAmt1 = ShiftAmt1C->getLimitedValue(TypeBits);
4270 uint32_t ShiftAmt2 = Op1->getLimitedValue(TypeBits);
4271 assert(ShiftAmt2 != 0 && "Should have been simplified earlier");
4272 if (ShiftAmt1 == 0) return 0; // Will be simplified in the future.
4273 Value *X = ShiftOp->getOperand(0);
4274
4275 uint32_t AmtSum = ShiftAmt1+ShiftAmt2; // Fold into one big shift.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004276
4277 const IntegerType *Ty = cast<IntegerType>(I.getType());
4278
4279 // Check for (X << c1) << c2 and (X >> c1) >> c2
4280 if (I.getOpcode() == ShiftOp->getOpcode()) {
Chris Lattnerb36c7012009-03-20 22:41:15 +00004281 // If this is oversized composite shift, then unsigned shifts get 0, ashr
4282 // saturates.
4283 if (AmtSum >= TypeBits) {
4284 if (I.getOpcode() != Instruction::AShr)
Owen Andersonaac28372009-07-31 20:28:14 +00004285 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerb36c7012009-03-20 22:41:15 +00004286 AmtSum = TypeBits-1; // Saturate to 31 for i32 ashr.
4287 }
4288
Gabor Greifa645dd32008-05-16 19:29:10 +00004289 return BinaryOperator::Create(I.getOpcode(), X,
Owen Andersoneacb44d2009-07-24 23:12:02 +00004290 ConstantInt::get(Ty, AmtSum));
Chris Lattnerad7516a2009-08-30 18:50:58 +00004291 }
4292
4293 if (ShiftOp->getOpcode() == Instruction::LShr &&
4294 I.getOpcode() == Instruction::AShr) {
Chris Lattnerb36c7012009-03-20 22:41:15 +00004295 if (AmtSum >= TypeBits)
Owen Andersonaac28372009-07-31 20:28:14 +00004296 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerb36c7012009-03-20 22:41:15 +00004297
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004298 // ((X >>u C1) >>s C2) -> (X >>u (C1+C2)) since C1 != 0.
Owen Andersoneacb44d2009-07-24 23:12:02 +00004299 return BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, AmtSum));
Chris Lattnerad7516a2009-08-30 18:50:58 +00004300 }
4301
4302 if (ShiftOp->getOpcode() == Instruction::AShr &&
4303 I.getOpcode() == Instruction::LShr) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004304 // ((X >>s C1) >>u C2) -> ((X >>s (C1+C2)) & mask) since C1 != 0.
Chris Lattnerb36c7012009-03-20 22:41:15 +00004305 if (AmtSum >= TypeBits)
4306 AmtSum = TypeBits-1;
4307
Chris Lattnerad7516a2009-08-30 18:50:58 +00004308 Value *Shift = Builder->CreateAShr(X, ConstantInt::get(Ty, AmtSum));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004309
4310 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Chris Lattner03a27b42010-01-04 07:02:48 +00004311 return BinaryOperator::CreateAnd(Shift,
4312 ConstantInt::get(I.getContext(), Mask));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004313 }
4314
4315 // Okay, if we get here, one shift must be left, and the other shift must be
4316 // right. See if the amounts are equal.
4317 if (ShiftAmt1 == ShiftAmt2) {
4318 // If we have ((X >>? C) << C), turn this into X & (-1 << C).
4319 if (I.getOpcode() == Instruction::Shl) {
4320 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt1));
Chris Lattner03a27b42010-01-04 07:02:48 +00004321 return BinaryOperator::CreateAnd(X,
4322 ConstantInt::get(I.getContext(),Mask));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004323 }
4324 // If we have ((X << C) >>u C), turn this into X & (-1 >>u C).
4325 if (I.getOpcode() == Instruction::LShr) {
4326 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt1));
Chris Lattner03a27b42010-01-04 07:02:48 +00004327 return BinaryOperator::CreateAnd(X,
4328 ConstantInt::get(I.getContext(), Mask));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004329 }
4330 // We can simplify ((X << C) >>s C) into a trunc + sext.
4331 // NOTE: we could do this for any C, but that would make 'unusual' integer
4332 // types. For now, just stick to ones well-supported by the code
4333 // generators.
4334 const Type *SExtType = 0;
4335 switch (Ty->getBitWidth() - ShiftAmt1) {
4336 case 1 :
4337 case 8 :
4338 case 16 :
4339 case 32 :
4340 case 64 :
4341 case 128:
Chris Lattner03a27b42010-01-04 07:02:48 +00004342 SExtType = IntegerType::get(I.getContext(),
4343 Ty->getBitWidth() - ShiftAmt1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004344 break;
4345 default: break;
4346 }
Chris Lattnerad7516a2009-08-30 18:50:58 +00004347 if (SExtType)
4348 return new SExtInst(Builder->CreateTrunc(X, SExtType, "sext"), Ty);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004349 // Otherwise, we can't handle it yet.
4350 } else if (ShiftAmt1 < ShiftAmt2) {
4351 uint32_t ShiftDiff = ShiftAmt2-ShiftAmt1;
4352
4353 // (X >>? C1) << C2 --> X << (C2-C1) & (-1 << C2)
4354 if (I.getOpcode() == Instruction::Shl) {
4355 assert(ShiftOp->getOpcode() == Instruction::LShr ||
4356 ShiftOp->getOpcode() == Instruction::AShr);
Chris Lattnerad7516a2009-08-30 18:50:58 +00004357 Value *Shift = Builder->CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004358
4359 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersoneacb44d2009-07-24 23:12:02 +00004360 return BinaryOperator::CreateAnd(Shift,
Chris Lattner03a27b42010-01-04 07:02:48 +00004361 ConstantInt::get(I.getContext(),Mask));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004362 }
4363
4364 // (X << C1) >>u C2 --> X >>u (C2-C1) & (-1 >> C2)
4365 if (I.getOpcode() == Instruction::LShr) {
4366 assert(ShiftOp->getOpcode() == Instruction::Shl);
Chris Lattnerad7516a2009-08-30 18:50:58 +00004367 Value *Shift = Builder->CreateLShr(X, ConstantInt::get(Ty, ShiftDiff));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004368
4369 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersoneacb44d2009-07-24 23:12:02 +00004370 return BinaryOperator::CreateAnd(Shift,
Chris Lattner03a27b42010-01-04 07:02:48 +00004371 ConstantInt::get(I.getContext(),Mask));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004372 }
4373
4374 // We can't handle (X << C1) >>s C2, it shifts arbitrary bits in.
4375 } else {
4376 assert(ShiftAmt2 < ShiftAmt1);
4377 uint32_t ShiftDiff = ShiftAmt1-ShiftAmt2;
4378
4379 // (X >>? C1) << C2 --> X >>? (C1-C2) & (-1 << C2)
4380 if (I.getOpcode() == Instruction::Shl) {
4381 assert(ShiftOp->getOpcode() == Instruction::LShr ||
4382 ShiftOp->getOpcode() == Instruction::AShr);
Chris Lattnerad7516a2009-08-30 18:50:58 +00004383 Value *Shift = Builder->CreateBinOp(ShiftOp->getOpcode(), X,
4384 ConstantInt::get(Ty, ShiftDiff));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004385
4386 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersoneacb44d2009-07-24 23:12:02 +00004387 return BinaryOperator::CreateAnd(Shift,
Chris Lattner03a27b42010-01-04 07:02:48 +00004388 ConstantInt::get(I.getContext(),Mask));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004389 }
4390
4391 // (X << C1) >>u C2 --> X << (C1-C2) & (-1 >> C2)
4392 if (I.getOpcode() == Instruction::LShr) {
4393 assert(ShiftOp->getOpcode() == Instruction::Shl);
Chris Lattnerad7516a2009-08-30 18:50:58 +00004394 Value *Shift = Builder->CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004395
4396 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersoneacb44d2009-07-24 23:12:02 +00004397 return BinaryOperator::CreateAnd(Shift,
Chris Lattner03a27b42010-01-04 07:02:48 +00004398 ConstantInt::get(I.getContext(),Mask));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004399 }
4400
4401 // We can't handle (X << C1) >>a C2, it shifts arbitrary bits in.
4402 }
4403 }
4404 return 0;
4405}
4406
4407
4408/// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
4409/// expression. If so, decompose it, returning some value X, such that Val is
4410/// X*Scale+Offset.
4411///
4412static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
Chris Lattner03a27b42010-01-04 07:02:48 +00004413 int &Offset) {
4414 assert(Val->getType() == Type::getInt32Ty(Val->getContext()) &&
Chris Lattnerad7516a2009-08-30 18:50:58 +00004415 "Unexpected allocation size type!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004416 if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
4417 Offset = CI->getZExtValue();
Chris Lattnerc59171a2007-10-12 05:30:59 +00004418 Scale = 0;
Chris Lattner03a27b42010-01-04 07:02:48 +00004419 return ConstantInt::get(Type::getInt32Ty(Val->getContext()), 0);
Chris Lattnerc59171a2007-10-12 05:30:59 +00004420 } else if (BinaryOperator *I = dyn_cast<BinaryOperator>(Val)) {
4421 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
4422 if (I->getOpcode() == Instruction::Shl) {
4423 // This is a value scaled by '1 << the shift amt'.
4424 Scale = 1U << RHS->getZExtValue();
4425 Offset = 0;
4426 return I->getOperand(0);
4427 } else if (I->getOpcode() == Instruction::Mul) {
4428 // This value is scaled by 'RHS'.
4429 Scale = RHS->getZExtValue();
4430 Offset = 0;
4431 return I->getOperand(0);
4432 } else if (I->getOpcode() == Instruction::Add) {
4433 // We have X+C. Check to see if we really have (X*C2)+C1,
4434 // where C1 is divisible by C2.
4435 unsigned SubScale;
4436 Value *SubVal =
Chris Lattner03a27b42010-01-04 07:02:48 +00004437 DecomposeSimpleLinearExpr(I->getOperand(0), SubScale, Offset);
Chris Lattnerc59171a2007-10-12 05:30:59 +00004438 Offset += RHS->getZExtValue();
4439 Scale = SubScale;
4440 return SubVal;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004441 }
4442 }
4443 }
4444
4445 // Otherwise, we can't look past this.
4446 Scale = 1;
4447 Offset = 0;
4448 return Val;
4449}
4450
4451
4452/// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
4453/// try to eliminate the cast by moving the type information into the alloc.
4454Instruction *InstCombiner::PromoteCastOfAllocation(BitCastInst &CI,
Victor Hernandezb1687302009-10-23 21:09:37 +00004455 AllocaInst &AI) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004456 const PointerType *PTy = cast<PointerType>(CI.getType());
4457
Chris Lattnerad7516a2009-08-30 18:50:58 +00004458 BuilderTy AllocaBuilder(*Builder);
4459 AllocaBuilder.SetInsertPoint(AI.getParent(), &AI);
4460
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004461 // Remove any uses of AI that are dead.
4462 assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
4463
4464 for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
4465 Instruction *User = cast<Instruction>(*UI++);
4466 if (isInstructionTriviallyDead(User)) {
4467 while (UI != E && *UI == User)
4468 ++UI; // If this instruction uses AI more than once, don't break UI.
4469
4470 ++NumDeadInst;
Chris Lattner8a6411c2009-08-23 04:37:46 +00004471 DEBUG(errs() << "IC: DCE: " << *User << '\n');
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004472 EraseInstFromFunction(*User);
4473 }
4474 }
Dan Gohmana80e2712009-07-21 23:21:54 +00004475
4476 // This requires TargetData to get the alloca alignment and size information.
4477 if (!TD) return 0;
4478
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004479 // Get the type really allocated and the type casted to.
4480 const Type *AllocElTy = AI.getAllocatedType();
4481 const Type *CastElTy = PTy->getElementType();
4482 if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
4483
4484 unsigned AllocElTyAlign = TD->getABITypeAlignment(AllocElTy);
4485 unsigned CastElTyAlign = TD->getABITypeAlignment(CastElTy);
4486 if (CastElTyAlign < AllocElTyAlign) return 0;
4487
4488 // If the allocation has multiple uses, only promote it if we are strictly
4489 // increasing the alignment of the resultant allocation. If we keep it the
Dale Johannesen1ef9dc12009-03-05 00:39:02 +00004490 // same, we open the door to infinite loops of various kinds. (A reference
4491 // from a dbg.declare doesn't count as a use for this purpose.)
4492 if (!AI.hasOneUse() && !hasOneUsePlusDeclare(&AI) &&
4493 CastElTyAlign == AllocElTyAlign) return 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004494
Duncan Sandsec4f97d2009-05-09 07:06:46 +00004495 uint64_t AllocElTySize = TD->getTypeAllocSize(AllocElTy);
4496 uint64_t CastElTySize = TD->getTypeAllocSize(CastElTy);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004497 if (CastElTySize == 0 || AllocElTySize == 0) return 0;
4498
4499 // See if we can satisfy the modulus by pulling a scale out of the array
4500 // size argument.
4501 unsigned ArraySizeScale;
4502 int ArrayOffset;
4503 Value *NumElements = // See if the array size is a decomposable linear expr.
Chris Lattner03a27b42010-01-04 07:02:48 +00004504 DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale, ArrayOffset);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004505
4506 // If we can now satisfy the modulus, by using a non-1 scale, we really can
4507 // do the xform.
4508 if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
4509 (AllocElTySize*ArrayOffset ) % CastElTySize != 0) return 0;
4510
4511 unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
4512 Value *Amt = 0;
4513 if (Scale == 1) {
4514 Amt = NumElements;
4515 } else {
Chris Lattner03a27b42010-01-04 07:02:48 +00004516 Amt = ConstantInt::get(Type::getInt32Ty(CI.getContext()), Scale);
Chris Lattnerad7516a2009-08-30 18:50:58 +00004517 // Insert before the alloca, not before the cast.
4518 Amt = AllocaBuilder.CreateMul(Amt, NumElements, "tmp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004519 }
4520
4521 if (int Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
Chris Lattner03a27b42010-01-04 07:02:48 +00004522 Value *Off = ConstantInt::get(Type::getInt32Ty(CI.getContext()),
4523 Offset, true);
Chris Lattnerad7516a2009-08-30 18:50:58 +00004524 Amt = AllocaBuilder.CreateAdd(Amt, Off, "tmp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004525 }
4526
Victor Hernandezb1687302009-10-23 21:09:37 +00004527 AllocaInst *New = AllocaBuilder.CreateAlloca(CastElTy, Amt);
Chris Lattnerad7516a2009-08-30 18:50:58 +00004528 New->setAlignment(AI.getAlignment());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004529 New->takeName(&AI);
4530
Dale Johannesen1ef9dc12009-03-05 00:39:02 +00004531 // If the allocation has one real use plus a dbg.declare, just remove the
4532 // declare.
4533 if (DbgDeclareInst *DI = hasOneUsePlusDeclare(&AI)) {
4534 EraseInstFromFunction(*DI);
4535 }
4536 // If the allocation has multiple real uses, insert a cast and change all
4537 // things that used it to use the new cast. This will also hack on CI, but it
4538 // will die soon.
4539 else if (!AI.hasOneUse()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004540 // New is the allocation instruction, pointer typed. AI is the original
4541 // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
Chris Lattnerad7516a2009-08-30 18:50:58 +00004542 Value *NewCast = AllocaBuilder.CreateBitCast(New, AI.getType(), "tmpcast");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004543 AI.replaceAllUsesWith(NewCast);
4544 }
4545 return ReplaceInstUsesWith(CI, New);
4546}
4547
4548/// CanEvaluateInDifferentType - Return true if we can take the specified value
4549/// and return it as type Ty without inserting any new casts and without
4550/// changing the computed value. This is used by code that tries to decide
4551/// whether promoting or shrinking integer operations to wider or smaller types
4552/// will allow us to eliminate a truncate or extend.
4553///
4554/// This is a truncation operation if Ty is smaller than V->getType(), or an
4555/// extension operation if Ty is larger.
Chris Lattner4200c2062008-06-18 04:00:49 +00004556///
4557/// If CastOpc is a truncation, then Ty will be a type smaller than V. We
4558/// should return true if trunc(V) can be computed by computing V in the smaller
4559/// type. If V is an instruction, then trunc(inst(x,y)) can be computed as
4560/// inst(trunc(x),trunc(y)), which only makes sense if x and y can be
4561/// efficiently truncated.
4562///
4563/// If CastOpc is a sext or zext, we are asking if the low bits of the value can
4564/// bit computed in a larger type, which is then and'd or sext_in_reg'd to get
4565/// the final result.
Dan Gohman8fd520a2009-06-15 22:12:54 +00004566bool InstCombiner::CanEvaluateInDifferentType(Value *V, const Type *Ty,
Evan Cheng814a00c2009-01-16 02:11:43 +00004567 unsigned CastOpc,
4568 int &NumCastsRemoved){
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004569 // We can always evaluate constants in another type.
Dan Gohman8fd520a2009-06-15 22:12:54 +00004570 if (isa<Constant>(V))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004571 return true;
4572
4573 Instruction *I = dyn_cast<Instruction>(V);
4574 if (!I) return false;
4575
Dan Gohman8fd520a2009-06-15 22:12:54 +00004576 const Type *OrigTy = V->getType();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004577
Chris Lattneref70bb82007-08-02 06:11:14 +00004578 // If this is an extension or truncate, we can often eliminate it.
4579 if (isa<TruncInst>(I) || isa<ZExtInst>(I) || isa<SExtInst>(I)) {
4580 // If this is a cast from the destination type, we can trivially eliminate
4581 // it, and this will remove a cast overall.
4582 if (I->getOperand(0)->getType() == Ty) {
4583 // If the first operand is itself a cast, and is eliminable, do not count
4584 // this as an eliminable cast. We would prefer to eliminate those two
4585 // casts first.
Chris Lattner4200c2062008-06-18 04:00:49 +00004586 if (!isa<CastInst>(I->getOperand(0)) && I->hasOneUse())
Chris Lattneref70bb82007-08-02 06:11:14 +00004587 ++NumCastsRemoved;
4588 return true;
4589 }
4590 }
4591
4592 // We can't extend or shrink something that has multiple uses: doing so would
4593 // require duplicating the instruction in general, which isn't profitable.
4594 if (!I->hasOneUse()) return false;
4595
Evan Cheng9ca34ab2009-01-15 17:01:23 +00004596 unsigned Opc = I->getOpcode();
4597 switch (Opc) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004598 case Instruction::Add:
4599 case Instruction::Sub:
Nick Lewycky1265a7d2008-07-05 21:19:34 +00004600 case Instruction::Mul:
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004601 case Instruction::And:
4602 case Instruction::Or:
4603 case Instruction::Xor:
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004604 // These operators can all arbitrarily be extended or truncated.
Chris Lattneref70bb82007-08-02 06:11:14 +00004605 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
Evan Cheng814a00c2009-01-16 02:11:43 +00004606 NumCastsRemoved) &&
Chris Lattneref70bb82007-08-02 06:11:14 +00004607 CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
Evan Cheng814a00c2009-01-16 02:11:43 +00004608 NumCastsRemoved);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004609
Eli Friedman08c45bc2009-07-13 22:46:01 +00004610 case Instruction::UDiv:
4611 case Instruction::URem: {
4612 // UDiv and URem can be truncated if all the truncated bits are zero.
4613 uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
4614 uint32_t BitWidth = Ty->getScalarSizeInBits();
4615 if (BitWidth < OrigBitWidth) {
4616 APInt Mask = APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth);
4617 if (MaskedValueIsZero(I->getOperand(0), Mask) &&
4618 MaskedValueIsZero(I->getOperand(1), Mask)) {
4619 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
4620 NumCastsRemoved) &&
4621 CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
4622 NumCastsRemoved);
4623 }
4624 }
4625 break;
4626 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004627 case Instruction::Shl:
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004628 // If we are truncating the result of this SHL, and if it's a shift of a
4629 // constant amount, we can always perform a SHL in a smaller type.
4630 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
Dan Gohman8fd520a2009-06-15 22:12:54 +00004631 uint32_t BitWidth = Ty->getScalarSizeInBits();
4632 if (BitWidth < OrigTy->getScalarSizeInBits() &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004633 CI->getLimitedValue(BitWidth) < BitWidth)
Chris Lattneref70bb82007-08-02 06:11:14 +00004634 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
Evan Cheng814a00c2009-01-16 02:11:43 +00004635 NumCastsRemoved);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004636 }
4637 break;
4638 case Instruction::LShr:
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004639 // If this is a truncate of a logical shr, we can truncate it to a smaller
4640 // lshr iff we know that the bits we would otherwise be shifting in are
4641 // already zeros.
4642 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
Dan Gohman8fd520a2009-06-15 22:12:54 +00004643 uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
4644 uint32_t BitWidth = Ty->getScalarSizeInBits();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004645 if (BitWidth < OrigBitWidth &&
4646 MaskedValueIsZero(I->getOperand(0),
4647 APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth)) &&
4648 CI->getLimitedValue(BitWidth) < BitWidth) {
Chris Lattneref70bb82007-08-02 06:11:14 +00004649 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
Evan Cheng814a00c2009-01-16 02:11:43 +00004650 NumCastsRemoved);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004651 }
4652 }
4653 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004654 case Instruction::ZExt:
4655 case Instruction::SExt:
Chris Lattneref70bb82007-08-02 06:11:14 +00004656 case Instruction::Trunc:
4657 // If this is the same kind of case as our original (e.g. zext+zext), we
Chris Lattner9c909d22007-08-02 17:23:38 +00004658 // can safely replace it. Note that replacing it does not reduce the number
4659 // of casts in the input.
Evan Cheng9ca34ab2009-01-15 17:01:23 +00004660 if (Opc == CastOpc)
4661 return true;
4662
4663 // sext (zext ty1), ty2 -> zext ty2
Evan Cheng7bb0d952009-01-15 17:09:07 +00004664 if (CastOpc == Instruction::SExt && Opc == Instruction::ZExt)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004665 return true;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004666 break;
Nick Lewycky1265a7d2008-07-05 21:19:34 +00004667 case Instruction::Select: {
4668 SelectInst *SI = cast<SelectInst>(I);
4669 return CanEvaluateInDifferentType(SI->getTrueValue(), Ty, CastOpc,
Evan Cheng814a00c2009-01-16 02:11:43 +00004670 NumCastsRemoved) &&
Nick Lewycky1265a7d2008-07-05 21:19:34 +00004671 CanEvaluateInDifferentType(SI->getFalseValue(), Ty, CastOpc,
Evan Cheng814a00c2009-01-16 02:11:43 +00004672 NumCastsRemoved);
Nick Lewycky1265a7d2008-07-05 21:19:34 +00004673 }
Chris Lattner4200c2062008-06-18 04:00:49 +00004674 case Instruction::PHI: {
4675 // We can change a phi if we can change all operands.
4676 PHINode *PN = cast<PHINode>(I);
4677 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
4678 if (!CanEvaluateInDifferentType(PN->getIncomingValue(i), Ty, CastOpc,
Evan Cheng814a00c2009-01-16 02:11:43 +00004679 NumCastsRemoved))
Chris Lattner4200c2062008-06-18 04:00:49 +00004680 return false;
4681 return true;
4682 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004683 default:
4684 // TODO: Can handle more cases here.
4685 break;
4686 }
4687
4688 return false;
4689}
4690
4691/// EvaluateInDifferentType - Given an expression that
4692/// CanEvaluateInDifferentType returns true for, actually insert the code to
4693/// evaluate the expression.
4694Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty,
4695 bool isSigned) {
4696 if (Constant *C = dyn_cast<Constant>(V))
Chris Lattner1cd526b2009-11-08 19:23:30 +00004697 return ConstantExpr::getIntegerCast(C, Ty, isSigned /*Sext or ZExt*/);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004698
4699 // Otherwise, it must be an instruction.
4700 Instruction *I = cast<Instruction>(V);
4701 Instruction *Res = 0;
Evan Cheng9ca34ab2009-01-15 17:01:23 +00004702 unsigned Opc = I->getOpcode();
4703 switch (Opc) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004704 case Instruction::Add:
4705 case Instruction::Sub:
Nick Lewyckyc52646a2008-01-22 05:08:48 +00004706 case Instruction::Mul:
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004707 case Instruction::And:
4708 case Instruction::Or:
4709 case Instruction::Xor:
4710 case Instruction::AShr:
4711 case Instruction::LShr:
Eli Friedman08c45bc2009-07-13 22:46:01 +00004712 case Instruction::Shl:
4713 case Instruction::UDiv:
4714 case Instruction::URem: {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004715 Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
4716 Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
Evan Cheng9ca34ab2009-01-15 17:01:23 +00004717 Res = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004718 break;
4719 }
4720 case Instruction::Trunc:
4721 case Instruction::ZExt:
4722 case Instruction::SExt:
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004723 // If the source type of the cast is the type we're trying for then we can
Chris Lattneref70bb82007-08-02 06:11:14 +00004724 // just return the source. There's no need to insert it because it is not
4725 // new.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004726 if (I->getOperand(0)->getType() == Ty)
4727 return I->getOperand(0);
4728
Chris Lattner4200c2062008-06-18 04:00:49 +00004729 // Otherwise, must be the same type of cast, so just reinsert a new one.
Chris Lattner1cd526b2009-11-08 19:23:30 +00004730 Res = CastInst::Create(cast<CastInst>(I)->getOpcode(), I->getOperand(0),Ty);
Chris Lattneref70bb82007-08-02 06:11:14 +00004731 break;
Nick Lewycky1265a7d2008-07-05 21:19:34 +00004732 case Instruction::Select: {
4733 Value *True = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
4734 Value *False = EvaluateInDifferentType(I->getOperand(2), Ty, isSigned);
4735 Res = SelectInst::Create(I->getOperand(0), True, False);
4736 break;
4737 }
Chris Lattner4200c2062008-06-18 04:00:49 +00004738 case Instruction::PHI: {
4739 PHINode *OPN = cast<PHINode>(I);
4740 PHINode *NPN = PHINode::Create(Ty);
4741 for (unsigned i = 0, e = OPN->getNumIncomingValues(); i != e; ++i) {
4742 Value *V =EvaluateInDifferentType(OPN->getIncomingValue(i), Ty, isSigned);
4743 NPN->addIncoming(V, OPN->getIncomingBlock(i));
4744 }
4745 Res = NPN;
4746 break;
4747 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004748 default:
4749 // TODO: Can handle more cases here.
Edwin Törökbd448e32009-07-14 16:55:14 +00004750 llvm_unreachable("Unreachable!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004751 break;
4752 }
4753
Chris Lattner4200c2062008-06-18 04:00:49 +00004754 Res->takeName(I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004755 return InsertNewInstBefore(Res, *I);
4756}
4757
4758/// @brief Implement the transforms common to all CastInst visitors.
4759Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
4760 Value *Src = CI.getOperand(0);
4761
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004762 // Many cases of "cast of a cast" are eliminable. If it's eliminable we just
4763 // eliminate it now.
4764 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
4765 if (Instruction::CastOps opc =
4766 isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
4767 // The first cast (CSrc) is eliminable so we need to fix up or replace
4768 // the second cast (CI). CSrc will then have a good chance of being dead.
Gabor Greifa645dd32008-05-16 19:29:10 +00004769 return CastInst::Create(opc, CSrc->getOperand(0), CI.getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004770 }
4771 }
4772
4773 // If we are casting a select then fold the cast into the select
4774 if (SelectInst *SI = dyn_cast<SelectInst>(Src))
4775 if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
4776 return NV;
4777
4778 // If we are casting a PHI then fold the cast into the PHI
Chris Lattner1cd526b2009-11-08 19:23:30 +00004779 if (isa<PHINode>(Src)) {
4780 // We don't do this if this would create a PHI node with an illegal type if
4781 // it is currently legal.
4782 if (!isa<IntegerType>(Src->getType()) ||
4783 !isa<IntegerType>(CI.getType()) ||
Chris Lattnerd0011092009-11-10 07:23:37 +00004784 ShouldChangeType(CI.getType(), Src->getType(), TD))
Chris Lattner1cd526b2009-11-08 19:23:30 +00004785 if (Instruction *NV = FoldOpIntoPhi(CI))
4786 return NV;
Chris Lattner1cd526b2009-11-08 19:23:30 +00004787 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004788
4789 return 0;
4790}
4791
Chris Lattner94ccd5f2009-01-09 05:44:56 +00004792/// FindElementAtOffset - Given a type and a constant offset, determine whether
4793/// or not there is a sequence of GEP indices into the type that will land us at
Chris Lattner54dddc72009-01-24 01:00:13 +00004794/// the specified offset. If so, fill them into NewIndices and return the
4795/// resultant element type, otherwise return null.
4796static const Type *FindElementAtOffset(const Type *Ty, int64_t Offset,
4797 SmallVectorImpl<Value*> &NewIndices,
Chris Lattner03a27b42010-01-04 07:02:48 +00004798 const TargetData *TD) {
Dan Gohmana80e2712009-07-21 23:21:54 +00004799 if (!TD) return 0;
Chris Lattner54dddc72009-01-24 01:00:13 +00004800 if (!Ty->isSized()) return 0;
Chris Lattner94ccd5f2009-01-09 05:44:56 +00004801
4802 // Start with the index over the outer type. Note that the type size
4803 // might be zero (even if the offset isn't zero) if the indexed type
4804 // is something like [0 x {int, int}]
Chris Lattner03a27b42010-01-04 07:02:48 +00004805 const Type *IntPtrTy = TD->getIntPtrType(Ty->getContext());
Chris Lattner94ccd5f2009-01-09 05:44:56 +00004806 int64_t FirstIdx = 0;
Duncan Sandsec4f97d2009-05-09 07:06:46 +00004807 if (int64_t TySize = TD->getTypeAllocSize(Ty)) {
Chris Lattner94ccd5f2009-01-09 05:44:56 +00004808 FirstIdx = Offset/TySize;
Chris Lattner0bd6f2b2009-01-11 20:41:36 +00004809 Offset -= FirstIdx*TySize;
Chris Lattner94ccd5f2009-01-09 05:44:56 +00004810
Chris Lattnerce48c462009-01-11 20:15:20 +00004811 // Handle hosts where % returns negative instead of values [0..TySize).
Chris Lattner94ccd5f2009-01-09 05:44:56 +00004812 if (Offset < 0) {
4813 --FirstIdx;
4814 Offset += TySize;
4815 assert(Offset >= 0);
4816 }
4817 assert((uint64_t)Offset < (uint64_t)TySize && "Out of range offset");
4818 }
4819
Owen Andersoneacb44d2009-07-24 23:12:02 +00004820 NewIndices.push_back(ConstantInt::get(IntPtrTy, FirstIdx));
Chris Lattner94ccd5f2009-01-09 05:44:56 +00004821
4822 // Index into the types. If we fail, set OrigBase to null.
4823 while (Offset) {
Chris Lattnerce48c462009-01-11 20:15:20 +00004824 // Indexing into tail padding between struct/array elements.
4825 if (uint64_t(Offset*8) >= TD->getTypeSizeInBits(Ty))
Chris Lattner54dddc72009-01-24 01:00:13 +00004826 return 0;
Chris Lattnerce48c462009-01-11 20:15:20 +00004827
Chris Lattner94ccd5f2009-01-09 05:44:56 +00004828 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
4829 const StructLayout *SL = TD->getStructLayout(STy);
Chris Lattnerce48c462009-01-11 20:15:20 +00004830 assert(Offset < (int64_t)SL->getSizeInBytes() &&
4831 "Offset must stay within the indexed type");
4832
Chris Lattner94ccd5f2009-01-09 05:44:56 +00004833 unsigned Elt = SL->getElementContainingOffset(Offset);
Chris Lattner03a27b42010-01-04 07:02:48 +00004834 NewIndices.push_back(ConstantInt::get(Type::getInt32Ty(Ty->getContext()),
4835 Elt));
Chris Lattner94ccd5f2009-01-09 05:44:56 +00004836
4837 Offset -= SL->getElementOffset(Elt);
4838 Ty = STy->getElementType(Elt);
Chris Lattnerd35ce6a2009-01-11 20:23:52 +00004839 } else if (const ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
Duncan Sandsec4f97d2009-05-09 07:06:46 +00004840 uint64_t EltSize = TD->getTypeAllocSize(AT->getElementType());
Chris Lattnerce48c462009-01-11 20:15:20 +00004841 assert(EltSize && "Cannot index into a zero-sized array");
Owen Andersoneacb44d2009-07-24 23:12:02 +00004842 NewIndices.push_back(ConstantInt::get(IntPtrTy,Offset/EltSize));
Chris Lattnerce48c462009-01-11 20:15:20 +00004843 Offset %= EltSize;
Chris Lattnerd35ce6a2009-01-11 20:23:52 +00004844 Ty = AT->getElementType();
Chris Lattner94ccd5f2009-01-09 05:44:56 +00004845 } else {
Chris Lattnerce48c462009-01-11 20:15:20 +00004846 // Otherwise, we can't index into the middle of this atomic type, bail.
Chris Lattner54dddc72009-01-24 01:00:13 +00004847 return 0;
Chris Lattner94ccd5f2009-01-09 05:44:56 +00004848 }
4849 }
4850
Chris Lattner54dddc72009-01-24 01:00:13 +00004851 return Ty;
Chris Lattner94ccd5f2009-01-09 05:44:56 +00004852}
4853
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004854/// @brief Implement the transforms for cast of pointer (bitcast/ptrtoint)
4855Instruction *InstCombiner::commonPointerCastTransforms(CastInst &CI) {
4856 Value *Src = CI.getOperand(0);
4857
4858 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
4859 // If casting the result of a getelementptr instruction with no offset, turn
4860 // this into a cast of the original pointer!
4861 if (GEP->hasAllZeroIndices()) {
4862 // Changing the cast operand is usually not a good idea but it is safe
4863 // here because the pointer operand is being replaced with another
4864 // pointer operand so the opcode doesn't need to change.
Chris Lattner3183fb62009-08-30 06:13:40 +00004865 Worklist.Add(GEP);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004866 CI.setOperand(0, GEP->getOperand(0));
4867 return &CI;
4868 }
4869
4870 // If the GEP has a single use, and the base pointer is a bitcast, and the
4871 // GEP computes a constant offset, see if we can convert these three
4872 // instructions into fewer. This typically happens with unions and other
4873 // non-type-safe code.
Dan Gohmana80e2712009-07-21 23:21:54 +00004874 if (TD && GEP->hasOneUse() && isa<BitCastInst>(GEP->getOperand(0))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004875 if (GEP->hasAllConstantIndices()) {
4876 // We are guaranteed to get a constant from EmitGEPOffset.
Chris Lattner63ac8422010-01-04 07:37:31 +00004877 ConstantInt *OffsetV = cast<ConstantInt>(EmitGEPOffset(GEP));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004878 int64_t Offset = OffsetV->getSExtValue();
4879
4880 // Get the base pointer input of the bitcast, and the type it points to.
4881 Value *OrigBase = cast<BitCastInst>(GEP->getOperand(0))->getOperand(0);
4882 const Type *GEPIdxTy =
4883 cast<PointerType>(OrigBase->getType())->getElementType();
Chris Lattner94ccd5f2009-01-09 05:44:56 +00004884 SmallVector<Value*, 8> NewIndices;
Chris Lattner03a27b42010-01-04 07:02:48 +00004885 if (FindElementAtOffset(GEPIdxTy, Offset, NewIndices, TD)) {
Chris Lattner94ccd5f2009-01-09 05:44:56 +00004886 // If we were able to index down into an element, create the GEP
4887 // and bitcast the result. This eliminates one bitcast, potentially
4888 // two.
Dan Gohmanf3a08b82009-09-07 23:54:19 +00004889 Value *NGEP = cast<GEPOperator>(GEP)->isInBounds() ?
4890 Builder->CreateInBoundsGEP(OrigBase,
4891 NewIndices.begin(), NewIndices.end()) :
4892 Builder->CreateGEP(OrigBase, NewIndices.begin(), NewIndices.end());
Chris Lattner94ccd5f2009-01-09 05:44:56 +00004893 NGEP->takeName(GEP);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004894
Chris Lattner94ccd5f2009-01-09 05:44:56 +00004895 if (isa<BitCastInst>(CI))
4896 return new BitCastInst(NGEP, CI.getType());
4897 assert(isa<PtrToIntInst>(CI));
4898 return new PtrToIntInst(NGEP, CI.getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004899 }
4900 }
4901 }
4902 }
4903
4904 return commonCastTransforms(CI);
4905}
4906
Eli Friedman827e37a2009-07-13 20:58:59 +00004907/// commonIntCastTransforms - This function implements the common transforms
4908/// for trunc, zext, and sext.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004909Instruction *InstCombiner::commonIntCastTransforms(CastInst &CI) {
4910 if (Instruction *Result = commonCastTransforms(CI))
4911 return Result;
4912
4913 Value *Src = CI.getOperand(0);
4914 const Type *SrcTy = Src->getType();
4915 const Type *DestTy = CI.getType();
Dan Gohman8fd520a2009-06-15 22:12:54 +00004916 uint32_t SrcBitSize = SrcTy->getScalarSizeInBits();
4917 uint32_t DestBitSize = DestTy->getScalarSizeInBits();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004918
4919 // See if we can simplify any instructions used by the LHS whose sole
4920 // purpose is to compute bits we don't care about.
Chris Lattner676c78e2009-01-31 08:15:18 +00004921 if (SimplifyDemandedInstructionBits(CI))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004922 return &CI;
4923
4924 // If the source isn't an instruction or has more than one use then we
4925 // can't do anything more.
4926 Instruction *SrcI = dyn_cast<Instruction>(Src);
4927 if (!SrcI || !Src->hasOneUse())
4928 return 0;
4929
4930 // Attempt to propagate the cast into the instruction for int->int casts.
4931 int NumCastsRemoved = 0;
Eli Friedman1cfc6b42009-07-13 21:45:57 +00004932 // Only do this if the dest type is a simple type, don't convert the
4933 // expression tree to something weird like i93 unless the source is also
4934 // strange.
Chris Lattnerbc5d0132009-11-10 17:00:47 +00004935 if ((isa<VectorType>(DestTy) ||
4936 ShouldChangeType(SrcI->getType(), DestTy, TD)) &&
4937 CanEvaluateInDifferentType(SrcI, DestTy,
4938 CI.getOpcode(), NumCastsRemoved)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004939 // If this cast is a truncate, evaluting in a different type always
Chris Lattneref70bb82007-08-02 06:11:14 +00004940 // eliminates the cast, so it is always a win. If this is a zero-extension,
4941 // we need to do an AND to maintain the clear top-part of the computation,
4942 // so we require that the input have eliminated at least one cast. If this
4943 // is a sign extension, we insert two new casts (to do the extension) so we
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004944 // require that two casts have been eliminated.
Evan Cheng9ca34ab2009-01-15 17:01:23 +00004945 bool DoXForm = false;
4946 bool JustReplace = false;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004947 switch (CI.getOpcode()) {
4948 default:
4949 // All the others use floating point so we shouldn't actually
4950 // get here because of the check above.
Edwin Törökbd448e32009-07-14 16:55:14 +00004951 llvm_unreachable("Unknown cast type");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004952 case Instruction::Trunc:
4953 DoXForm = true;
4954 break;
Evan Cheng814a00c2009-01-16 02:11:43 +00004955 case Instruction::ZExt: {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004956 DoXForm = NumCastsRemoved >= 1;
Chris Lattner2e9f5d02009-11-07 19:11:46 +00004957
Chris Lattner3c0e6f42009-01-31 19:05:27 +00004958 if (!DoXForm && 0) {
Evan Cheng814a00c2009-01-16 02:11:43 +00004959 // If it's unnecessary to issue an AND to clear the high bits, it's
4960 // always profitable to do this xform.
Chris Lattner3c0e6f42009-01-31 19:05:27 +00004961 Value *TryRes = EvaluateInDifferentType(SrcI, DestTy, false);
Evan Cheng814a00c2009-01-16 02:11:43 +00004962 APInt Mask(APInt::getBitsSet(DestBitSize, SrcBitSize, DestBitSize));
4963 if (MaskedValueIsZero(TryRes, Mask))
4964 return ReplaceInstUsesWith(CI, TryRes);
Chris Lattner3c0e6f42009-01-31 19:05:27 +00004965
4966 if (Instruction *TryI = dyn_cast<Instruction>(TryRes))
Evan Cheng814a00c2009-01-16 02:11:43 +00004967 if (TryI->use_empty())
4968 EraseInstFromFunction(*TryI);
4969 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004970 break;
Evan Cheng814a00c2009-01-16 02:11:43 +00004971 }
Evan Cheng9ca34ab2009-01-15 17:01:23 +00004972 case Instruction::SExt: {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004973 DoXForm = NumCastsRemoved >= 2;
Chris Lattner3c0e6f42009-01-31 19:05:27 +00004974 if (!DoXForm && !isa<TruncInst>(SrcI) && 0) {
Evan Cheng814a00c2009-01-16 02:11:43 +00004975 // If we do not have to emit the truncate + sext pair, then it's always
4976 // profitable to do this xform.
Evan Cheng9ca34ab2009-01-15 17:01:23 +00004977 //
4978 // It's not safe to eliminate the trunc + sext pair if one of the
4979 // eliminated cast is a truncate. e.g.
4980 // t2 = trunc i32 t1 to i16
4981 // t3 = sext i16 t2 to i32
4982 // !=
4983 // i32 t1
Chris Lattner3c0e6f42009-01-31 19:05:27 +00004984 Value *TryRes = EvaluateInDifferentType(SrcI, DestTy, true);
Evan Cheng814a00c2009-01-16 02:11:43 +00004985 unsigned NumSignBits = ComputeNumSignBits(TryRes);
4986 if (NumSignBits > (DestBitSize - SrcBitSize))
4987 return ReplaceInstUsesWith(CI, TryRes);
Chris Lattner3c0e6f42009-01-31 19:05:27 +00004988
4989 if (Instruction *TryI = dyn_cast<Instruction>(TryRes))
Evan Cheng814a00c2009-01-16 02:11:43 +00004990 if (TryI->use_empty())
4991 EraseInstFromFunction(*TryI);
Evan Cheng9ca34ab2009-01-15 17:01:23 +00004992 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004993 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004994 }
Evan Cheng9ca34ab2009-01-15 17:01:23 +00004995 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004996
4997 if (DoXForm) {
Chris Lattner8a6411c2009-08-23 04:37:46 +00004998 DEBUG(errs() << "ICE: EvaluateInDifferentType converting expression type"
4999 " to avoid cast: " << CI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005000 Value *Res = EvaluateInDifferentType(SrcI, DestTy,
5001 CI.getOpcode() == Instruction::SExt);
Evan Cheng814a00c2009-01-16 02:11:43 +00005002 if (JustReplace)
Chris Lattner3c0e6f42009-01-31 19:05:27 +00005003 // Just replace this cast with the result.
5004 return ReplaceInstUsesWith(CI, Res);
Evan Cheng814a00c2009-01-16 02:11:43 +00005005
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005006 assert(Res->getType() == DestTy);
5007 switch (CI.getOpcode()) {
Edwin Törökbd448e32009-07-14 16:55:14 +00005008 default: llvm_unreachable("Unknown cast type!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005009 case Instruction::Trunc:
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005010 // Just replace this cast with the result.
5011 return ReplaceInstUsesWith(CI, Res);
5012 case Instruction::ZExt: {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005013 assert(SrcBitSize < DestBitSize && "Not a zext?");
Evan Cheng814a00c2009-01-16 02:11:43 +00005014
5015 // If the high bits are already zero, just replace this cast with the
5016 // result.
5017 APInt Mask(APInt::getBitsSet(DestBitSize, SrcBitSize, DestBitSize));
5018 if (MaskedValueIsZero(Res, Mask))
5019 return ReplaceInstUsesWith(CI, Res);
5020
5021 // We need to emit an AND to clear the high bits.
Chris Lattner03a27b42010-01-04 07:02:48 +00005022 Constant *C = ConstantInt::get(CI.getContext(),
Owen Andersoneacb44d2009-07-24 23:12:02 +00005023 APInt::getLowBitsSet(DestBitSize, SrcBitSize));
Gabor Greifa645dd32008-05-16 19:29:10 +00005024 return BinaryOperator::CreateAnd(Res, C);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005025 }
Evan Cheng814a00c2009-01-16 02:11:43 +00005026 case Instruction::SExt: {
5027 // If the high bits are already filled with sign bit, just replace this
5028 // cast with the result.
5029 unsigned NumSignBits = ComputeNumSignBits(Res);
5030 if (NumSignBits > (DestBitSize - SrcBitSize))
Evan Cheng9ca34ab2009-01-15 17:01:23 +00005031 return ReplaceInstUsesWith(CI, Res);
5032
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005033 // We need to emit a cast to truncate, then a cast to sext.
Chris Lattnerd6164c22009-08-30 20:01:10 +00005034 return new SExtInst(Builder->CreateTrunc(Res, Src->getType()), DestTy);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005035 }
Evan Cheng814a00c2009-01-16 02:11:43 +00005036 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005037 }
5038 }
5039
5040 Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
5041 Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
5042
5043 switch (SrcI->getOpcode()) {
5044 case Instruction::Add:
5045 case Instruction::Mul:
5046 case Instruction::And:
5047 case Instruction::Or:
5048 case Instruction::Xor:
5049 // If we are discarding information, rewrite.
Eli Friedman1cfc6b42009-07-13 21:45:57 +00005050 if (DestBitSize < SrcBitSize && DestBitSize != 1) {
5051 // Don't insert two casts unless at least one can be eliminated.
5052 if (!ValueRequiresCast(CI.getOpcode(), Op1, DestTy, TD) ||
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005053 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
Chris Lattnerd6164c22009-08-30 20:01:10 +00005054 Value *Op0c = Builder->CreateTrunc(Op0, DestTy, Op0->getName());
5055 Value *Op1c = Builder->CreateTrunc(Op1, DestTy, Op1->getName());
Gabor Greifa645dd32008-05-16 19:29:10 +00005056 return BinaryOperator::Create(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005057 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
5058 }
5059 }
5060
5061 // cast (xor bool X, true) to int --> xor (cast bool X to int), 1
5062 if (isa<ZExtInst>(CI) && SrcBitSize == 1 &&
5063 SrcI->getOpcode() == Instruction::Xor &&
Chris Lattner03a27b42010-01-04 07:02:48 +00005064 Op1 == ConstantInt::getTrue(CI.getContext()) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005065 (!Op0->hasOneUse() || !isa<CmpInst>(Op0))) {
Chris Lattnerd6164c22009-08-30 20:01:10 +00005066 Value *New = Builder->CreateZExt(Op0, DestTy, Op0->getName());
Owen Anderson24be4c12009-07-03 00:17:18 +00005067 return BinaryOperator::CreateXor(New,
Owen Andersoneacb44d2009-07-24 23:12:02 +00005068 ConstantInt::get(CI.getType(), 1));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005069 }
5070 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005071
Eli Friedman1cfc6b42009-07-13 21:45:57 +00005072 case Instruction::Shl: {
5073 // Canonicalize trunc inside shl, if we can.
5074 ConstantInt *CI = dyn_cast<ConstantInt>(Op1);
5075 if (CI && DestBitSize < SrcBitSize &&
5076 CI->getLimitedValue(DestBitSize) < DestBitSize) {
Chris Lattnerd6164c22009-08-30 20:01:10 +00005077 Value *Op0c = Builder->CreateTrunc(Op0, DestTy, Op0->getName());
5078 Value *Op1c = Builder->CreateTrunc(Op1, DestTy, Op1->getName());
Gabor Greifa645dd32008-05-16 19:29:10 +00005079 return BinaryOperator::CreateShl(Op0c, Op1c);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005080 }
5081 break;
Eli Friedman1cfc6b42009-07-13 21:45:57 +00005082 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005083 }
5084 return 0;
5085}
5086
5087Instruction *InstCombiner::visitTrunc(TruncInst &CI) {
5088 if (Instruction *Result = commonIntCastTransforms(CI))
5089 return Result;
5090
5091 Value *Src = CI.getOperand(0);
5092 const Type *Ty = CI.getType();
Dan Gohman8fd520a2009-06-15 22:12:54 +00005093 uint32_t DestBitWidth = Ty->getScalarSizeInBits();
5094 uint32_t SrcBitWidth = Src->getType()->getScalarSizeInBits();
Chris Lattner32177f82009-03-24 18:15:30 +00005095
5096 // Canonicalize trunc x to i1 -> (icmp ne (and x, 1), 0)
Eli Friedman37a5d412009-07-18 09:21:25 +00005097 if (DestBitWidth == 1) {
Owen Andersoneacb44d2009-07-24 23:12:02 +00005098 Constant *One = ConstantInt::get(Src->getType(), 1);
Chris Lattnerad7516a2009-08-30 18:50:58 +00005099 Src = Builder->CreateAnd(Src, One, "tmp");
Owen Andersonaac28372009-07-31 20:28:14 +00005100 Value *Zero = Constant::getNullValue(Src->getType());
Dan Gohmane6803b82009-08-25 23:17:54 +00005101 return new ICmpInst(ICmpInst::ICMP_NE, Src, Zero);
Chris Lattner32177f82009-03-24 18:15:30 +00005102 }
Dan Gohman8fd520a2009-06-15 22:12:54 +00005103
Chris Lattner32177f82009-03-24 18:15:30 +00005104 // Optimize trunc(lshr(), c) to pull the shift through the truncate.
5105 ConstantInt *ShAmtV = 0;
5106 Value *ShiftOp = 0;
5107 if (Src->hasOneUse() &&
Dan Gohmancdff2122009-08-12 16:23:25 +00005108 match(Src, m_LShr(m_Value(ShiftOp), m_ConstantInt(ShAmtV)))) {
Chris Lattner32177f82009-03-24 18:15:30 +00005109 uint32_t ShAmt = ShAmtV->getLimitedValue(SrcBitWidth);
5110
5111 // Get a mask for the bits shifting in.
5112 APInt Mask(APInt::getLowBitsSet(SrcBitWidth, ShAmt).shl(DestBitWidth));
5113 if (MaskedValueIsZero(ShiftOp, Mask)) {
5114 if (ShAmt >= DestBitWidth) // All zeros.
Owen Andersonaac28372009-07-31 20:28:14 +00005115 return ReplaceInstUsesWith(CI, Constant::getNullValue(Ty));
Chris Lattner32177f82009-03-24 18:15:30 +00005116
5117 // Okay, we can shrink this. Truncate the input, then return a new
5118 // shift.
Chris Lattnerd6164c22009-08-30 20:01:10 +00005119 Value *V1 = Builder->CreateTrunc(ShiftOp, Ty, ShiftOp->getName());
Owen Anderson02b48c32009-07-29 18:55:55 +00005120 Value *V2 = ConstantExpr::getTrunc(ShAmtV, Ty);
Chris Lattner32177f82009-03-24 18:15:30 +00005121 return BinaryOperator::CreateLShr(V1, V2);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005122 }
5123 }
Chris Lattner1cd526b2009-11-08 19:23:30 +00005124
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005125 return 0;
5126}
5127
Evan Chenge3779cf2008-03-24 00:21:34 +00005128/// transformZExtICmp - Transform (zext icmp) to bitwise / integer operations
5129/// in order to eliminate the icmp.
5130Instruction *InstCombiner::transformZExtICmp(ICmpInst *ICI, Instruction &CI,
5131 bool DoXform) {
5132 // If we are just checking for a icmp eq of a single bit and zext'ing it
5133 // to an integer, then shift the bit to the appropriate place and then
5134 // cast to integer to avoid the comparison.
5135 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
5136 const APInt &Op1CV = Op1C->getValue();
5137
5138 // zext (x <s 0) to i32 --> x>>u31 true if signbit set.
5139 // zext (x >s -1) to i32 --> (x>>u31)^1 true if signbit clear.
5140 if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
5141 (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())) {
5142 if (!DoXform) return ICI;
5143
5144 Value *In = ICI->getOperand(0);
Owen Andersoneacb44d2009-07-24 23:12:02 +00005145 Value *Sh = ConstantInt::get(In->getType(),
Dan Gohman8fd520a2009-06-15 22:12:54 +00005146 In->getType()->getScalarSizeInBits()-1);
Chris Lattnerad7516a2009-08-30 18:50:58 +00005147 In = Builder->CreateLShr(In, Sh, In->getName()+".lobit");
Evan Chenge3779cf2008-03-24 00:21:34 +00005148 if (In->getType() != CI.getType())
Chris Lattnerad7516a2009-08-30 18:50:58 +00005149 In = Builder->CreateIntCast(In, CI.getType(), false/*ZExt*/, "tmp");
Evan Chenge3779cf2008-03-24 00:21:34 +00005150
5151 if (ICI->getPredicate() == ICmpInst::ICMP_SGT) {
Owen Andersoneacb44d2009-07-24 23:12:02 +00005152 Constant *One = ConstantInt::get(In->getType(), 1);
Chris Lattnerad7516a2009-08-30 18:50:58 +00005153 In = Builder->CreateXor(In, One, In->getName()+".not");
Evan Chenge3779cf2008-03-24 00:21:34 +00005154 }
5155
5156 return ReplaceInstUsesWith(CI, In);
5157 }
5158
5159
5160
5161 // zext (X == 0) to i32 --> X^1 iff X has only the low bit set.
5162 // zext (X == 0) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
5163 // zext (X == 1) to i32 --> X iff X has only the low bit set.
5164 // zext (X == 2) to i32 --> X>>1 iff X has only the 2nd bit set.
5165 // zext (X != 0) to i32 --> X iff X has only the low bit set.
5166 // zext (X != 0) to i32 --> X>>1 iff X has only the 2nd bit set.
5167 // zext (X != 1) to i32 --> X^1 iff X has only the low bit set.
5168 // zext (X != 2) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
5169 if ((Op1CV == 0 || Op1CV.isPowerOf2()) &&
5170 // This only works for EQ and NE
5171 ICI->isEquality()) {
5172 // If Op1C some other power of two, convert:
5173 uint32_t BitWidth = Op1C->getType()->getBitWidth();
5174 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
5175 APInt TypeMask(APInt::getAllOnesValue(BitWidth));
5176 ComputeMaskedBits(ICI->getOperand(0), TypeMask, KnownZero, KnownOne);
5177
5178 APInt KnownZeroMask(~KnownZero);
5179 if (KnownZeroMask.isPowerOf2()) { // Exactly 1 possible 1?
5180 if (!DoXform) return ICI;
5181
5182 bool isNE = ICI->getPredicate() == ICmpInst::ICMP_NE;
5183 if (Op1CV != 0 && (Op1CV != KnownZeroMask)) {
5184 // (X&4) == 2 --> false
5185 // (X&4) != 2 --> true
Chris Lattner03a27b42010-01-04 07:02:48 +00005186 Constant *Res = ConstantInt::get(Type::getInt1Ty(CI.getContext()),
5187 isNE);
Owen Anderson02b48c32009-07-29 18:55:55 +00005188 Res = ConstantExpr::getZExt(Res, CI.getType());
Evan Chenge3779cf2008-03-24 00:21:34 +00005189 return ReplaceInstUsesWith(CI, Res);
5190 }
5191
5192 uint32_t ShiftAmt = KnownZeroMask.logBase2();
5193 Value *In = ICI->getOperand(0);
5194 if (ShiftAmt) {
5195 // Perform a logical shr by shiftamt.
5196 // Insert the shift to put the result in the low bit.
Chris Lattnerad7516a2009-08-30 18:50:58 +00005197 In = Builder->CreateLShr(In, ConstantInt::get(In->getType(),ShiftAmt),
5198 In->getName()+".lobit");
Evan Chenge3779cf2008-03-24 00:21:34 +00005199 }
5200
5201 if ((Op1CV != 0) == isNE) { // Toggle the low bit.
Owen Andersoneacb44d2009-07-24 23:12:02 +00005202 Constant *One = ConstantInt::get(In->getType(), 1);
Chris Lattnerad7516a2009-08-30 18:50:58 +00005203 In = Builder->CreateXor(In, One, "tmp");
Evan Chenge3779cf2008-03-24 00:21:34 +00005204 }
5205
5206 if (CI.getType() == In->getType())
5207 return ReplaceInstUsesWith(CI, In);
5208 else
Gabor Greifa645dd32008-05-16 19:29:10 +00005209 return CastInst::CreateIntegerCast(In, CI.getType(), false/*ZExt*/);
Evan Chenge3779cf2008-03-24 00:21:34 +00005210 }
5211 }
5212 }
5213
Nick Lewyckyef61f692009-11-23 03:17:33 +00005214 // icmp ne A, B is equal to xor A, B when A and B only really have one bit.
5215 // It is also profitable to transform icmp eq into not(xor(A, B)) because that
5216 // may lead to additional simplifications.
5217 if (ICI->isEquality() && CI.getType() == ICI->getOperand(0)->getType()) {
5218 if (const IntegerType *ITy = dyn_cast<IntegerType>(CI.getType())) {
5219 uint32_t BitWidth = ITy->getBitWidth();
Nick Lewycky2b7bc812009-12-05 05:00:00 +00005220 Value *LHS = ICI->getOperand(0);
5221 Value *RHS = ICI->getOperand(1);
Nick Lewyckyef61f692009-11-23 03:17:33 +00005222
Nick Lewycky2b7bc812009-12-05 05:00:00 +00005223 APInt KnownZeroLHS(BitWidth, 0), KnownOneLHS(BitWidth, 0);
5224 APInt KnownZeroRHS(BitWidth, 0), KnownOneRHS(BitWidth, 0);
5225 APInt TypeMask(APInt::getAllOnesValue(BitWidth));
5226 ComputeMaskedBits(LHS, TypeMask, KnownZeroLHS, KnownOneLHS);
5227 ComputeMaskedBits(RHS, TypeMask, KnownZeroRHS, KnownOneRHS);
Nick Lewyckyef61f692009-11-23 03:17:33 +00005228
Nick Lewycky2b7bc812009-12-05 05:00:00 +00005229 if (KnownZeroLHS == KnownZeroRHS && KnownOneLHS == KnownOneRHS) {
5230 APInt KnownBits = KnownZeroLHS | KnownOneLHS;
5231 APInt UnknownBit = ~KnownBits;
5232 if (UnknownBit.countPopulation() == 1) {
Nick Lewyckyef61f692009-11-23 03:17:33 +00005233 if (!DoXform) return ICI;
5234
Nick Lewycky2b7bc812009-12-05 05:00:00 +00005235 Value *Result = Builder->CreateXor(LHS, RHS);
5236
5237 // Mask off any bits that are set and won't be shifted away.
5238 if (KnownOneLHS.uge(UnknownBit))
5239 Result = Builder->CreateAnd(Result,
5240 ConstantInt::get(ITy, UnknownBit));
5241
5242 // Shift the bit we're testing down to the lsb.
5243 Result = Builder->CreateLShr(
5244 Result, ConstantInt::get(ITy, UnknownBit.countTrailingZeros()));
5245
Nick Lewyckyef61f692009-11-23 03:17:33 +00005246 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
Nick Lewycky2b7bc812009-12-05 05:00:00 +00005247 Result = Builder->CreateXor(Result, ConstantInt::get(ITy, 1));
5248 Result->takeName(ICI);
5249 return ReplaceInstUsesWith(CI, Result);
Nick Lewyckyef61f692009-11-23 03:17:33 +00005250 }
5251 }
5252 }
5253 }
5254
Evan Chenge3779cf2008-03-24 00:21:34 +00005255 return 0;
5256}
5257
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005258Instruction *InstCombiner::visitZExt(ZExtInst &CI) {
Chris Lattnerfe6c6d12010-01-04 06:23:24 +00005259 // If one of the common conversion will work, do it.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005260 if (Instruction *Result = commonIntCastTransforms(CI))
5261 return Result;
5262
5263 Value *Src = CI.getOperand(0);
5264
Chris Lattner215d56e2009-02-17 20:47:23 +00005265 // If this is a TRUNC followed by a ZEXT then we are dealing with integral
5266 // types and if the sizes are just right we can convert this into a logical
5267 // 'and' which will be much cheaper than the pair of casts.
5268 if (TruncInst *CSrc = dyn_cast<TruncInst>(Src)) { // A->B->C cast
5269 // Get the sizes of the types involved. We know that the intermediate type
5270 // will be smaller than A or C, but don't know the relation between A and C.
5271 Value *A = CSrc->getOperand(0);
Dan Gohman8fd520a2009-06-15 22:12:54 +00005272 unsigned SrcSize = A->getType()->getScalarSizeInBits();
5273 unsigned MidSize = CSrc->getType()->getScalarSizeInBits();
5274 unsigned DstSize = CI.getType()->getScalarSizeInBits();
Chris Lattner215d56e2009-02-17 20:47:23 +00005275 // If we're actually extending zero bits, then if
5276 // SrcSize < DstSize: zext(a & mask)
5277 // SrcSize == DstSize: a & mask
5278 // SrcSize > DstSize: trunc(a) & mask
5279 if (SrcSize < DstSize) {
5280 APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
Owen Andersoneacb44d2009-07-24 23:12:02 +00005281 Constant *AndConst = ConstantInt::get(A->getType(), AndValue);
Chris Lattnerad7516a2009-08-30 18:50:58 +00005282 Value *And = Builder->CreateAnd(A, AndConst, CSrc->getName()+".mask");
Chris Lattner215d56e2009-02-17 20:47:23 +00005283 return new ZExtInst(And, CI.getType());
Chris Lattnerad7516a2009-08-30 18:50:58 +00005284 }
5285
5286 if (SrcSize == DstSize) {
Chris Lattner215d56e2009-02-17 20:47:23 +00005287 APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
Owen Andersoneacb44d2009-07-24 23:12:02 +00005288 return BinaryOperator::CreateAnd(A, ConstantInt::get(A->getType(),
Dan Gohman8fd520a2009-06-15 22:12:54 +00005289 AndValue));
Chris Lattnerad7516a2009-08-30 18:50:58 +00005290 }
5291 if (SrcSize > DstSize) {
5292 Value *Trunc = Builder->CreateTrunc(A, CI.getType(), "tmp");
Chris Lattner215d56e2009-02-17 20:47:23 +00005293 APInt AndValue(APInt::getLowBitsSet(DstSize, MidSize));
Owen Anderson24be4c12009-07-03 00:17:18 +00005294 return BinaryOperator::CreateAnd(Trunc,
Owen Andersoneacb44d2009-07-24 23:12:02 +00005295 ConstantInt::get(Trunc->getType(),
Dan Gohman8fd520a2009-06-15 22:12:54 +00005296 AndValue));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005297 }
5298 }
5299
Evan Chenge3779cf2008-03-24 00:21:34 +00005300 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src))
5301 return transformZExtICmp(ICI, CI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005302
Evan Chenge3779cf2008-03-24 00:21:34 +00005303 BinaryOperator *SrcI = dyn_cast<BinaryOperator>(Src);
5304 if (SrcI && SrcI->getOpcode() == Instruction::Or) {
5305 // zext (or icmp, icmp) --> or (zext icmp), (zext icmp) if at least one
5306 // of the (zext icmp) will be transformed.
5307 ICmpInst *LHS = dyn_cast<ICmpInst>(SrcI->getOperand(0));
5308 ICmpInst *RHS = dyn_cast<ICmpInst>(SrcI->getOperand(1));
5309 if (LHS && RHS && LHS->hasOneUse() && RHS->hasOneUse() &&
5310 (transformZExtICmp(LHS, CI, false) ||
5311 transformZExtICmp(RHS, CI, false))) {
Chris Lattnerd6164c22009-08-30 20:01:10 +00005312 Value *LCast = Builder->CreateZExt(LHS, CI.getType(), LHS->getName());
5313 Value *RCast = Builder->CreateZExt(RHS, CI.getType(), RHS->getName());
Gabor Greifa645dd32008-05-16 19:29:10 +00005314 return BinaryOperator::Create(Instruction::Or, LCast, RCast);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005315 }
Evan Chenge3779cf2008-03-24 00:21:34 +00005316 }
5317
Dan Gohman7ac1e4a2009-06-18 16:30:21 +00005318 // zext(trunc(t) & C) -> (t & zext(C)).
Dan Gohmanead83a52009-06-17 23:17:05 +00005319 if (SrcI && SrcI->getOpcode() == Instruction::And && SrcI->hasOneUse())
5320 if (ConstantInt *C = dyn_cast<ConstantInt>(SrcI->getOperand(1)))
5321 if (TruncInst *TI = dyn_cast<TruncInst>(SrcI->getOperand(0))) {
5322 Value *TI0 = TI->getOperand(0);
Dan Gohman7ac1e4a2009-06-18 16:30:21 +00005323 if (TI0->getType() == CI.getType())
5324 return
5325 BinaryOperator::CreateAnd(TI0,
Owen Anderson02b48c32009-07-29 18:55:55 +00005326 ConstantExpr::getZExt(C, CI.getType()));
Dan Gohmanead83a52009-06-17 23:17:05 +00005327 }
5328
Dan Gohman7ac1e4a2009-06-18 16:30:21 +00005329 // zext((trunc(t) & C) ^ C) -> ((t & zext(C)) ^ zext(C)).
5330 if (SrcI && SrcI->getOpcode() == Instruction::Xor && SrcI->hasOneUse())
5331 if (ConstantInt *C = dyn_cast<ConstantInt>(SrcI->getOperand(1)))
5332 if (BinaryOperator *And = dyn_cast<BinaryOperator>(SrcI->getOperand(0)))
5333 if (And->getOpcode() == Instruction::And && And->hasOneUse() &&
5334 And->getOperand(1) == C)
5335 if (TruncInst *TI = dyn_cast<TruncInst>(And->getOperand(0))) {
5336 Value *TI0 = TI->getOperand(0);
5337 if (TI0->getType() == CI.getType()) {
Owen Anderson02b48c32009-07-29 18:55:55 +00005338 Constant *ZC = ConstantExpr::getZExt(C, CI.getType());
Chris Lattnerad7516a2009-08-30 18:50:58 +00005339 Value *NewAnd = Builder->CreateAnd(TI0, ZC, "tmp");
Dan Gohman7ac1e4a2009-06-18 16:30:21 +00005340 return BinaryOperator::CreateXor(NewAnd, ZC);
5341 }
5342 }
5343
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005344 return 0;
5345}
5346
5347Instruction *InstCombiner::visitSExt(SExtInst &CI) {
5348 if (Instruction *I = commonIntCastTransforms(CI))
5349 return I;
5350
5351 Value *Src = CI.getOperand(0);
5352
Dan Gohman35b76162008-10-30 20:40:10 +00005353 // Canonicalize sign-extend from i1 to a select.
Chris Lattner03a27b42010-01-04 07:02:48 +00005354 if (Src->getType() == Type::getInt1Ty(CI.getContext()))
Dan Gohman35b76162008-10-30 20:40:10 +00005355 return SelectInst::Create(Src,
Owen Andersonaac28372009-07-31 20:28:14 +00005356 Constant::getAllOnesValue(CI.getType()),
5357 Constant::getNullValue(CI.getType()));
Dan Gohmanf0f12022008-05-20 21:01:12 +00005358
5359 // See if the value being truncated is already sign extended. If so, just
5360 // eliminate the trunc/sext pair.
Dan Gohman9545fb02009-07-17 20:47:02 +00005361 if (Operator::getOpcode(Src) == Instruction::Trunc) {
Dan Gohmanf0f12022008-05-20 21:01:12 +00005362 Value *Op = cast<User>(Src)->getOperand(0);
Dan Gohman8fd520a2009-06-15 22:12:54 +00005363 unsigned OpBits = Op->getType()->getScalarSizeInBits();
5364 unsigned MidBits = Src->getType()->getScalarSizeInBits();
5365 unsigned DestBits = CI.getType()->getScalarSizeInBits();
Dan Gohmanf0f12022008-05-20 21:01:12 +00005366 unsigned NumSignBits = ComputeNumSignBits(Op);
5367
5368 if (OpBits == DestBits) {
5369 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign
5370 // bits, it is already ready.
5371 if (NumSignBits > DestBits-MidBits)
5372 return ReplaceInstUsesWith(CI, Op);
5373 } else if (OpBits < DestBits) {
5374 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign
5375 // bits, just sext from i32.
5376 if (NumSignBits > OpBits-MidBits)
5377 return new SExtInst(Op, CI.getType(), "tmp");
5378 } else {
5379 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign
5380 // bits, just truncate to i32.
5381 if (NumSignBits > OpBits-MidBits)
5382 return new TruncInst(Op, CI.getType(), "tmp");
5383 }
5384 }
Chris Lattner8a2d0592008-08-06 07:35:52 +00005385
5386 // If the input is a shl/ashr pair of a same constant, then this is a sign
5387 // extension from a smaller value. If we could trust arbitrary bitwidth
5388 // integers, we could turn this into a truncate to the smaller bit and then
5389 // use a sext for the whole extension. Since we don't, look deeper and check
5390 // for a truncate. If the source and dest are the same type, eliminate the
5391 // trunc and extend and just do shifts. For example, turn:
5392 // %a = trunc i32 %i to i8
5393 // %b = shl i8 %a, 6
5394 // %c = ashr i8 %b, 6
5395 // %d = sext i8 %c to i32
5396 // into:
5397 // %a = shl i32 %i, 30
5398 // %d = ashr i32 %a, 30
5399 Value *A = 0;
5400 ConstantInt *BA = 0, *CA = 0;
5401 if (match(Src, m_AShr(m_Shl(m_Value(A), m_ConstantInt(BA)),
Dan Gohmancdff2122009-08-12 16:23:25 +00005402 m_ConstantInt(CA))) &&
Chris Lattner8a2d0592008-08-06 07:35:52 +00005403 BA == CA && isa<TruncInst>(A)) {
5404 Value *I = cast<TruncInst>(A)->getOperand(0);
5405 if (I->getType() == CI.getType()) {
Dan Gohman8fd520a2009-06-15 22:12:54 +00005406 unsigned MidSize = Src->getType()->getScalarSizeInBits();
5407 unsigned SrcDstSize = CI.getType()->getScalarSizeInBits();
Chris Lattner8a2d0592008-08-06 07:35:52 +00005408 unsigned ShAmt = CA->getZExtValue()+SrcDstSize-MidSize;
Owen Andersoneacb44d2009-07-24 23:12:02 +00005409 Constant *ShAmtV = ConstantInt::get(CI.getType(), ShAmt);
Chris Lattnerad7516a2009-08-30 18:50:58 +00005410 I = Builder->CreateShl(I, ShAmtV, CI.getName());
Chris Lattner8a2d0592008-08-06 07:35:52 +00005411 return BinaryOperator::CreateAShr(I, ShAmtV);
5412 }
5413 }
5414
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005415 return 0;
5416}
5417
Chris Lattnerdf7e8402008-01-27 05:29:54 +00005418/// FitsInFPType - Return a Constant* for the specified FP constant if it fits
5419/// in the specified FP type without changing its value.
Chris Lattner03a27b42010-01-04 07:02:48 +00005420static Constant *FitsInFPType(ConstantFP *CFP, const fltSemantics &Sem) {
Dale Johannesen6e547b42008-10-09 23:00:39 +00005421 bool losesInfo;
Chris Lattnerdf7e8402008-01-27 05:29:54 +00005422 APFloat F = CFP->getValueAPF();
Dale Johannesen6e547b42008-10-09 23:00:39 +00005423 (void)F.convert(Sem, APFloat::rmNearestTiesToEven, &losesInfo);
5424 if (!losesInfo)
Chris Lattner03a27b42010-01-04 07:02:48 +00005425 return ConstantFP::get(CFP->getContext(), F);
Chris Lattnerdf7e8402008-01-27 05:29:54 +00005426 return 0;
5427}
5428
5429/// LookThroughFPExtensions - If this is an fp extension instruction, look
5430/// through it until we get the source value.
Chris Lattner03a27b42010-01-04 07:02:48 +00005431static Value *LookThroughFPExtensions(Value *V) {
Chris Lattnerdf7e8402008-01-27 05:29:54 +00005432 if (Instruction *I = dyn_cast<Instruction>(V))
5433 if (I->getOpcode() == Instruction::FPExt)
Chris Lattner03a27b42010-01-04 07:02:48 +00005434 return LookThroughFPExtensions(I->getOperand(0));
Chris Lattnerdf7e8402008-01-27 05:29:54 +00005435
5436 // If this value is a constant, return the constant in the smallest FP type
5437 // that can accurately represent it. This allows us to turn
5438 // (float)((double)X+2.0) into x+2.0f.
5439 if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
Chris Lattner03a27b42010-01-04 07:02:48 +00005440 if (CFP->getType() == Type::getPPC_FP128Ty(V->getContext()))
Chris Lattnerdf7e8402008-01-27 05:29:54 +00005441 return V; // No constant folding of this.
5442 // See if the value can be truncated to float and then reextended.
Chris Lattner03a27b42010-01-04 07:02:48 +00005443 if (Value *V = FitsInFPType(CFP, APFloat::IEEEsingle))
Chris Lattnerdf7e8402008-01-27 05:29:54 +00005444 return V;
Chris Lattner03a27b42010-01-04 07:02:48 +00005445 if (CFP->getType() == Type::getDoubleTy(V->getContext()))
Chris Lattnerdf7e8402008-01-27 05:29:54 +00005446 return V; // Won't shrink.
Chris Lattner03a27b42010-01-04 07:02:48 +00005447 if (Value *V = FitsInFPType(CFP, APFloat::IEEEdouble))
Chris Lattnerdf7e8402008-01-27 05:29:54 +00005448 return V;
5449 // Don't try to shrink to various long double types.
5450 }
5451
5452 return V;
5453}
5454
5455Instruction *InstCombiner::visitFPTrunc(FPTruncInst &CI) {
5456 if (Instruction *I = commonCastTransforms(CI))
5457 return I;
5458
Dan Gohman7ce405e2009-06-04 22:49:04 +00005459 // If we have fptrunc(fadd (fpextend x), (fpextend y)), where x and y are
Chris Lattnerdf7e8402008-01-27 05:29:54 +00005460 // smaller than the destination type, we can eliminate the truncate by doing
Dan Gohman7ce405e2009-06-04 22:49:04 +00005461 // the add as the smaller type. This applies to fadd/fsub/fmul/fdiv as well as
Chris Lattnerdf7e8402008-01-27 05:29:54 +00005462 // many builtins (sqrt, etc).
5463 BinaryOperator *OpI = dyn_cast<BinaryOperator>(CI.getOperand(0));
5464 if (OpI && OpI->hasOneUse()) {
5465 switch (OpI->getOpcode()) {
5466 default: break;
Dan Gohman7ce405e2009-06-04 22:49:04 +00005467 case Instruction::FAdd:
5468 case Instruction::FSub:
5469 case Instruction::FMul:
Chris Lattnerdf7e8402008-01-27 05:29:54 +00005470 case Instruction::FDiv:
5471 case Instruction::FRem:
5472 const Type *SrcTy = OpI->getType();
Chris Lattner03a27b42010-01-04 07:02:48 +00005473 Value *LHSTrunc = LookThroughFPExtensions(OpI->getOperand(0));
5474 Value *RHSTrunc = LookThroughFPExtensions(OpI->getOperand(1));
Chris Lattnerdf7e8402008-01-27 05:29:54 +00005475 if (LHSTrunc->getType() != SrcTy &&
5476 RHSTrunc->getType() != SrcTy) {
Dan Gohman8fd520a2009-06-15 22:12:54 +00005477 unsigned DstSize = CI.getType()->getScalarSizeInBits();
Chris Lattnerdf7e8402008-01-27 05:29:54 +00005478 // If the source types were both smaller than the destination type of
5479 // the cast, do this xform.
Dan Gohman8fd520a2009-06-15 22:12:54 +00005480 if (LHSTrunc->getType()->getScalarSizeInBits() <= DstSize &&
5481 RHSTrunc->getType()->getScalarSizeInBits() <= DstSize) {
Chris Lattnerd6164c22009-08-30 20:01:10 +00005482 LHSTrunc = Builder->CreateFPExt(LHSTrunc, CI.getType());
5483 RHSTrunc = Builder->CreateFPExt(RHSTrunc, CI.getType());
Gabor Greifa645dd32008-05-16 19:29:10 +00005484 return BinaryOperator::Create(OpI->getOpcode(), LHSTrunc, RHSTrunc);
Chris Lattnerdf7e8402008-01-27 05:29:54 +00005485 }
5486 }
5487 break;
5488 }
5489 }
5490 return 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005491}
5492
5493Instruction *InstCombiner::visitFPExt(CastInst &CI) {
5494 return commonCastTransforms(CI);
5495}
5496
Chris Lattnerdeef1a72008-05-19 20:25:04 +00005497Instruction *InstCombiner::visitFPToUI(FPToUIInst &FI) {
Chris Lattner5f4d6912008-08-06 05:13:06 +00005498 Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
5499 if (OpI == 0)
5500 return commonCastTransforms(FI);
5501
5502 // fptoui(uitofp(X)) --> X
5503 // fptoui(sitofp(X)) --> X
5504 // This is safe if the intermediate type has enough bits in its mantissa to
5505 // accurately represent all values of X. For example, do not do this with
5506 // i64->float->i64. This is also safe for sitofp case, because any negative
5507 // 'X' value would cause an undefined result for the fptoui.
5508 if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
5509 OpI->getOperand(0)->getType() == FI.getType() &&
Dan Gohman8fd520a2009-06-15 22:12:54 +00005510 (int)FI.getType()->getScalarSizeInBits() < /*extra bit for sign */
Chris Lattner5f4d6912008-08-06 05:13:06 +00005511 OpI->getType()->getFPMantissaWidth())
5512 return ReplaceInstUsesWith(FI, OpI->getOperand(0));
Chris Lattnerdeef1a72008-05-19 20:25:04 +00005513
5514 return commonCastTransforms(FI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005515}
5516
Chris Lattnerdeef1a72008-05-19 20:25:04 +00005517Instruction *InstCombiner::visitFPToSI(FPToSIInst &FI) {
Chris Lattner5f4d6912008-08-06 05:13:06 +00005518 Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
5519 if (OpI == 0)
5520 return commonCastTransforms(FI);
5521
5522 // fptosi(sitofp(X)) --> X
5523 // fptosi(uitofp(X)) --> X
5524 // This is safe if the intermediate type has enough bits in its mantissa to
5525 // accurately represent all values of X. For example, do not do this with
5526 // i64->float->i64. This is also safe for sitofp case, because any negative
5527 // 'X' value would cause an undefined result for the fptoui.
5528 if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
5529 OpI->getOperand(0)->getType() == FI.getType() &&
Dan Gohman8fd520a2009-06-15 22:12:54 +00005530 (int)FI.getType()->getScalarSizeInBits() <=
Chris Lattner5f4d6912008-08-06 05:13:06 +00005531 OpI->getType()->getFPMantissaWidth())
5532 return ReplaceInstUsesWith(FI, OpI->getOperand(0));
Chris Lattnerdeef1a72008-05-19 20:25:04 +00005533
5534 return commonCastTransforms(FI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005535}
5536
5537Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
5538 return commonCastTransforms(CI);
5539}
5540
5541Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
5542 return commonCastTransforms(CI);
5543}
5544
Chris Lattner3e10f8d2009-03-24 18:35:40 +00005545Instruction *InstCombiner::visitPtrToInt(PtrToIntInst &CI) {
5546 // If the destination integer type is smaller than the intptr_t type for
5547 // this target, do a ptrtoint to intptr_t then do a trunc. This allows the
5548 // trunc to be exposed to other transforms. Don't do this for extending
5549 // ptrtoint's, because we don't know if the target sign or zero extends its
5550 // pointers.
Dan Gohmana80e2712009-07-21 23:21:54 +00005551 if (TD &&
5552 CI.getType()->getScalarSizeInBits() < TD->getPointerSizeInBits()) {
Chris Lattnerad7516a2009-08-30 18:50:58 +00005553 Value *P = Builder->CreatePtrToInt(CI.getOperand(0),
5554 TD->getIntPtrType(CI.getContext()),
5555 "tmp");
Chris Lattner3e10f8d2009-03-24 18:35:40 +00005556 return new TruncInst(P, CI.getType());
5557 }
5558
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005559 return commonPointerCastTransforms(CI);
5560}
5561
Chris Lattner7c1626482008-01-08 07:23:51 +00005562Instruction *InstCombiner::visitIntToPtr(IntToPtrInst &CI) {
Chris Lattner3e10f8d2009-03-24 18:35:40 +00005563 // If the source integer type is larger than the intptr_t type for
5564 // this target, do a trunc to the intptr_t type, then inttoptr of it. This
5565 // allows the trunc to be exposed to other transforms. Don't do this for
5566 // extending inttoptr's, because we don't know if the target sign or zero
5567 // extends to pointers.
Chris Lattnerad7516a2009-08-30 18:50:58 +00005568 if (TD && CI.getOperand(0)->getType()->getScalarSizeInBits() >
Chris Lattner3e10f8d2009-03-24 18:35:40 +00005569 TD->getPointerSizeInBits()) {
Chris Lattnerad7516a2009-08-30 18:50:58 +00005570 Value *P = Builder->CreateTrunc(CI.getOperand(0),
5571 TD->getIntPtrType(CI.getContext()), "tmp");
Chris Lattner3e10f8d2009-03-24 18:35:40 +00005572 return new IntToPtrInst(P, CI.getType());
5573 }
5574
Chris Lattner7c1626482008-01-08 07:23:51 +00005575 if (Instruction *I = commonCastTransforms(CI))
5576 return I;
Chris Lattner7c1626482008-01-08 07:23:51 +00005577
Chris Lattner7c1626482008-01-08 07:23:51 +00005578 return 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005579}
5580
5581Instruction *InstCombiner::visitBitCast(BitCastInst &CI) {
5582 // If the operands are integer typed then apply the integer transforms,
5583 // otherwise just apply the common ones.
5584 Value *Src = CI.getOperand(0);
5585 const Type *SrcTy = Src->getType();
5586 const Type *DestTy = CI.getType();
5587
Eli Friedman5013d3f2009-07-13 20:53:00 +00005588 if (isa<PointerType>(SrcTy)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005589 if (Instruction *I = commonPointerCastTransforms(CI))
5590 return I;
5591 } else {
5592 if (Instruction *Result = commonCastTransforms(CI))
5593 return Result;
5594 }
5595
5596
5597 // Get rid of casts from one type to the same type. These are useless and can
5598 // be replaced by the operand.
5599 if (DestTy == Src->getType())
5600 return ReplaceInstUsesWith(CI, Src);
5601
5602 if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
5603 const PointerType *SrcPTy = cast<PointerType>(SrcTy);
5604 const Type *DstElTy = DstPTy->getElementType();
5605 const Type *SrcElTy = SrcPTy->getElementType();
5606
Nate Begemandf5b3612008-03-31 00:22:16 +00005607 // If the address spaces don't match, don't eliminate the bitcast, which is
5608 // required for changing types.
5609 if (SrcPTy->getAddressSpace() != DstPTy->getAddressSpace())
5610 return 0;
5611
Victor Hernandez48c3c542009-09-18 22:35:49 +00005612 // If we are casting a alloca to a pointer to a type of the same
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005613 // size, rewrite the allocation instruction to allocate the "right" type.
Victor Hernandez48c3c542009-09-18 22:35:49 +00005614 // There is no need to modify malloc calls because it is their bitcast that
5615 // needs to be cleaned up.
Victor Hernandezb1687302009-10-23 21:09:37 +00005616 if (AllocaInst *AI = dyn_cast<AllocaInst>(Src))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005617 if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
5618 return V;
5619
5620 // If the source and destination are pointers, and this cast is equivalent
5621 // to a getelementptr X, 0, 0, 0... turn it into the appropriate gep.
5622 // This can enhance SROA and other transforms that want type-safe pointers.
Chris Lattner03a27b42010-01-04 07:02:48 +00005623 Constant *ZeroUInt =
5624 Constant::getNullValue(Type::getInt32Ty(CI.getContext()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005625 unsigned NumZeros = 0;
5626 while (SrcElTy != DstElTy &&
5627 isa<CompositeType>(SrcElTy) && !isa<PointerType>(SrcElTy) &&
5628 SrcElTy->getNumContainedTypes() /* not "{}" */) {
5629 SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
5630 ++NumZeros;
5631 }
5632
5633 // If we found a path from the src to dest, create the getelementptr now.
5634 if (SrcElTy == DstElTy) {
5635 SmallVector<Value*, 8> Idxs(NumZeros+1, ZeroUInt);
Chris Lattner03a27b42010-01-04 07:02:48 +00005636 return GetElementPtrInst::CreateInBounds(Src, Idxs.begin(), Idxs.end(),"",
Dan Gohmanf3a08b82009-09-07 23:54:19 +00005637 ((Instruction*) NULL));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005638 }
5639 }
5640
Eli Friedman1d31dee2009-07-18 23:06:53 +00005641 if (const VectorType *DestVTy = dyn_cast<VectorType>(DestTy)) {
5642 if (DestVTy->getNumElements() == 1) {
5643 if (!isa<VectorType>(SrcTy)) {
Chris Lattnerd6164c22009-08-30 20:01:10 +00005644 Value *Elem = Builder->CreateBitCast(Src, DestVTy->getElementType());
Owen Andersonb99ecca2009-07-30 23:03:37 +00005645 return InsertElementInst::Create(UndefValue::get(DestTy), Elem,
Chris Lattner03a27b42010-01-04 07:02:48 +00005646 Constant::getNullValue(Type::getInt32Ty(CI.getContext())));
Eli Friedman1d31dee2009-07-18 23:06:53 +00005647 }
5648 // FIXME: Canonicalize bitcast(insertelement) -> insertelement(bitcast)
5649 }
5650 }
5651
5652 if (const VectorType *SrcVTy = dyn_cast<VectorType>(SrcTy)) {
5653 if (SrcVTy->getNumElements() == 1) {
5654 if (!isa<VectorType>(DestTy)) {
Chris Lattnerad7516a2009-08-30 18:50:58 +00005655 Value *Elem =
5656 Builder->CreateExtractElement(Src,
Chris Lattner03a27b42010-01-04 07:02:48 +00005657 Constant::getNullValue(Type::getInt32Ty(CI.getContext())));
Eli Friedman1d31dee2009-07-18 23:06:53 +00005658 return CastInst::Create(Instruction::BitCast, Elem, DestTy);
5659 }
5660 }
5661 }
5662
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005663 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
5664 if (SVI->hasOneUse()) {
5665 // Okay, we have (bitconvert (shuffle ..)). Check to see if this is
5666 // a bitconvert to a vector with the same # elts.
5667 if (isa<VectorType>(DestTy) &&
Mon P Wangbff5d9c2008-11-10 04:46:22 +00005668 cast<VectorType>(DestTy)->getNumElements() ==
5669 SVI->getType()->getNumElements() &&
5670 SVI->getType()->getNumElements() ==
5671 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005672 CastInst *Tmp;
5673 // If either of the operands is a cast from CI.getType(), then
5674 // evaluating the shuffle in the casted destination's type will allow
5675 // us to eliminate at least one cast.
5676 if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) &&
5677 Tmp->getOperand(0)->getType() == DestTy) ||
5678 ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) &&
5679 Tmp->getOperand(0)->getType() == DestTy)) {
Chris Lattnerd6164c22009-08-30 20:01:10 +00005680 Value *LHS = Builder->CreateBitCast(SVI->getOperand(0), DestTy);
5681 Value *RHS = Builder->CreateBitCast(SVI->getOperand(1), DestTy);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005682 // Return a new shuffle vector. Use the same element ID's, as we
5683 // know the vector types match #elts.
5684 return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
5685 }
5686 }
5687 }
5688 }
5689 return 0;
5690}
5691
5692/// GetSelectFoldableOperands - We want to turn code that looks like this:
5693/// %C = or %A, %B
5694/// %D = select %cond, %C, %A
5695/// into:
5696/// %C = select %cond, %B, 0
5697/// %D = or %A, %C
5698///
5699/// Assuming that the specified instruction is an operand to the select, return
5700/// a bitmask indicating which operands of this instruction are foldable if they
5701/// equal the other incoming value of the select.
5702///
5703static unsigned GetSelectFoldableOperands(Instruction *I) {
5704 switch (I->getOpcode()) {
5705 case Instruction::Add:
5706 case Instruction::Mul:
5707 case Instruction::And:
5708 case Instruction::Or:
5709 case Instruction::Xor:
5710 return 3; // Can fold through either operand.
5711 case Instruction::Sub: // Can only fold on the amount subtracted.
5712 case Instruction::Shl: // Can only fold on the shift amount.
5713 case Instruction::LShr:
5714 case Instruction::AShr:
5715 return 1;
5716 default:
5717 return 0; // Cannot fold
5718 }
5719}
5720
5721/// GetSelectFoldableConstant - For the same transformation as the previous
5722/// function, return the identity constant that goes into the select.
Chris Lattner03a27b42010-01-04 07:02:48 +00005723static Constant *GetSelectFoldableConstant(Instruction *I) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005724 switch (I->getOpcode()) {
Edwin Törökbd448e32009-07-14 16:55:14 +00005725 default: llvm_unreachable("This cannot happen!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005726 case Instruction::Add:
5727 case Instruction::Sub:
5728 case Instruction::Or:
5729 case Instruction::Xor:
5730 case Instruction::Shl:
5731 case Instruction::LShr:
5732 case Instruction::AShr:
Owen Andersonaac28372009-07-31 20:28:14 +00005733 return Constant::getNullValue(I->getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005734 case Instruction::And:
Owen Andersonaac28372009-07-31 20:28:14 +00005735 return Constant::getAllOnesValue(I->getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005736 case Instruction::Mul:
Owen Andersoneacb44d2009-07-24 23:12:02 +00005737 return ConstantInt::get(I->getType(), 1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005738 }
5739}
5740
5741/// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
5742/// have the same opcode and only one use each. Try to simplify this.
5743Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
5744 Instruction *FI) {
5745 if (TI->getNumOperands() == 1) {
5746 // If this is a non-volatile load or a cast from the same type,
5747 // merge.
5748 if (TI->isCast()) {
5749 if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
5750 return 0;
5751 } else {
5752 return 0; // unknown unary op.
5753 }
5754
5755 // Fold this by inserting a select from the input values.
Gabor Greifd6da1d02008-04-06 20:25:17 +00005756 SelectInst *NewSI = SelectInst::Create(SI.getCondition(), TI->getOperand(0),
Eric Christopher3e7381f2009-07-25 02:45:27 +00005757 FI->getOperand(0), SI.getName()+".v");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005758 InsertNewInstBefore(NewSI, SI);
Gabor Greifa645dd32008-05-16 19:29:10 +00005759 return CastInst::Create(Instruction::CastOps(TI->getOpcode()), NewSI,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005760 TI->getType());
5761 }
5762
5763 // Only handle binary operators here.
5764 if (!isa<BinaryOperator>(TI))
5765 return 0;
5766
5767 // Figure out if the operations have any operands in common.
5768 Value *MatchOp, *OtherOpT, *OtherOpF;
5769 bool MatchIsOpZero;
5770 if (TI->getOperand(0) == FI->getOperand(0)) {
5771 MatchOp = TI->getOperand(0);
5772 OtherOpT = TI->getOperand(1);
5773 OtherOpF = FI->getOperand(1);
5774 MatchIsOpZero = true;
5775 } else if (TI->getOperand(1) == FI->getOperand(1)) {
5776 MatchOp = TI->getOperand(1);
5777 OtherOpT = TI->getOperand(0);
5778 OtherOpF = FI->getOperand(0);
5779 MatchIsOpZero = false;
5780 } else if (!TI->isCommutative()) {
5781 return 0;
5782 } else if (TI->getOperand(0) == FI->getOperand(1)) {
5783 MatchOp = TI->getOperand(0);
5784 OtherOpT = TI->getOperand(1);
5785 OtherOpF = FI->getOperand(0);
5786 MatchIsOpZero = true;
5787 } else if (TI->getOperand(1) == FI->getOperand(0)) {
5788 MatchOp = TI->getOperand(1);
5789 OtherOpT = TI->getOperand(0);
5790 OtherOpF = FI->getOperand(1);
5791 MatchIsOpZero = true;
5792 } else {
5793 return 0;
5794 }
5795
5796 // If we reach here, they do have operations in common.
Gabor Greifd6da1d02008-04-06 20:25:17 +00005797 SelectInst *NewSI = SelectInst::Create(SI.getCondition(), OtherOpT,
5798 OtherOpF, SI.getName()+".v");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005799 InsertNewInstBefore(NewSI, SI);
5800
5801 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
5802 if (MatchIsOpZero)
Gabor Greifa645dd32008-05-16 19:29:10 +00005803 return BinaryOperator::Create(BO->getOpcode(), MatchOp, NewSI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005804 else
Gabor Greifa645dd32008-05-16 19:29:10 +00005805 return BinaryOperator::Create(BO->getOpcode(), NewSI, MatchOp);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005806 }
Edwin Törökbd448e32009-07-14 16:55:14 +00005807 llvm_unreachable("Shouldn't get here");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005808 return 0;
5809}
5810
Evan Cheng9f8ee8f2009-03-31 20:42:45 +00005811static bool isSelect01(Constant *C1, Constant *C2) {
5812 ConstantInt *C1I = dyn_cast<ConstantInt>(C1);
5813 if (!C1I)
5814 return false;
5815 ConstantInt *C2I = dyn_cast<ConstantInt>(C2);
5816 if (!C2I)
5817 return false;
5818 return (C1I->isZero() || C1I->isOne()) && (C2I->isZero() || C2I->isOne());
5819}
5820
5821/// FoldSelectIntoOp - Try fold the select into one of the operands to
5822/// facilitate further optimization.
5823Instruction *InstCombiner::FoldSelectIntoOp(SelectInst &SI, Value *TrueVal,
5824 Value *FalseVal) {
5825 // See the comment above GetSelectFoldableOperands for a description of the
5826 // transformation we are doing here.
5827 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal)) {
5828 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
5829 !isa<Constant>(FalseVal)) {
5830 if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
5831 unsigned OpToFold = 0;
5832 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
5833 OpToFold = 1;
5834 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
5835 OpToFold = 2;
5836 }
5837
5838 if (OpToFold) {
Chris Lattner03a27b42010-01-04 07:02:48 +00005839 Constant *C = GetSelectFoldableConstant(TVI);
Evan Cheng9f8ee8f2009-03-31 20:42:45 +00005840 Value *OOp = TVI->getOperand(2-OpToFold);
5841 // Avoid creating select between 2 constants unless it's selecting
5842 // between 0 and 1.
5843 if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
5844 Instruction *NewSel = SelectInst::Create(SI.getCondition(), OOp, C);
5845 InsertNewInstBefore(NewSel, SI);
5846 NewSel->takeName(TVI);
5847 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
5848 return BinaryOperator::Create(BO->getOpcode(), FalseVal, NewSel);
Edwin Törökbd448e32009-07-14 16:55:14 +00005849 llvm_unreachable("Unknown instruction!!");
Evan Cheng9f8ee8f2009-03-31 20:42:45 +00005850 }
5851 }
5852 }
5853 }
5854 }
5855
5856 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal)) {
5857 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
5858 !isa<Constant>(TrueVal)) {
5859 if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
5860 unsigned OpToFold = 0;
5861 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
5862 OpToFold = 1;
5863 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
5864 OpToFold = 2;
5865 }
5866
5867 if (OpToFold) {
Chris Lattner03a27b42010-01-04 07:02:48 +00005868 Constant *C = GetSelectFoldableConstant(FVI);
Evan Cheng9f8ee8f2009-03-31 20:42:45 +00005869 Value *OOp = FVI->getOperand(2-OpToFold);
5870 // Avoid creating select between 2 constants unless it's selecting
5871 // between 0 and 1.
5872 if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
5873 Instruction *NewSel = SelectInst::Create(SI.getCondition(), C, OOp);
5874 InsertNewInstBefore(NewSel, SI);
5875 NewSel->takeName(FVI);
5876 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
5877 return BinaryOperator::Create(BO->getOpcode(), TrueVal, NewSel);
Edwin Törökbd448e32009-07-14 16:55:14 +00005878 llvm_unreachable("Unknown instruction!!");
Evan Cheng9f8ee8f2009-03-31 20:42:45 +00005879 }
5880 }
5881 }
5882 }
5883 }
5884
5885 return 0;
5886}
5887
Dan Gohman58c09632008-09-16 18:46:06 +00005888/// visitSelectInstWithICmp - Visit a SelectInst that has an
5889/// ICmpInst as its first operand.
5890///
5891Instruction *InstCombiner::visitSelectInstWithICmp(SelectInst &SI,
5892 ICmpInst *ICI) {
5893 bool Changed = false;
5894 ICmpInst::Predicate Pred = ICI->getPredicate();
5895 Value *CmpLHS = ICI->getOperand(0);
5896 Value *CmpRHS = ICI->getOperand(1);
5897 Value *TrueVal = SI.getTrueValue();
5898 Value *FalseVal = SI.getFalseValue();
5899
5900 // Check cases where the comparison is with a constant that
5901 // can be adjusted to fit the min/max idiom. We may edit ICI in
5902 // place here, so make sure the select is the only user.
5903 if (ICI->hasOneUse())
Dan Gohman35b76162008-10-30 20:40:10 +00005904 if (ConstantInt *CI = dyn_cast<ConstantInt>(CmpRHS)) {
Dan Gohman58c09632008-09-16 18:46:06 +00005905 switch (Pred) {
5906 default: break;
5907 case ICmpInst::ICMP_ULT:
5908 case ICmpInst::ICMP_SLT: {
5909 // X < MIN ? T : F --> F
5910 if (CI->isMinValue(Pred == ICmpInst::ICMP_SLT))
5911 return ReplaceInstUsesWith(SI, FalseVal);
5912 // X < C ? X : C-1 --> X > C-1 ? C-1 : X
Dan Gohmanfe91cd62009-08-12 16:04:34 +00005913 Constant *AdjustedRHS = SubOne(CI);
Dan Gohman58c09632008-09-16 18:46:06 +00005914 if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
5915 (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
5916 Pred = ICmpInst::getSwappedPredicate(Pred);
5917 CmpRHS = AdjustedRHS;
5918 std::swap(FalseVal, TrueVal);
5919 ICI->setPredicate(Pred);
5920 ICI->setOperand(1, CmpRHS);
5921 SI.setOperand(1, TrueVal);
5922 SI.setOperand(2, FalseVal);
5923 Changed = true;
5924 }
5925 break;
5926 }
5927 case ICmpInst::ICMP_UGT:
5928 case ICmpInst::ICMP_SGT: {
5929 // X > MAX ? T : F --> F
5930 if (CI->isMaxValue(Pred == ICmpInst::ICMP_SGT))
5931 return ReplaceInstUsesWith(SI, FalseVal);
5932 // X > C ? X : C+1 --> X < C+1 ? C+1 : X
Dan Gohmanfe91cd62009-08-12 16:04:34 +00005933 Constant *AdjustedRHS = AddOne(CI);
Dan Gohman58c09632008-09-16 18:46:06 +00005934 if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
5935 (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
5936 Pred = ICmpInst::getSwappedPredicate(Pred);
5937 CmpRHS = AdjustedRHS;
5938 std::swap(FalseVal, TrueVal);
5939 ICI->setPredicate(Pred);
5940 ICI->setOperand(1, CmpRHS);
5941 SI.setOperand(1, TrueVal);
5942 SI.setOperand(2, FalseVal);
5943 Changed = true;
5944 }
5945 break;
5946 }
5947 }
5948
Dan Gohman35b76162008-10-30 20:40:10 +00005949 // (x <s 0) ? -1 : 0 -> ashr x, 31 -> all ones if signed
5950 // (x >s -1) ? -1 : 0 -> ashr x, 31 -> all ones if not signed
Chris Lattner3b874082008-11-16 05:38:51 +00005951 CmpInst::Predicate Pred = CmpInst::BAD_ICMP_PREDICATE;
Dan Gohmancdff2122009-08-12 16:23:25 +00005952 if (match(TrueVal, m_ConstantInt<-1>()) &&
5953 match(FalseVal, m_ConstantInt<0>()))
Chris Lattner3b874082008-11-16 05:38:51 +00005954 Pred = ICI->getPredicate();
Dan Gohmancdff2122009-08-12 16:23:25 +00005955 else if (match(TrueVal, m_ConstantInt<0>()) &&
5956 match(FalseVal, m_ConstantInt<-1>()))
Chris Lattner3b874082008-11-16 05:38:51 +00005957 Pred = CmpInst::getInversePredicate(ICI->getPredicate());
5958
Dan Gohman35b76162008-10-30 20:40:10 +00005959 if (Pred != CmpInst::BAD_ICMP_PREDICATE) {
5960 // If we are just checking for a icmp eq of a single bit and zext'ing it
5961 // to an integer, then shift the bit to the appropriate place and then
5962 // cast to integer to avoid the comparison.
5963 const APInt &Op1CV = CI->getValue();
5964
5965 // sext (x <s 0) to i32 --> x>>s31 true if signbit set.
5966 // sext (x >s -1) to i32 --> (x>>s31)^-1 true if signbit clear.
5967 if ((Pred == ICmpInst::ICMP_SLT && Op1CV == 0) ||
Chris Lattner3b874082008-11-16 05:38:51 +00005968 (Pred == ICmpInst::ICMP_SGT && Op1CV.isAllOnesValue())) {
Dan Gohman35b76162008-10-30 20:40:10 +00005969 Value *In = ICI->getOperand(0);
Owen Andersoneacb44d2009-07-24 23:12:02 +00005970 Value *Sh = ConstantInt::get(In->getType(),
Dan Gohman8fd520a2009-06-15 22:12:54 +00005971 In->getType()->getScalarSizeInBits()-1);
Dan Gohman35b76162008-10-30 20:40:10 +00005972 In = InsertNewInstBefore(BinaryOperator::CreateAShr(In, Sh,
Eric Christopher3e7381f2009-07-25 02:45:27 +00005973 In->getName()+".lobit"),
Dan Gohman35b76162008-10-30 20:40:10 +00005974 *ICI);
Dan Gohman47a60772008-11-02 00:17:33 +00005975 if (In->getType() != SI.getType())
5976 In = CastInst::CreateIntegerCast(In, SI.getType(),
Dan Gohman35b76162008-10-30 20:40:10 +00005977 true/*SExt*/, "tmp", ICI);
5978
5979 if (Pred == ICmpInst::ICMP_SGT)
Dan Gohmancdff2122009-08-12 16:23:25 +00005980 In = InsertNewInstBefore(BinaryOperator::CreateNot(In,
Dan Gohman35b76162008-10-30 20:40:10 +00005981 In->getName()+".not"), *ICI);
5982
5983 return ReplaceInstUsesWith(SI, In);
5984 }
5985 }
5986 }
5987
Dan Gohman58c09632008-09-16 18:46:06 +00005988 if (CmpLHS == TrueVal && CmpRHS == FalseVal) {
5989 // Transform (X == Y) ? X : Y -> Y
5990 if (Pred == ICmpInst::ICMP_EQ)
5991 return ReplaceInstUsesWith(SI, FalseVal);
5992 // Transform (X != Y) ? X : Y -> X
5993 if (Pred == ICmpInst::ICMP_NE)
5994 return ReplaceInstUsesWith(SI, TrueVal);
5995 /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
5996
5997 } else if (CmpLHS == FalseVal && CmpRHS == TrueVal) {
5998 // Transform (X == Y) ? Y : X -> X
5999 if (Pred == ICmpInst::ICMP_EQ)
6000 return ReplaceInstUsesWith(SI, FalseVal);
6001 // Transform (X != Y) ? Y : X -> Y
6002 if (Pred == ICmpInst::ICMP_NE)
6003 return ReplaceInstUsesWith(SI, TrueVal);
6004 /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
6005 }
Dan Gohman58c09632008-09-16 18:46:06 +00006006 return Changed ? &SI : 0;
6007}
6008
Chris Lattnerff5cd9d2009-09-27 20:18:49 +00006009
Chris Lattnerb5ed7f02009-10-22 00:17:26 +00006010/// CanSelectOperandBeMappingIntoPredBlock - SI is a select whose condition is a
6011/// PHI node (but the two may be in different blocks). See if the true/false
6012/// values (V) are live in all of the predecessor blocks of the PHI. For
6013/// example, cases like this cannot be mapped:
6014///
6015/// X = phi [ C1, BB1], [C2, BB2]
6016/// Y = add
6017/// Z = select X, Y, 0
6018///
6019/// because Y is not live in BB1/BB2.
6020///
6021static bool CanSelectOperandBeMappingIntoPredBlock(const Value *V,
6022 const SelectInst &SI) {
6023 // If the value is a non-instruction value like a constant or argument, it
6024 // can always be mapped.
6025 const Instruction *I = dyn_cast<Instruction>(V);
6026 if (I == 0) return true;
6027
6028 // If V is a PHI node defined in the same block as the condition PHI, we can
6029 // map the arguments.
6030 const PHINode *CondPHI = cast<PHINode>(SI.getCondition());
6031
6032 if (const PHINode *VP = dyn_cast<PHINode>(I))
6033 if (VP->getParent() == CondPHI->getParent())
6034 return true;
6035
6036 // Otherwise, if the PHI and select are defined in the same block and if V is
6037 // defined in a different block, then we can transform it.
6038 if (SI.getParent() == CondPHI->getParent() &&
6039 I->getParent() != CondPHI->getParent())
6040 return true;
6041
6042 // Otherwise we have a 'hard' case and we can't tell without doing more
6043 // detailed dominator based analysis, punt.
6044 return false;
6045}
Chris Lattnerff5cd9d2009-09-27 20:18:49 +00006046
Chris Lattner78500cb2009-12-21 06:03:05 +00006047/// FoldSPFofSPF - We have an SPF (e.g. a min or max) of an SPF of the form:
6048/// SPF2(SPF1(A, B), C)
6049Instruction *InstCombiner::FoldSPFofSPF(Instruction *Inner,
6050 SelectPatternFlavor SPF1,
6051 Value *A, Value *B,
6052 Instruction &Outer,
6053 SelectPatternFlavor SPF2, Value *C) {
6054 if (C == A || C == B) {
6055 // MAX(MAX(A, B), B) -> MAX(A, B)
6056 // MIN(MIN(a, b), a) -> MIN(a, b)
6057 if (SPF1 == SPF2)
6058 return ReplaceInstUsesWith(Outer, Inner);
6059
6060 // MAX(MIN(a, b), a) -> a
6061 // MIN(MAX(a, b), a) -> a
Daniel Dunbarb61aa2b2009-12-21 23:27:57 +00006062 if ((SPF1 == SPF_SMIN && SPF2 == SPF_SMAX) ||
6063 (SPF1 == SPF_SMAX && SPF2 == SPF_SMIN) ||
6064 (SPF1 == SPF_UMIN && SPF2 == SPF_UMAX) ||
6065 (SPF1 == SPF_UMAX && SPF2 == SPF_UMIN))
Chris Lattner78500cb2009-12-21 06:03:05 +00006066 return ReplaceInstUsesWith(Outer, C);
6067 }
6068
6069 // TODO: MIN(MIN(A, 23), 97)
6070 return 0;
6071}
6072
6073
6074
6075
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006076Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
6077 Value *CondVal = SI.getCondition();
6078 Value *TrueVal = SI.getTrueValue();
6079 Value *FalseVal = SI.getFalseValue();
6080
6081 // select true, X, Y -> X
6082 // select false, X, Y -> Y
6083 if (ConstantInt *C = dyn_cast<ConstantInt>(CondVal))
6084 return ReplaceInstUsesWith(SI, C->getZExtValue() ? TrueVal : FalseVal);
6085
6086 // select C, X, X -> X
6087 if (TrueVal == FalseVal)
6088 return ReplaceInstUsesWith(SI, TrueVal);
6089
6090 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
6091 return ReplaceInstUsesWith(SI, FalseVal);
6092 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
6093 return ReplaceInstUsesWith(SI, TrueVal);
6094 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
6095 if (isa<Constant>(TrueVal))
6096 return ReplaceInstUsesWith(SI, TrueVal);
6097 else
6098 return ReplaceInstUsesWith(SI, FalseVal);
6099 }
6100
Chris Lattner03a27b42010-01-04 07:02:48 +00006101 if (SI.getType() == Type::getInt1Ty(SI.getContext())) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006102 if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) {
6103 if (C->getZExtValue()) {
6104 // Change: A = select B, true, C --> A = or B, C
Gabor Greifa645dd32008-05-16 19:29:10 +00006105 return BinaryOperator::CreateOr(CondVal, FalseVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006106 } else {
6107 // Change: A = select B, false, C --> A = and !B, C
6108 Value *NotCond =
Dan Gohmancdff2122009-08-12 16:23:25 +00006109 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006110 "not."+CondVal->getName()), SI);
Gabor Greifa645dd32008-05-16 19:29:10 +00006111 return BinaryOperator::CreateAnd(NotCond, FalseVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006112 }
6113 } else if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) {
6114 if (C->getZExtValue() == false) {
6115 // Change: A = select B, C, false --> A = and B, C
Gabor Greifa645dd32008-05-16 19:29:10 +00006116 return BinaryOperator::CreateAnd(CondVal, TrueVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006117 } else {
6118 // Change: A = select B, C, true --> A = or !B, C
6119 Value *NotCond =
Dan Gohmancdff2122009-08-12 16:23:25 +00006120 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006121 "not."+CondVal->getName()), SI);
Gabor Greifa645dd32008-05-16 19:29:10 +00006122 return BinaryOperator::CreateOr(NotCond, TrueVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006123 }
6124 }
Chris Lattner53f85a72007-11-25 21:27:53 +00006125
6126 // select a, b, a -> a&b
6127 // select a, a, b -> a|b
6128 if (CondVal == TrueVal)
Gabor Greifa645dd32008-05-16 19:29:10 +00006129 return BinaryOperator::CreateOr(CondVal, FalseVal);
Chris Lattner53f85a72007-11-25 21:27:53 +00006130 else if (CondVal == FalseVal)
Gabor Greifa645dd32008-05-16 19:29:10 +00006131 return BinaryOperator::CreateAnd(CondVal, TrueVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006132 }
6133
6134 // Selecting between two integer constants?
6135 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
6136 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
6137 // select C, 1, 0 -> zext C to int
6138 if (FalseValC->isZero() && TrueValC->getValue() == 1) {
Gabor Greifa645dd32008-05-16 19:29:10 +00006139 return CastInst::Create(Instruction::ZExt, CondVal, SI.getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006140 } else if (TrueValC->isZero() && FalseValC->getValue() == 1) {
6141 // select C, 0, 1 -> zext !C to int
6142 Value *NotCond =
Dan Gohmancdff2122009-08-12 16:23:25 +00006143 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006144 "not."+CondVal->getName()), SI);
Gabor Greifa645dd32008-05-16 19:29:10 +00006145 return CastInst::Create(Instruction::ZExt, NotCond, SI.getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006146 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006147
6148 if (ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition())) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006149 // If one of the constants is zero (we know they can't both be) and we
6150 // have an icmp instruction with zero, and we have an 'and' with the
6151 // non-constant value, eliminate this whole mess. This corresponds to
6152 // cases like this: ((X & 27) ? 27 : 0)
6153 if (TrueValC->isZero() || FalseValC->isZero())
6154 if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
6155 cast<Constant>(IC->getOperand(1))->isNullValue())
6156 if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
6157 if (ICA->getOpcode() == Instruction::And &&
6158 isa<ConstantInt>(ICA->getOperand(1)) &&
6159 (ICA->getOperand(1) == TrueValC ||
6160 ICA->getOperand(1) == FalseValC) &&
6161 isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
6162 // Okay, now we know that everything is set up, we just don't
6163 // know whether we have a icmp_ne or icmp_eq and whether the
6164 // true or false val is the zero.
6165 bool ShouldNotVal = !TrueValC->isZero();
6166 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
6167 Value *V = ICA;
6168 if (ShouldNotVal)
Gabor Greifa645dd32008-05-16 19:29:10 +00006169 V = InsertNewInstBefore(BinaryOperator::Create(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006170 Instruction::Xor, V, ICA->getOperand(1)), SI);
6171 return ReplaceInstUsesWith(SI, V);
6172 }
6173 }
6174 }
6175
6176 // See if we are selecting two values based on a comparison of the two values.
6177 if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
6178 if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
6179 // Transform (X == Y) ? X : Y -> Y
Dale Johannesen2e1b7692007-10-03 17:45:27 +00006180 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
6181 // This is not safe in general for floating point:
6182 // consider X== -0, Y== +0.
6183 // It becomes safe if either operand is a nonzero constant.
6184 ConstantFP *CFPt, *CFPf;
6185 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
6186 !CFPt->getValueAPF().isZero()) ||
6187 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
6188 !CFPf->getValueAPF().isZero()))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006189 return ReplaceInstUsesWith(SI, FalseVal);
Dale Johannesen2e1b7692007-10-03 17:45:27 +00006190 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006191 // Transform (X != Y) ? X : Y -> X
6192 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
6193 return ReplaceInstUsesWith(SI, TrueVal);
Dan Gohman58c09632008-09-16 18:46:06 +00006194 // NOTE: if we wanted to, this is where to detect MIN/MAX
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006195
6196 } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
6197 // Transform (X == Y) ? Y : X -> X
Dale Johannesen2e1b7692007-10-03 17:45:27 +00006198 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
6199 // This is not safe in general for floating point:
6200 // consider X== -0, Y== +0.
6201 // It becomes safe if either operand is a nonzero constant.
6202 ConstantFP *CFPt, *CFPf;
6203 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
6204 !CFPt->getValueAPF().isZero()) ||
6205 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
6206 !CFPf->getValueAPF().isZero()))
6207 return ReplaceInstUsesWith(SI, FalseVal);
6208 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006209 // Transform (X != Y) ? Y : X -> Y
6210 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
6211 return ReplaceInstUsesWith(SI, TrueVal);
Dan Gohman58c09632008-09-16 18:46:06 +00006212 // NOTE: if we wanted to, this is where to detect MIN/MAX
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006213 }
Dan Gohman58c09632008-09-16 18:46:06 +00006214 // NOTE: if we wanted to, this is where to detect ABS
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006215 }
6216
6217 // See if we are selecting two values based on a comparison of the two values.
Dan Gohman58c09632008-09-16 18:46:06 +00006218 if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal))
6219 if (Instruction *Result = visitSelectInstWithICmp(SI, ICI))
6220 return Result;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006221
6222 if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
6223 if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
6224 if (TI->hasOneUse() && FI->hasOneUse()) {
6225 Instruction *AddOp = 0, *SubOp = 0;
6226
6227 // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
6228 if (TI->getOpcode() == FI->getOpcode())
6229 if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
6230 return IV;
6231
6232 // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))). This is
6233 // even legal for FP.
Dan Gohman7ce405e2009-06-04 22:49:04 +00006234 if ((TI->getOpcode() == Instruction::Sub &&
6235 FI->getOpcode() == Instruction::Add) ||
6236 (TI->getOpcode() == Instruction::FSub &&
6237 FI->getOpcode() == Instruction::FAdd)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006238 AddOp = FI; SubOp = TI;
Dan Gohman7ce405e2009-06-04 22:49:04 +00006239 } else if ((FI->getOpcode() == Instruction::Sub &&
6240 TI->getOpcode() == Instruction::Add) ||
6241 (FI->getOpcode() == Instruction::FSub &&
6242 TI->getOpcode() == Instruction::FAdd)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006243 AddOp = TI; SubOp = FI;
6244 }
6245
6246 if (AddOp) {
6247 Value *OtherAddOp = 0;
6248 if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
6249 OtherAddOp = AddOp->getOperand(1);
6250 } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
6251 OtherAddOp = AddOp->getOperand(0);
6252 }
6253
6254 if (OtherAddOp) {
6255 // So at this point we know we have (Y -> OtherAddOp):
6256 // select C, (add X, Y), (sub X, Z)
6257 Value *NegVal; // Compute -Z
6258 if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
Owen Anderson02b48c32009-07-29 18:55:55 +00006259 NegVal = ConstantExpr::getNeg(C);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006260 } else {
6261 NegVal = InsertNewInstBefore(
Dan Gohmancdff2122009-08-12 16:23:25 +00006262 BinaryOperator::CreateNeg(SubOp->getOperand(1),
Owen Anderson15b39322009-07-13 04:09:18 +00006263 "tmp"), SI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006264 }
6265
6266 Value *NewTrueOp = OtherAddOp;
6267 Value *NewFalseOp = NegVal;
6268 if (AddOp != TI)
6269 std::swap(NewTrueOp, NewFalseOp);
6270 Instruction *NewSel =
Gabor Greifb91ea9d2008-05-15 10:04:30 +00006271 SelectInst::Create(CondVal, NewTrueOp,
6272 NewFalseOp, SI.getName() + ".p");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006273
6274 NewSel = InsertNewInstBefore(NewSel, SI);
Gabor Greifa645dd32008-05-16 19:29:10 +00006275 return BinaryOperator::CreateAdd(SubOp->getOperand(0), NewSel);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006276 }
6277 }
6278 }
6279
6280 // See if we can fold the select into one of our operands.
6281 if (SI.getType()->isInteger()) {
Chris Lattner78500cb2009-12-21 06:03:05 +00006282 if (Instruction *FoldI = FoldSelectIntoOp(SI, TrueVal, FalseVal))
Evan Cheng9f8ee8f2009-03-31 20:42:45 +00006283 return FoldI;
Chris Lattner78500cb2009-12-21 06:03:05 +00006284
6285 // MAX(MAX(a, b), a) -> MAX(a, b)
6286 // MIN(MIN(a, b), a) -> MIN(a, b)
6287 // MAX(MIN(a, b), a) -> a
6288 // MIN(MAX(a, b), a) -> a
6289 Value *LHS, *RHS, *LHS2, *RHS2;
6290 if (SelectPatternFlavor SPF = MatchSelectPattern(&SI, LHS, RHS)) {
6291 if (SelectPatternFlavor SPF2 = MatchSelectPattern(LHS, LHS2, RHS2))
6292 if (Instruction *R = FoldSPFofSPF(cast<Instruction>(LHS),SPF2,LHS2,RHS2,
6293 SI, SPF, RHS))
6294 return R;
6295 if (SelectPatternFlavor SPF2 = MatchSelectPattern(RHS, LHS2, RHS2))
6296 if (Instruction *R = FoldSPFofSPF(cast<Instruction>(RHS),SPF2,LHS2,RHS2,
6297 SI, SPF, LHS))
6298 return R;
6299 }
6300
6301 // TODO.
6302 // ABS(-X) -> ABS(X)
6303 // ABS(ABS(X)) -> ABS(X)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006304 }
6305
Chris Lattnerb5ed7f02009-10-22 00:17:26 +00006306 // See if we can fold the select into a phi node if the condition is a select.
6307 if (isa<PHINode>(SI.getCondition()))
6308 // The true/false values have to be live in the PHI predecessor's blocks.
6309 if (CanSelectOperandBeMappingIntoPredBlock(TrueVal, SI) &&
6310 CanSelectOperandBeMappingIntoPredBlock(FalseVal, SI))
6311 if (Instruction *NV = FoldOpIntoPhi(SI))
6312 return NV;
Chris Lattnerf7843b72009-09-27 19:57:57 +00006313
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006314 if (BinaryOperator::isNot(CondVal)) {
6315 SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
6316 SI.setOperand(1, FalseVal);
6317 SI.setOperand(2, TrueVal);
6318 return &SI;
6319 }
6320
6321 return 0;
6322}
6323
Dan Gohman2d648bb2008-04-10 18:43:06 +00006324/// EnforceKnownAlignment - If the specified pointer points to an object that
6325/// we control, modify the object's alignment to PrefAlign. This isn't
6326/// often possible though. If alignment is important, a more reliable approach
6327/// is to simply align all global variables and allocation instructions to
6328/// their preferred alignment from the beginning.
6329///
6330static unsigned EnforceKnownAlignment(Value *V,
6331 unsigned Align, unsigned PrefAlign) {
Chris Lattner47cf3452007-08-09 19:05:49 +00006332
Dan Gohman2d648bb2008-04-10 18:43:06 +00006333 User *U = dyn_cast<User>(V);
6334 if (!U) return Align;
6335
Dan Gohman9545fb02009-07-17 20:47:02 +00006336 switch (Operator::getOpcode(U)) {
Dan Gohman2d648bb2008-04-10 18:43:06 +00006337 default: break;
6338 case Instruction::BitCast:
6339 return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
6340 case Instruction::GetElementPtr: {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006341 // If all indexes are zero, it is just the alignment of the base pointer.
6342 bool AllZeroOperands = true;
Gabor Greife92fbe22008-06-12 21:51:29 +00006343 for (User::op_iterator i = U->op_begin() + 1, e = U->op_end(); i != e; ++i)
Gabor Greif17396002008-06-12 21:37:33 +00006344 if (!isa<Constant>(*i) ||
6345 !cast<Constant>(*i)->isNullValue()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006346 AllZeroOperands = false;
6347 break;
6348 }
Chris Lattner47cf3452007-08-09 19:05:49 +00006349
6350 if (AllZeroOperands) {
6351 // Treat this like a bitcast.
Dan Gohman2d648bb2008-04-10 18:43:06 +00006352 return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
Chris Lattner47cf3452007-08-09 19:05:49 +00006353 }
Dan Gohman2d648bb2008-04-10 18:43:06 +00006354 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006355 }
Dan Gohman2d648bb2008-04-10 18:43:06 +00006356 }
6357
6358 if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
6359 // If there is a large requested alignment and we can, bump up the alignment
6360 // of the global.
6361 if (!GV->isDeclaration()) {
Dan Gohmanf6fe71e2009-02-16 23:02:21 +00006362 if (GV->getAlignment() >= PrefAlign)
6363 Align = GV->getAlignment();
6364 else {
6365 GV->setAlignment(PrefAlign);
6366 Align = PrefAlign;
6367 }
Dan Gohman2d648bb2008-04-10 18:43:06 +00006368 }
Chris Lattnere8ad9ae2009-09-27 21:42:46 +00006369 } else if (AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
6370 // If there is a requested alignment and if this is an alloca, round up.
6371 if (AI->getAlignment() >= PrefAlign)
6372 Align = AI->getAlignment();
6373 else {
6374 AI->setAlignment(PrefAlign);
6375 Align = PrefAlign;
Dan Gohman2d648bb2008-04-10 18:43:06 +00006376 }
6377 }
6378
6379 return Align;
6380}
6381
6382/// GetOrEnforceKnownAlignment - If the specified pointer has an alignment that
6383/// we can determine, return it, otherwise return 0. If PrefAlign is specified,
6384/// and it is more than the alignment of the ultimate object, see if we can
6385/// increase the alignment of the ultimate object, making this check succeed.
6386unsigned InstCombiner::GetOrEnforceKnownAlignment(Value *V,
6387 unsigned PrefAlign) {
6388 unsigned BitWidth = TD ? TD->getTypeSizeInBits(V->getType()) :
6389 sizeof(PrefAlign) * CHAR_BIT;
6390 APInt Mask = APInt::getAllOnesValue(BitWidth);
6391 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
6392 ComputeMaskedBits(V, Mask, KnownZero, KnownOne);
6393 unsigned TrailZ = KnownZero.countTrailingOnes();
6394 unsigned Align = 1u << std::min(BitWidth - 1, TrailZ);
6395
6396 if (PrefAlign > Align)
6397 Align = EnforceKnownAlignment(V, Align, PrefAlign);
6398
6399 // We don't need to make any adjustment.
6400 return Align;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006401}
6402
Chris Lattner00ae5132008-01-13 23:50:23 +00006403Instruction *InstCombiner::SimplifyMemTransfer(MemIntrinsic *MI) {
Dan Gohman2d648bb2008-04-10 18:43:06 +00006404 unsigned DstAlign = GetOrEnforceKnownAlignment(MI->getOperand(1));
Dan Gohmaneb254912009-02-22 18:06:32 +00006405 unsigned SrcAlign = GetOrEnforceKnownAlignment(MI->getOperand(2));
Chris Lattner00ae5132008-01-13 23:50:23 +00006406 unsigned MinAlign = std::min(DstAlign, SrcAlign);
Chris Lattner3947da72009-03-08 03:59:00 +00006407 unsigned CopyAlign = MI->getAlignment();
Chris Lattner00ae5132008-01-13 23:50:23 +00006408
6409 if (CopyAlign < MinAlign) {
Owen Andersoneacb44d2009-07-24 23:12:02 +00006410 MI->setAlignment(ConstantInt::get(MI->getAlignmentType(),
Owen Andersonf9f99362009-07-09 18:36:20 +00006411 MinAlign, false));
Chris Lattner00ae5132008-01-13 23:50:23 +00006412 return MI;
6413 }
6414
6415 // If MemCpyInst length is 1/2/4/8 bytes then replace memcpy with
6416 // load/store.
6417 ConstantInt *MemOpLength = dyn_cast<ConstantInt>(MI->getOperand(3));
6418 if (MemOpLength == 0) return 0;
6419
Chris Lattnerc669fb62008-01-14 00:28:35 +00006420 // Source and destination pointer types are always "i8*" for intrinsic. See
6421 // if the size is something we can handle with a single primitive load/store.
6422 // A single load+store correctly handles overlapping memory in the memmove
6423 // case.
Chris Lattner00ae5132008-01-13 23:50:23 +00006424 unsigned Size = MemOpLength->getZExtValue();
Chris Lattner5af8a912008-04-30 06:39:11 +00006425 if (Size == 0) return MI; // Delete this mem transfer.
6426
6427 if (Size > 8 || (Size&(Size-1)))
Chris Lattnerc669fb62008-01-14 00:28:35 +00006428 return 0; // If not 1/2/4/8 bytes, exit.
Chris Lattner00ae5132008-01-13 23:50:23 +00006429
Chris Lattnerc669fb62008-01-14 00:28:35 +00006430 // Use an integer load+store unless we can find something better.
Owen Anderson24be4c12009-07-03 00:17:18 +00006431 Type *NewPtrTy =
Chris Lattner03a27b42010-01-04 07:02:48 +00006432 PointerType::getUnqual(IntegerType::get(MI->getContext(), Size<<3));
Chris Lattnerc669fb62008-01-14 00:28:35 +00006433
6434 // Memcpy forces the use of i8* for the source and destination. That means
6435 // that if you're using memcpy to move one double around, you'll get a cast
6436 // from double* to i8*. We'd much rather use a double load+store rather than
6437 // an i64 load+store, here because this improves the odds that the source or
6438 // dest address will be promotable. See if we can find a better type than the
6439 // integer datatype.
6440 if (Value *Op = getBitCastOperand(MI->getOperand(1))) {
6441 const Type *SrcETy = cast<PointerType>(Op->getType())->getElementType();
Dan Gohmana80e2712009-07-21 23:21:54 +00006442 if (TD && SrcETy->isSized() && TD->getTypeStoreSize(SrcETy) == Size) {
Chris Lattnerc669fb62008-01-14 00:28:35 +00006443 // The SrcETy might be something like {{{double}}} or [1 x double]. Rip
6444 // down through these levels if so.
Dan Gohmanb8e94f62008-05-23 01:52:21 +00006445 while (!SrcETy->isSingleValueType()) {
Chris Lattnerc669fb62008-01-14 00:28:35 +00006446 if (const StructType *STy = dyn_cast<StructType>(SrcETy)) {
6447 if (STy->getNumElements() == 1)
6448 SrcETy = STy->getElementType(0);
6449 else
6450 break;
6451 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcETy)) {
6452 if (ATy->getNumElements() == 1)
6453 SrcETy = ATy->getElementType();
6454 else
6455 break;
6456 } else
6457 break;
6458 }
6459
Dan Gohmanb8e94f62008-05-23 01:52:21 +00006460 if (SrcETy->isSingleValueType())
Owen Anderson6b6e2d92009-07-29 22:17:13 +00006461 NewPtrTy = PointerType::getUnqual(SrcETy);
Chris Lattnerc669fb62008-01-14 00:28:35 +00006462 }
6463 }
6464
6465
Chris Lattner00ae5132008-01-13 23:50:23 +00006466 // If the memcpy/memmove provides better alignment info than we can
6467 // infer, use it.
6468 SrcAlign = std::max(SrcAlign, CopyAlign);
6469 DstAlign = std::max(DstAlign, CopyAlign);
6470
Chris Lattner78628292009-08-30 19:47:22 +00006471 Value *Src = Builder->CreateBitCast(MI->getOperand(2), NewPtrTy);
6472 Value *Dest = Builder->CreateBitCast(MI->getOperand(1), NewPtrTy);
Chris Lattnerc669fb62008-01-14 00:28:35 +00006473 Instruction *L = new LoadInst(Src, "tmp", false, SrcAlign);
6474 InsertNewInstBefore(L, *MI);
6475 InsertNewInstBefore(new StoreInst(L, Dest, false, DstAlign), *MI);
6476
6477 // Set the size of the copy to 0, it will be deleted on the next iteration.
Owen Andersonaac28372009-07-31 20:28:14 +00006478 MI->setOperand(3, Constant::getNullValue(MemOpLength->getType()));
Chris Lattnerc669fb62008-01-14 00:28:35 +00006479 return MI;
Chris Lattner00ae5132008-01-13 23:50:23 +00006480}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006481
Chris Lattner5af8a912008-04-30 06:39:11 +00006482Instruction *InstCombiner::SimplifyMemSet(MemSetInst *MI) {
6483 unsigned Alignment = GetOrEnforceKnownAlignment(MI->getDest());
Chris Lattner3947da72009-03-08 03:59:00 +00006484 if (MI->getAlignment() < Alignment) {
Owen Andersoneacb44d2009-07-24 23:12:02 +00006485 MI->setAlignment(ConstantInt::get(MI->getAlignmentType(),
Owen Andersonf9f99362009-07-09 18:36:20 +00006486 Alignment, false));
Chris Lattner5af8a912008-04-30 06:39:11 +00006487 return MI;
6488 }
6489
6490 // Extract the length and alignment and fill if they are constant.
6491 ConstantInt *LenC = dyn_cast<ConstantInt>(MI->getLength());
6492 ConstantInt *FillC = dyn_cast<ConstantInt>(MI->getValue());
Chris Lattner03a27b42010-01-04 07:02:48 +00006493 if (!LenC || !FillC || FillC->getType() != Type::getInt8Ty(MI->getContext()))
Chris Lattner5af8a912008-04-30 06:39:11 +00006494 return 0;
6495 uint64_t Len = LenC->getZExtValue();
Chris Lattner3947da72009-03-08 03:59:00 +00006496 Alignment = MI->getAlignment();
Chris Lattner5af8a912008-04-30 06:39:11 +00006497
6498 // If the length is zero, this is a no-op
6499 if (Len == 0) return MI; // memset(d,c,0,a) -> noop
6500
6501 // memset(s,c,n) -> store s, c (for n=1,2,4,8)
6502 if (Len <= 8 && isPowerOf2_32((uint32_t)Len)) {
Chris Lattner03a27b42010-01-04 07:02:48 +00006503 const Type *ITy = IntegerType::get(MI->getContext(), Len*8); // n=1 -> i8.
Chris Lattner5af8a912008-04-30 06:39:11 +00006504
6505 Value *Dest = MI->getDest();
Chris Lattner78628292009-08-30 19:47:22 +00006506 Dest = Builder->CreateBitCast(Dest, PointerType::getUnqual(ITy));
Chris Lattner5af8a912008-04-30 06:39:11 +00006507
6508 // Alignment 0 is identity for alignment 1 for memset, but not store.
6509 if (Alignment == 0) Alignment = 1;
6510
6511 // Extract the fill value and store.
6512 uint64_t Fill = FillC->getZExtValue()*0x0101010101010101ULL;
Owen Andersoneacb44d2009-07-24 23:12:02 +00006513 InsertNewInstBefore(new StoreInst(ConstantInt::get(ITy, Fill),
Owen Anderson24be4c12009-07-03 00:17:18 +00006514 Dest, false, Alignment), *MI);
Chris Lattner5af8a912008-04-30 06:39:11 +00006515
6516 // Set the size of the copy to 0, it will be deleted on the next iteration.
Owen Andersonaac28372009-07-31 20:28:14 +00006517 MI->setLength(Constant::getNullValue(LenC->getType()));
Chris Lattner5af8a912008-04-30 06:39:11 +00006518 return MI;
6519 }
6520
6521 return 0;
6522}
6523
6524
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006525/// visitCallInst - CallInst simplification. This mostly only handles folding
6526/// of intrinsic instructions. For normal calls, it allows visitCallSite to do
6527/// the heavy lifting.
6528///
6529Instruction *InstCombiner::visitCallInst(CallInst &CI) {
Victor Hernandez93946082009-10-24 04:23:03 +00006530 if (isFreeCall(&CI))
6531 return visitFree(CI);
6532
Chris Lattneraa295aa2009-05-13 17:39:14 +00006533 // If the caller function is nounwind, mark the call as nounwind, even if the
6534 // callee isn't.
6535 if (CI.getParent()->getParent()->doesNotThrow() &&
6536 !CI.doesNotThrow()) {
6537 CI.setDoesNotThrow();
6538 return &CI;
6539 }
6540
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006541 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
6542 if (!II) return visitCallSite(&CI);
6543
6544 // Intrinsics cannot occur in an invoke, so handle them here instead of in
6545 // visitCallSite.
6546 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
6547 bool Changed = false;
6548
6549 // memmove/cpy/set of zero bytes is a noop.
6550 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
6551 if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
6552
6553 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
6554 if (CI->getZExtValue() == 1) {
6555 // Replace the instruction with just byte operations. We would
6556 // transform other cases to loads/stores, but we don't know if
6557 // alignment is sufficient.
6558 }
6559 }
6560
6561 // If we have a memmove and the source operation is a constant global,
6562 // then the source and dest pointers can't alias, so we can change this
6563 // into a call to memcpy.
Chris Lattner00ae5132008-01-13 23:50:23 +00006564 if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006565 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
6566 if (GVSrc->isConstant()) {
6567 Module *M = CI.getParent()->getParent()->getParent();
Chris Lattner82c2e432008-11-21 16:42:48 +00006568 Intrinsic::ID MemCpyID = Intrinsic::memcpy;
6569 const Type *Tys[1];
6570 Tys[0] = CI.getOperand(3)->getType();
6571 CI.setOperand(0,
6572 Intrinsic::getDeclaration(M, MemCpyID, Tys, 1));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006573 Changed = true;
6574 }
Eli Friedman626e32a2009-12-17 21:07:31 +00006575 }
Chris Lattner59b27d92008-05-28 05:30:41 +00006576
Eli Friedman626e32a2009-12-17 21:07:31 +00006577 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(MI)) {
Chris Lattner59b27d92008-05-28 05:30:41 +00006578 // memmove(x,x,size) -> noop.
Eli Friedman626e32a2009-12-17 21:07:31 +00006579 if (MTI->getSource() == MTI->getDest())
Chris Lattner59b27d92008-05-28 05:30:41 +00006580 return EraseInstFromFunction(CI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006581 }
6582
6583 // If we can determine a pointer alignment that is bigger than currently
6584 // set, update the alignment.
Chris Lattnera86628a2009-03-08 03:37:16 +00006585 if (isa<MemTransferInst>(MI)) {
Chris Lattner00ae5132008-01-13 23:50:23 +00006586 if (Instruction *I = SimplifyMemTransfer(MI))
6587 return I;
Chris Lattner5af8a912008-04-30 06:39:11 +00006588 } else if (MemSetInst *MSI = dyn_cast<MemSetInst>(MI)) {
6589 if (Instruction *I = SimplifyMemSet(MSI))
6590 return I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006591 }
6592
6593 if (Changed) return II;
Chris Lattner989ba312008-06-18 04:33:20 +00006594 }
6595
6596 switch (II->getIntrinsicID()) {
6597 default: break;
6598 case Intrinsic::bswap:
6599 // bswap(bswap(x)) -> x
6600 if (IntrinsicInst *Operand = dyn_cast<IntrinsicInst>(II->getOperand(1)))
6601 if (Operand->getIntrinsicID() == Intrinsic::bswap)
6602 return ReplaceInstUsesWith(CI, Operand->getOperand(1));
Chris Lattner723b9642010-01-01 18:34:40 +00006603
6604 // bswap(trunc(bswap(x))) -> trunc(lshr(x, c))
6605 if (TruncInst *TI = dyn_cast<TruncInst>(II->getOperand(1))) {
6606 if (IntrinsicInst *Operand = dyn_cast<IntrinsicInst>(TI->getOperand(0)))
6607 if (Operand->getIntrinsicID() == Intrinsic::bswap) {
6608 unsigned C = Operand->getType()->getPrimitiveSizeInBits() -
6609 TI->getType()->getPrimitiveSizeInBits();
6610 Value *CV = ConstantInt::get(Operand->getType(), C);
6611 Value *V = Builder->CreateLShr(Operand->getOperand(1), CV);
6612 return new TruncInst(V, TI->getType());
6613 }
6614 }
6615
Chris Lattner989ba312008-06-18 04:33:20 +00006616 break;
Chris Lattnerfd4f21a2010-01-01 01:52:15 +00006617 case Intrinsic::powi:
6618 if (ConstantInt *Power = dyn_cast<ConstantInt>(II->getOperand(2))) {
6619 // powi(x, 0) -> 1.0
6620 if (Power->isZero())
6621 return ReplaceInstUsesWith(CI, ConstantFP::get(CI.getType(), 1.0));
6622 // powi(x, 1) -> x
6623 if (Power->isOne())
6624 return ReplaceInstUsesWith(CI, II->getOperand(1));
6625 // powi(x, -1) -> 1/x
Chris Lattner60179fb2010-01-01 01:54:08 +00006626 if (Power->isAllOnesValue())
6627 return BinaryOperator::CreateFDiv(ConstantFP::get(CI.getType(), 1.0),
6628 II->getOperand(1));
Chris Lattnerfd4f21a2010-01-01 01:52:15 +00006629 }
6630 break;
6631
Chris Lattner0b452262009-11-26 21:42:47 +00006632 case Intrinsic::uadd_with_overflow: {
6633 Value *LHS = II->getOperand(1), *RHS = II->getOperand(2);
6634 const IntegerType *IT = cast<IntegerType>(II->getOperand(1)->getType());
6635 uint32_t BitWidth = IT->getBitWidth();
6636 APInt Mask = APInt::getSignBit(BitWidth);
Chris Lattner65e34842009-11-26 22:08:06 +00006637 APInt LHSKnownZero(BitWidth, 0);
6638 APInt LHSKnownOne(BitWidth, 0);
Chris Lattner0b452262009-11-26 21:42:47 +00006639 ComputeMaskedBits(LHS, Mask, LHSKnownZero, LHSKnownOne);
6640 bool LHSKnownNegative = LHSKnownOne[BitWidth - 1];
6641 bool LHSKnownPositive = LHSKnownZero[BitWidth - 1];
6642
6643 if (LHSKnownNegative || LHSKnownPositive) {
Chris Lattner65e34842009-11-26 22:08:06 +00006644 APInt RHSKnownZero(BitWidth, 0);
6645 APInt RHSKnownOne(BitWidth, 0);
Chris Lattner0b452262009-11-26 21:42:47 +00006646 ComputeMaskedBits(RHS, Mask, RHSKnownZero, RHSKnownOne);
6647 bool RHSKnownNegative = RHSKnownOne[BitWidth - 1];
6648 bool RHSKnownPositive = RHSKnownZero[BitWidth - 1];
6649 if (LHSKnownNegative && RHSKnownNegative) {
6650 // The sign bit is set in both cases: this MUST overflow.
6651 // Create a simple add instruction, and insert it into the struct.
6652 Instruction *Add = BinaryOperator::CreateAdd(LHS, RHS, "", &CI);
6653 Worklist.Add(Add);
Chris Lattnerdbbf1b22009-11-29 02:57:29 +00006654 Constant *V[] = {
Chris Lattner03a27b42010-01-04 07:02:48 +00006655 UndefValue::get(LHS->getType()),ConstantInt::getTrue(II->getContext())
Chris Lattnerdbbf1b22009-11-29 02:57:29 +00006656 };
Chris Lattner03a27b42010-01-04 07:02:48 +00006657 Constant *Struct = ConstantStruct::get(II->getContext(), V, 2, false);
Chris Lattner0b452262009-11-26 21:42:47 +00006658 return InsertValueInst::Create(Struct, Add, 0);
6659 }
6660
6661 if (LHSKnownPositive && RHSKnownPositive) {
6662 // The sign bit is clear in both cases: this CANNOT overflow.
6663 // Create a simple add instruction, and insert it into the struct.
6664 Instruction *Add = BinaryOperator::CreateNUWAdd(LHS, RHS, "", &CI);
6665 Worklist.Add(Add);
Chris Lattnerdbbf1b22009-11-29 02:57:29 +00006666 Constant *V[] = {
Chris Lattner03a27b42010-01-04 07:02:48 +00006667 UndefValue::get(LHS->getType()),
6668 ConstantInt::getFalse(II->getContext())
Chris Lattnerdbbf1b22009-11-29 02:57:29 +00006669 };
Chris Lattner03a27b42010-01-04 07:02:48 +00006670 Constant *Struct = ConstantStruct::get(II->getContext(), V, 2, false);
Chris Lattner0b452262009-11-26 21:42:47 +00006671 return InsertValueInst::Create(Struct, Add, 0);
6672 }
6673 }
6674 }
6675 // FALL THROUGH uadd into sadd
6676 case Intrinsic::sadd_with_overflow:
6677 // Canonicalize constants into the RHS.
6678 if (isa<Constant>(II->getOperand(1)) &&
6679 !isa<Constant>(II->getOperand(2))) {
6680 Value *LHS = II->getOperand(1);
6681 II->setOperand(1, II->getOperand(2));
6682 II->setOperand(2, LHS);
6683 return II;
6684 }
6685
6686 // X + undef -> undef
6687 if (isa<UndefValue>(II->getOperand(2)))
6688 return ReplaceInstUsesWith(CI, UndefValue::get(II->getType()));
6689
6690 if (ConstantInt *RHS = dyn_cast<ConstantInt>(II->getOperand(2))) {
6691 // X + 0 -> {X, false}
6692 if (RHS->isZero()) {
6693 Constant *V[] = {
Chris Lattnerdbbf1b22009-11-29 02:57:29 +00006694 UndefValue::get(II->getOperand(0)->getType()),
Chris Lattner03a27b42010-01-04 07:02:48 +00006695 ConstantInt::getFalse(II->getContext())
Chris Lattner0b452262009-11-26 21:42:47 +00006696 };
Chris Lattner03a27b42010-01-04 07:02:48 +00006697 Constant *Struct = ConstantStruct::get(II->getContext(), V, 2, false);
Chris Lattner0b452262009-11-26 21:42:47 +00006698 return InsertValueInst::Create(Struct, II->getOperand(1), 0);
6699 }
6700 }
6701 break;
6702 case Intrinsic::usub_with_overflow:
6703 case Intrinsic::ssub_with_overflow:
6704 // undef - X -> undef
6705 // X - undef -> undef
6706 if (isa<UndefValue>(II->getOperand(1)) ||
6707 isa<UndefValue>(II->getOperand(2)))
6708 return ReplaceInstUsesWith(CI, UndefValue::get(II->getType()));
6709
6710 if (ConstantInt *RHS = dyn_cast<ConstantInt>(II->getOperand(2))) {
6711 // X - 0 -> {X, false}
6712 if (RHS->isZero()) {
6713 Constant *V[] = {
Chris Lattnerdbbf1b22009-11-29 02:57:29 +00006714 UndefValue::get(II->getOperand(1)->getType()),
Chris Lattner03a27b42010-01-04 07:02:48 +00006715 ConstantInt::getFalse(II->getContext())
Chris Lattner0b452262009-11-26 21:42:47 +00006716 };
Chris Lattner03a27b42010-01-04 07:02:48 +00006717 Constant *Struct = ConstantStruct::get(II->getContext(), V, 2, false);
Chris Lattner0b452262009-11-26 21:42:47 +00006718 return InsertValueInst::Create(Struct, II->getOperand(1), 0);
6719 }
6720 }
6721 break;
6722 case Intrinsic::umul_with_overflow:
6723 case Intrinsic::smul_with_overflow:
6724 // Canonicalize constants into the RHS.
6725 if (isa<Constant>(II->getOperand(1)) &&
6726 !isa<Constant>(II->getOperand(2))) {
6727 Value *LHS = II->getOperand(1);
6728 II->setOperand(1, II->getOperand(2));
6729 II->setOperand(2, LHS);
6730 return II;
6731 }
6732
6733 // X * undef -> undef
6734 if (isa<UndefValue>(II->getOperand(2)))
6735 return ReplaceInstUsesWith(CI, UndefValue::get(II->getType()));
6736
6737 if (ConstantInt *RHSI = dyn_cast<ConstantInt>(II->getOperand(2))) {
6738 // X*0 -> {0, false}
6739 if (RHSI->isZero())
6740 return ReplaceInstUsesWith(CI, Constant::getNullValue(II->getType()));
6741
6742 // X * 1 -> {X, false}
6743 if (RHSI->equalsInt(1)) {
Chris Lattnerdbbf1b22009-11-29 02:57:29 +00006744 Constant *V[] = {
6745 UndefValue::get(II->getOperand(1)->getType()),
Chris Lattner03a27b42010-01-04 07:02:48 +00006746 ConstantInt::getFalse(II->getContext())
Chris Lattnerdbbf1b22009-11-29 02:57:29 +00006747 };
Chris Lattner03a27b42010-01-04 07:02:48 +00006748 Constant *Struct = ConstantStruct::get(II->getContext(), V, 2, false);
Chris Lattnerdbbf1b22009-11-29 02:57:29 +00006749 return InsertValueInst::Create(Struct, II->getOperand(1), 0);
Chris Lattner0b452262009-11-26 21:42:47 +00006750 }
6751 }
6752 break;
Chris Lattner989ba312008-06-18 04:33:20 +00006753 case Intrinsic::ppc_altivec_lvx:
6754 case Intrinsic::ppc_altivec_lvxl:
6755 case Intrinsic::x86_sse_loadu_ps:
6756 case Intrinsic::x86_sse2_loadu_pd:
6757 case Intrinsic::x86_sse2_loadu_dq:
6758 // Turn PPC lvx -> load if the pointer is known aligned.
6759 // Turn X86 loadups -> load if the pointer is known aligned.
6760 if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
Chris Lattner78628292009-08-30 19:47:22 +00006761 Value *Ptr = Builder->CreateBitCast(II->getOperand(1),
6762 PointerType::getUnqual(II->getType()));
Chris Lattner989ba312008-06-18 04:33:20 +00006763 return new LoadInst(Ptr);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006764 }
Chris Lattner989ba312008-06-18 04:33:20 +00006765 break;
6766 case Intrinsic::ppc_altivec_stvx:
6767 case Intrinsic::ppc_altivec_stvxl:
6768 // Turn stvx -> store if the pointer is known aligned.
6769 if (GetOrEnforceKnownAlignment(II->getOperand(2), 16) >= 16) {
6770 const Type *OpPtrTy =
Owen Anderson6b6e2d92009-07-29 22:17:13 +00006771 PointerType::getUnqual(II->getOperand(1)->getType());
Chris Lattner78628292009-08-30 19:47:22 +00006772 Value *Ptr = Builder->CreateBitCast(II->getOperand(2), OpPtrTy);
Chris Lattner989ba312008-06-18 04:33:20 +00006773 return new StoreInst(II->getOperand(1), Ptr);
6774 }
6775 break;
6776 case Intrinsic::x86_sse_storeu_ps:
6777 case Intrinsic::x86_sse2_storeu_pd:
6778 case Intrinsic::x86_sse2_storeu_dq:
Chris Lattner989ba312008-06-18 04:33:20 +00006779 // Turn X86 storeu -> store if the pointer is known aligned.
6780 if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
6781 const Type *OpPtrTy =
Owen Anderson6b6e2d92009-07-29 22:17:13 +00006782 PointerType::getUnqual(II->getOperand(2)->getType());
Chris Lattner78628292009-08-30 19:47:22 +00006783 Value *Ptr = Builder->CreateBitCast(II->getOperand(1), OpPtrTy);
Chris Lattner989ba312008-06-18 04:33:20 +00006784 return new StoreInst(II->getOperand(2), Ptr);
6785 }
6786 break;
6787
6788 case Intrinsic::x86_sse_cvttss2si: {
6789 // These intrinsics only demands the 0th element of its input vector. If
6790 // we can simplify the input based on that, do so now.
Evan Cheng63295ab2009-02-03 10:05:09 +00006791 unsigned VWidth =
6792 cast<VectorType>(II->getOperand(1)->getType())->getNumElements();
6793 APInt DemandedElts(VWidth, 1);
6794 APInt UndefElts(VWidth, 0);
6795 if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
Chris Lattner989ba312008-06-18 04:33:20 +00006796 UndefElts)) {
6797 II->setOperand(1, V);
6798 return II;
6799 }
6800 break;
6801 }
6802
6803 case Intrinsic::ppc_altivec_vperm:
6804 // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
6805 if (ConstantVector *Mask = dyn_cast<ConstantVector>(II->getOperand(3))) {
6806 assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006807
Chris Lattner989ba312008-06-18 04:33:20 +00006808 // Check that all of the elements are integer constants or undefs.
6809 bool AllEltsOk = true;
6810 for (unsigned i = 0; i != 16; ++i) {
6811 if (!isa<ConstantInt>(Mask->getOperand(i)) &&
6812 !isa<UndefValue>(Mask->getOperand(i))) {
6813 AllEltsOk = false;
6814 break;
6815 }
6816 }
6817
6818 if (AllEltsOk) {
6819 // Cast the input vectors to byte vectors.
Chris Lattner78628292009-08-30 19:47:22 +00006820 Value *Op0 = Builder->CreateBitCast(II->getOperand(1), Mask->getType());
6821 Value *Op1 = Builder->CreateBitCast(II->getOperand(2), Mask->getType());
Owen Andersonb99ecca2009-07-30 23:03:37 +00006822 Value *Result = UndefValue::get(Op0->getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006823
Chris Lattner989ba312008-06-18 04:33:20 +00006824 // Only extract each element once.
6825 Value *ExtractedElts[32];
6826 memset(ExtractedElts, 0, sizeof(ExtractedElts));
6827
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006828 for (unsigned i = 0; i != 16; ++i) {
Chris Lattner989ba312008-06-18 04:33:20 +00006829 if (isa<UndefValue>(Mask->getOperand(i)))
6830 continue;
6831 unsigned Idx=cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
6832 Idx &= 31; // Match the hardware behavior.
6833
6834 if (ExtractedElts[Idx] == 0) {
Chris Lattnerad7516a2009-08-30 18:50:58 +00006835 ExtractedElts[Idx] =
6836 Builder->CreateExtractElement(Idx < 16 ? Op0 : Op1,
Chris Lattner03a27b42010-01-04 07:02:48 +00006837 ConstantInt::get(Type::getInt32Ty(II->getContext()),
6838 Idx&15, false), "tmp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006839 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006840
Chris Lattner989ba312008-06-18 04:33:20 +00006841 // Insert this value into the result vector.
Chris Lattnerad7516a2009-08-30 18:50:58 +00006842 Result = Builder->CreateInsertElement(Result, ExtractedElts[Idx],
Chris Lattner03a27b42010-01-04 07:02:48 +00006843 ConstantInt::get(Type::getInt32Ty(II->getContext()),
6844 i, false), "tmp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006845 }
Chris Lattner989ba312008-06-18 04:33:20 +00006846 return CastInst::Create(Instruction::BitCast, Result, CI.getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006847 }
Chris Lattner989ba312008-06-18 04:33:20 +00006848 }
6849 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006850
Chris Lattner989ba312008-06-18 04:33:20 +00006851 case Intrinsic::stackrestore: {
6852 // If the save is right next to the restore, remove the restore. This can
6853 // happen when variable allocas are DCE'd.
6854 if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
6855 if (SS->getIntrinsicID() == Intrinsic::stacksave) {
6856 BasicBlock::iterator BI = SS;
6857 if (&*++BI == II)
6858 return EraseInstFromFunction(CI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006859 }
Chris Lattner989ba312008-06-18 04:33:20 +00006860 }
6861
6862 // Scan down this block to see if there is another stack restore in the
6863 // same block without an intervening call/alloca.
6864 BasicBlock::iterator BI = II;
6865 TerminatorInst *TI = II->getParent()->getTerminator();
6866 bool CannotRemove = false;
6867 for (++BI; &*BI != TI; ++BI) {
Victor Hernandez48c3c542009-09-18 22:35:49 +00006868 if (isa<AllocaInst>(BI) || isMalloc(BI)) {
Chris Lattner989ba312008-06-18 04:33:20 +00006869 CannotRemove = true;
6870 break;
6871 }
Chris Lattnera6b477c2008-06-25 05:59:28 +00006872 if (CallInst *BCI = dyn_cast<CallInst>(BI)) {
6873 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(BCI)) {
6874 // If there is a stackrestore below this one, remove this one.
6875 if (II->getIntrinsicID() == Intrinsic::stackrestore)
6876 return EraseInstFromFunction(CI);
6877 // Otherwise, ignore the intrinsic.
6878 } else {
6879 // If we found a non-intrinsic call, we can't remove the stack
6880 // restore.
Chris Lattner416d91c2008-02-18 06:12:38 +00006881 CannotRemove = true;
6882 break;
6883 }
Chris Lattner989ba312008-06-18 04:33:20 +00006884 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006885 }
Chris Lattner989ba312008-06-18 04:33:20 +00006886
6887 // If the stack restore is in a return/unwind block and if there are no
6888 // allocas or calls between the restore and the return, nuke the restore.
6889 if (!CannotRemove && (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)))
6890 return EraseInstFromFunction(CI);
6891 break;
6892 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006893 }
6894
6895 return visitCallSite(II);
6896}
6897
6898// InvokeInst simplification
6899//
6900Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
6901 return visitCallSite(&II);
6902}
6903
Dale Johannesen96021832008-04-25 21:16:07 +00006904/// isSafeToEliminateVarargsCast - If this cast does not affect the value
6905/// passed through the varargs area, we can eliminate the use of the cast.
Dale Johannesen35615462008-04-23 18:34:37 +00006906static bool isSafeToEliminateVarargsCast(const CallSite CS,
6907 const CastInst * const CI,
6908 const TargetData * const TD,
6909 const int ix) {
6910 if (!CI->isLosslessCast())
6911 return false;
6912
6913 // The size of ByVal arguments is derived from the type, so we
6914 // can't change to a type with a different size. If the size were
6915 // passed explicitly we could avoid this check.
Devang Pateld222f862008-09-25 21:00:45 +00006916 if (!CS.paramHasAttr(ix, Attribute::ByVal))
Dale Johannesen35615462008-04-23 18:34:37 +00006917 return true;
6918
6919 const Type* SrcTy =
6920 cast<PointerType>(CI->getOperand(0)->getType())->getElementType();
6921 const Type* DstTy = cast<PointerType>(CI->getType())->getElementType();
6922 if (!SrcTy->isSized() || !DstTy->isSized())
6923 return false;
Dan Gohmana80e2712009-07-21 23:21:54 +00006924 if (!TD || TD->getTypeAllocSize(SrcTy) != TD->getTypeAllocSize(DstTy))
Dale Johannesen35615462008-04-23 18:34:37 +00006925 return false;
6926 return true;
6927}
6928
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006929// visitCallSite - Improvements for call and invoke instructions.
6930//
6931Instruction *InstCombiner::visitCallSite(CallSite CS) {
6932 bool Changed = false;
6933
6934 // If the callee is a constexpr cast of a function, attempt to move the cast
6935 // to the arguments of the call/invoke.
6936 if (transformConstExprCastCall(CS)) return 0;
6937
6938 Value *Callee = CS.getCalledValue();
6939
6940 if (Function *CalleeF = dyn_cast<Function>(Callee))
6941 if (CalleeF->getCallingConv() != CS.getCallingConv()) {
6942 Instruction *OldCall = CS.getInstruction();
6943 // If the call and callee calling conventions don't match, this call must
6944 // be unreachable, as the call is undefined.
Chris Lattner03a27b42010-01-04 07:02:48 +00006945 new StoreInst(ConstantInt::getTrue(Callee->getContext()),
6946 UndefValue::get(Type::getInt1PtrTy(Callee->getContext())),
Owen Anderson24be4c12009-07-03 00:17:18 +00006947 OldCall);
Devang Patele3829c82009-10-13 22:56:32 +00006948 // If OldCall dues not return void then replaceAllUsesWith undef.
6949 // This allows ValueHandlers and custom metadata to adjust itself.
Devang Patele9d08b82009-10-14 17:29:00 +00006950 if (!OldCall->getType()->isVoidTy())
Devang Patele3829c82009-10-13 22:56:32 +00006951 OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006952 if (isa<CallInst>(OldCall)) // Not worth removing an invoke here.
6953 return EraseInstFromFunction(*OldCall);
6954 return 0;
6955 }
6956
6957 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
6958 // This instruction is not reachable, just remove it. We insert a store to
6959 // undef so that we know that this code is not reachable, despite the fact
6960 // that we can't modify the CFG here.
Chris Lattner03a27b42010-01-04 07:02:48 +00006961 new StoreInst(ConstantInt::getTrue(Callee->getContext()),
6962 UndefValue::get(Type::getInt1PtrTy(Callee->getContext())),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006963 CS.getInstruction());
6964
Devang Patele3829c82009-10-13 22:56:32 +00006965 // If CS dues not return void then replaceAllUsesWith undef.
6966 // This allows ValueHandlers and custom metadata to adjust itself.
Devang Patele9d08b82009-10-14 17:29:00 +00006967 if (!CS.getInstruction()->getType()->isVoidTy())
Devang Patele3829c82009-10-13 22:56:32 +00006968 CS.getInstruction()->
6969 replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006970
6971 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
6972 // Don't break the CFG, insert a dummy cond branch.
Gabor Greifd6da1d02008-04-06 20:25:17 +00006973 BranchInst::Create(II->getNormalDest(), II->getUnwindDest(),
Chris Lattner03a27b42010-01-04 07:02:48 +00006974 ConstantInt::getTrue(Callee->getContext()), II);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006975 }
6976 return EraseInstFromFunction(*CS.getInstruction());
6977 }
6978
Duncan Sands74833f22007-09-17 10:26:40 +00006979 if (BitCastInst *BC = dyn_cast<BitCastInst>(Callee))
6980 if (IntrinsicInst *In = dyn_cast<IntrinsicInst>(BC->getOperand(0)))
6981 if (In->getIntrinsicID() == Intrinsic::init_trampoline)
6982 return transformCallThroughTrampoline(CS);
6983
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006984 const PointerType *PTy = cast<PointerType>(Callee->getType());
6985 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
6986 if (FTy->isVarArg()) {
Dale Johannesen502336c2008-04-23 01:03:05 +00006987 int ix = FTy->getNumParams() + (isa<InvokeInst>(Callee) ? 3 : 1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006988 // See if we can optimize any arguments passed through the varargs area of
6989 // the call.
6990 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
Dale Johannesen35615462008-04-23 18:34:37 +00006991 E = CS.arg_end(); I != E; ++I, ++ix) {
6992 CastInst *CI = dyn_cast<CastInst>(*I);
6993 if (CI && isSafeToEliminateVarargsCast(CS, CI, TD, ix)) {
6994 *I = CI->getOperand(0);
6995 Changed = true;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006996 }
Dale Johannesen35615462008-04-23 18:34:37 +00006997 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006998 }
6999
Duncan Sands2937e352007-12-19 21:13:37 +00007000 if (isa<InlineAsm>(Callee) && !CS.doesNotThrow()) {
Duncan Sands7868f3c2007-12-16 15:51:49 +00007001 // Inline asm calls cannot throw - mark them 'nounwind'.
Duncan Sands2937e352007-12-19 21:13:37 +00007002 CS.setDoesNotThrow();
Duncan Sands7868f3c2007-12-16 15:51:49 +00007003 Changed = true;
7004 }
7005
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007006 return Changed ? CS.getInstruction() : 0;
7007}
7008
7009// transformConstExprCastCall - If the callee is a constexpr cast of a function,
7010// attempt to move the cast to the arguments of the call/invoke.
7011//
7012bool InstCombiner::transformConstExprCastCall(CallSite CS) {
7013 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
7014 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
7015 if (CE->getOpcode() != Instruction::BitCast ||
7016 !isa<Function>(CE->getOperand(0)))
7017 return false;
7018 Function *Callee = cast<Function>(CE->getOperand(0));
7019 Instruction *Caller = CS.getInstruction();
Devang Pateld222f862008-09-25 21:00:45 +00007020 const AttrListPtr &CallerPAL = CS.getAttributes();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007021
7022 // Okay, this is a cast from a function to a different type. Unless doing so
7023 // would cause a type conversion of one of our arguments, change this call to
7024 // be a direct call with arguments casted to the appropriate types.
7025 //
7026 const FunctionType *FT = Callee->getFunctionType();
7027 const Type *OldRetTy = Caller->getType();
Duncan Sands7901ce12008-06-01 07:38:42 +00007028 const Type *NewRetTy = FT->getReturnType();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007029
Duncan Sands7901ce12008-06-01 07:38:42 +00007030 if (isa<StructType>(NewRetTy))
Devang Pateld091d322008-03-11 18:04:06 +00007031 return false; // TODO: Handle multiple return values.
7032
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007033 // Check to see if we are changing the return type...
Duncan Sands7901ce12008-06-01 07:38:42 +00007034 if (OldRetTy != NewRetTy) {
Bill Wendlingd9644a42008-05-14 22:45:20 +00007035 if (Callee->isDeclaration() &&
Duncan Sands7901ce12008-06-01 07:38:42 +00007036 // Conversion is ok if changing from one pointer type to another or from
7037 // a pointer to an integer of the same size.
Dan Gohmana80e2712009-07-21 23:21:54 +00007038 !((isa<PointerType>(OldRetTy) || !TD ||
Owen Anderson35b47072009-08-13 21:58:54 +00007039 OldRetTy == TD->getIntPtrType(Caller->getContext())) &&
Dan Gohmana80e2712009-07-21 23:21:54 +00007040 (isa<PointerType>(NewRetTy) || !TD ||
Owen Anderson35b47072009-08-13 21:58:54 +00007041 NewRetTy == TD->getIntPtrType(Caller->getContext()))))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007042 return false; // Cannot transform this return value.
7043
Duncan Sands5c489582008-01-06 10:12:28 +00007044 if (!Caller->use_empty() &&
Duncan Sands5c489582008-01-06 10:12:28 +00007045 // void -> non-void is handled specially
Devang Patele9d08b82009-10-14 17:29:00 +00007046 !NewRetTy->isVoidTy() && !CastInst::isCastable(NewRetTy, OldRetTy))
Duncan Sands5c489582008-01-06 10:12:28 +00007047 return false; // Cannot transform this return value.
7048
Chris Lattner1c8733e2008-03-12 17:45:29 +00007049 if (!CallerPAL.isEmpty() && !Caller->use_empty()) {
Devang Patelf2a4a922008-09-26 22:53:05 +00007050 Attributes RAttrs = CallerPAL.getRetAttributes();
Devang Pateld222f862008-09-25 21:00:45 +00007051 if (RAttrs & Attribute::typeIncompatible(NewRetTy))
Duncan Sandsdbe97dc2008-01-07 17:16:06 +00007052 return false; // Attribute not compatible with transformed value.
7053 }
Duncan Sandsc849e662008-01-06 18:27:01 +00007054
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007055 // If the callsite is an invoke instruction, and the return value is used by
7056 // a PHI node in a successor, we cannot change the return type of the call
7057 // because there is no place to put the cast instruction (without breaking
7058 // the critical edge). Bail out in this case.
7059 if (!Caller->use_empty())
7060 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
7061 for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
7062 UI != E; ++UI)
7063 if (PHINode *PN = dyn_cast<PHINode>(*UI))
7064 if (PN->getParent() == II->getNormalDest() ||
7065 PN->getParent() == II->getUnwindDest())
7066 return false;
7067 }
7068
7069 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
7070 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
7071
7072 CallSite::arg_iterator AI = CS.arg_begin();
7073 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
7074 const Type *ParamTy = FT->getParamType(i);
7075 const Type *ActTy = (*AI)->getType();
Duncan Sands5c489582008-01-06 10:12:28 +00007076
7077 if (!CastInst::isCastable(ActTy, ParamTy))
Duncan Sandsc849e662008-01-06 18:27:01 +00007078 return false; // Cannot transform this parameter value.
7079
Devang Patelf2a4a922008-09-26 22:53:05 +00007080 if (CallerPAL.getParamAttributes(i + 1)
7081 & Attribute::typeIncompatible(ParamTy))
Chris Lattner1c8733e2008-03-12 17:45:29 +00007082 return false; // Attribute not compatible with transformed value.
Duncan Sands5c489582008-01-06 10:12:28 +00007083
Duncan Sands7901ce12008-06-01 07:38:42 +00007084 // Converting from one pointer type to another or between a pointer and an
7085 // integer of the same size is safe even if we do not have a body.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007086 bool isConvertible = ActTy == ParamTy ||
Owen Anderson35b47072009-08-13 21:58:54 +00007087 (TD && ((isa<PointerType>(ParamTy) ||
7088 ParamTy == TD->getIntPtrType(Caller->getContext())) &&
7089 (isa<PointerType>(ActTy) ||
7090 ActTy == TD->getIntPtrType(Caller->getContext()))));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007091 if (Callee->isDeclaration() && !isConvertible) return false;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007092 }
7093
7094 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
7095 Callee->isDeclaration())
Chris Lattner1c8733e2008-03-12 17:45:29 +00007096 return false; // Do not delete arguments unless we have a function body.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007097
Chris Lattner1c8733e2008-03-12 17:45:29 +00007098 if (FT->getNumParams() < NumActualArgs && FT->isVarArg() &&
7099 !CallerPAL.isEmpty())
Duncan Sandsc849e662008-01-06 18:27:01 +00007100 // In this case we have more arguments than the new function type, but we
Duncan Sands4ced1f82008-01-13 08:02:44 +00007101 // won't be dropping them. Check that these extra arguments have attributes
7102 // that are compatible with being a vararg call argument.
Chris Lattner1c8733e2008-03-12 17:45:29 +00007103 for (unsigned i = CallerPAL.getNumSlots(); i; --i) {
7104 if (CallerPAL.getSlot(i - 1).Index <= FT->getNumParams())
Duncan Sands4ced1f82008-01-13 08:02:44 +00007105 break;
Devang Patele480dfa2008-09-23 23:03:40 +00007106 Attributes PAttrs = CallerPAL.getSlot(i - 1).Attrs;
Devang Pateld222f862008-09-25 21:00:45 +00007107 if (PAttrs & Attribute::VarArgsIncompatible)
Duncan Sands4ced1f82008-01-13 08:02:44 +00007108 return false;
7109 }
Duncan Sandsc849e662008-01-06 18:27:01 +00007110
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007111 // Okay, we decided that this is a safe thing to do: go ahead and start
7112 // inserting cast instructions as necessary...
7113 std::vector<Value*> Args;
7114 Args.reserve(NumActualArgs);
Devang Pateld222f862008-09-25 21:00:45 +00007115 SmallVector<AttributeWithIndex, 8> attrVec;
Duncan Sandsc849e662008-01-06 18:27:01 +00007116 attrVec.reserve(NumCommonArgs);
7117
7118 // Get any return attributes.
Devang Patelf2a4a922008-09-26 22:53:05 +00007119 Attributes RAttrs = CallerPAL.getRetAttributes();
Duncan Sandsc849e662008-01-06 18:27:01 +00007120
7121 // If the return value is not being used, the type may not be compatible
7122 // with the existing attributes. Wipe out any problematic attributes.
Devang Pateld222f862008-09-25 21:00:45 +00007123 RAttrs &= ~Attribute::typeIncompatible(NewRetTy);
Duncan Sandsc849e662008-01-06 18:27:01 +00007124
7125 // Add the new return attributes.
7126 if (RAttrs)
Devang Pateld222f862008-09-25 21:00:45 +00007127 attrVec.push_back(AttributeWithIndex::get(0, RAttrs));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007128
7129 AI = CS.arg_begin();
7130 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
7131 const Type *ParamTy = FT->getParamType(i);
7132 if ((*AI)->getType() == ParamTy) {
7133 Args.push_back(*AI);
7134 } else {
7135 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
7136 false, ParamTy, false);
Chris Lattnerad7516a2009-08-30 18:50:58 +00007137 Args.push_back(Builder->CreateCast(opcode, *AI, ParamTy, "tmp"));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007138 }
Duncan Sandsc849e662008-01-06 18:27:01 +00007139
7140 // Add any parameter attributes.
Devang Patelf2a4a922008-09-26 22:53:05 +00007141 if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
Devang Pateld222f862008-09-25 21:00:45 +00007142 attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007143 }
7144
7145 // If the function takes more arguments than the call was taking, add them
Chris Lattnerad7516a2009-08-30 18:50:58 +00007146 // now.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007147 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
Owen Andersonaac28372009-07-31 20:28:14 +00007148 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007149
Chris Lattnerad7516a2009-08-30 18:50:58 +00007150 // If we are removing arguments to the function, emit an obnoxious warning.
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00007151 if (FT->getNumParams() < NumActualArgs) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007152 if (!FT->isVarArg()) {
Daniel Dunbar005975c2009-07-25 00:23:56 +00007153 errs() << "WARNING: While resolving call to function '"
7154 << Callee->getName() << "' arguments were dropped!\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007155 } else {
Chris Lattnerad7516a2009-08-30 18:50:58 +00007156 // Add all of the arguments in their promoted form to the arg list.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007157 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
7158 const Type *PTy = getPromotedType((*AI)->getType());
7159 if (PTy != (*AI)->getType()) {
7160 // Must promote to pass through va_arg area!
Chris Lattnerad7516a2009-08-30 18:50:58 +00007161 Instruction::CastOps opcode =
7162 CastInst::getCastOpcode(*AI, false, PTy, false);
7163 Args.push_back(Builder->CreateCast(opcode, *AI, PTy, "tmp"));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007164 } else {
7165 Args.push_back(*AI);
7166 }
Duncan Sandsc849e662008-01-06 18:27:01 +00007167
Duncan Sands4ced1f82008-01-13 08:02:44 +00007168 // Add any parameter attributes.
Devang Patelf2a4a922008-09-26 22:53:05 +00007169 if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
Devang Pateld222f862008-09-25 21:00:45 +00007170 attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
Duncan Sands4ced1f82008-01-13 08:02:44 +00007171 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007172 }
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00007173 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007174
Devang Patelf2a4a922008-09-26 22:53:05 +00007175 if (Attributes FnAttrs = CallerPAL.getFnAttributes())
7176 attrVec.push_back(AttributeWithIndex::get(~0, FnAttrs));
7177
Devang Patele9d08b82009-10-14 17:29:00 +00007178 if (NewRetTy->isVoidTy())
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007179 Caller->setName(""); // Void type should not have a name.
7180
Eric Christopher3e7381f2009-07-25 02:45:27 +00007181 const AttrListPtr &NewCallerPAL = AttrListPtr::get(attrVec.begin(),
7182 attrVec.end());
Duncan Sandsc849e662008-01-06 18:27:01 +00007183
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007184 Instruction *NC;
7185 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Gabor Greifd6da1d02008-04-06 20:25:17 +00007186 NC = InvokeInst::Create(Callee, II->getNormalDest(), II->getUnwindDest(),
Gabor Greifb91ea9d2008-05-15 10:04:30 +00007187 Args.begin(), Args.end(),
7188 Caller->getName(), Caller);
Reid Spencer6b0b09a2007-07-30 19:53:57 +00007189 cast<InvokeInst>(NC)->setCallingConv(II->getCallingConv());
Devang Pateld222f862008-09-25 21:00:45 +00007190 cast<InvokeInst>(NC)->setAttributes(NewCallerPAL);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007191 } else {
Gabor Greifd6da1d02008-04-06 20:25:17 +00007192 NC = CallInst::Create(Callee, Args.begin(), Args.end(),
7193 Caller->getName(), Caller);
Duncan Sandsf5588dc2007-11-27 13:23:08 +00007194 CallInst *CI = cast<CallInst>(Caller);
7195 if (CI->isTailCall())
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007196 cast<CallInst>(NC)->setTailCall();
Duncan Sandsf5588dc2007-11-27 13:23:08 +00007197 cast<CallInst>(NC)->setCallingConv(CI->getCallingConv());
Devang Pateld222f862008-09-25 21:00:45 +00007198 cast<CallInst>(NC)->setAttributes(NewCallerPAL);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007199 }
7200
7201 // Insert a cast of the return type as necessary.
7202 Value *NV = NC;
Duncan Sands5c489582008-01-06 10:12:28 +00007203 if (OldRetTy != NV->getType() && !Caller->use_empty()) {
Devang Patele9d08b82009-10-14 17:29:00 +00007204 if (!NV->getType()->isVoidTy()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007205 Instruction::CastOps opcode = CastInst::getCastOpcode(NC, false,
Duncan Sands5c489582008-01-06 10:12:28 +00007206 OldRetTy, false);
Gabor Greifa645dd32008-05-16 19:29:10 +00007207 NV = NC = CastInst::Create(opcode, NC, OldRetTy, "tmp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007208
7209 // If this is an invoke instruction, we should insert it after the first
7210 // non-phi, instruction in the normal successor block.
7211 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Dan Gohman514277c2008-05-23 21:05:58 +00007212 BasicBlock::iterator I = II->getNormalDest()->getFirstNonPHI();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007213 InsertNewInstBefore(NC, *I);
7214 } else {
7215 // Otherwise, it's a call, just insert cast right after the call instr
7216 InsertNewInstBefore(NC, *Caller);
7217 }
Chris Lattner4796b622009-08-30 06:22:51 +00007218 Worklist.AddUsersToWorkList(*Caller);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007219 } else {
Owen Andersonb99ecca2009-07-30 23:03:37 +00007220 NV = UndefValue::get(Caller->getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007221 }
7222 }
7223
Devang Pateledad36f2009-10-13 21:41:20 +00007224
Chris Lattner26b7f942009-08-31 05:17:58 +00007225 if (!Caller->use_empty())
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007226 Caller->replaceAllUsesWith(NV);
Chris Lattner26b7f942009-08-31 05:17:58 +00007227
7228 EraseInstFromFunction(*Caller);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007229 return true;
7230}
7231
Duncan Sands74833f22007-09-17 10:26:40 +00007232// transformCallThroughTrampoline - Turn a call to a function created by the
7233// init_trampoline intrinsic into a direct call to the underlying function.
7234//
7235Instruction *InstCombiner::transformCallThroughTrampoline(CallSite CS) {
7236 Value *Callee = CS.getCalledValue();
7237 const PointerType *PTy = cast<PointerType>(Callee->getType());
7238 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
Devang Pateld222f862008-09-25 21:00:45 +00007239 const AttrListPtr &Attrs = CS.getAttributes();
Duncan Sands48b81112008-01-14 19:52:09 +00007240
7241 // If the call already has the 'nest' attribute somewhere then give up -
7242 // otherwise 'nest' would occur twice after splicing in the chain.
Devang Pateld222f862008-09-25 21:00:45 +00007243 if (Attrs.hasAttrSomewhere(Attribute::Nest))
Duncan Sands48b81112008-01-14 19:52:09 +00007244 return 0;
Duncan Sands74833f22007-09-17 10:26:40 +00007245
7246 IntrinsicInst *Tramp =
7247 cast<IntrinsicInst>(cast<BitCastInst>(Callee)->getOperand(0));
7248
Anton Korobeynikov48fc88f2008-05-07 22:54:15 +00007249 Function *NestF = cast<Function>(Tramp->getOperand(2)->stripPointerCasts());
Duncan Sands74833f22007-09-17 10:26:40 +00007250 const PointerType *NestFPTy = cast<PointerType>(NestF->getType());
7251 const FunctionType *NestFTy = cast<FunctionType>(NestFPTy->getElementType());
7252
Devang Pateld222f862008-09-25 21:00:45 +00007253 const AttrListPtr &NestAttrs = NestF->getAttributes();
Chris Lattner1c8733e2008-03-12 17:45:29 +00007254 if (!NestAttrs.isEmpty()) {
Duncan Sands74833f22007-09-17 10:26:40 +00007255 unsigned NestIdx = 1;
7256 const Type *NestTy = 0;
Devang Pateld222f862008-09-25 21:00:45 +00007257 Attributes NestAttr = Attribute::None;
Duncan Sands74833f22007-09-17 10:26:40 +00007258
7259 // Look for a parameter marked with the 'nest' attribute.
7260 for (FunctionType::param_iterator I = NestFTy->param_begin(),
7261 E = NestFTy->param_end(); I != E; ++NestIdx, ++I)
Devang Pateld222f862008-09-25 21:00:45 +00007262 if (NestAttrs.paramHasAttr(NestIdx, Attribute::Nest)) {
Duncan Sands74833f22007-09-17 10:26:40 +00007263 // Record the parameter type and any other attributes.
7264 NestTy = *I;
Devang Patelf2a4a922008-09-26 22:53:05 +00007265 NestAttr = NestAttrs.getParamAttributes(NestIdx);
Duncan Sands74833f22007-09-17 10:26:40 +00007266 break;
7267 }
7268
7269 if (NestTy) {
7270 Instruction *Caller = CS.getInstruction();
7271 std::vector<Value*> NewArgs;
7272 NewArgs.reserve(unsigned(CS.arg_end()-CS.arg_begin())+1);
7273
Devang Pateld222f862008-09-25 21:00:45 +00007274 SmallVector<AttributeWithIndex, 8> NewAttrs;
Chris Lattner1c8733e2008-03-12 17:45:29 +00007275 NewAttrs.reserve(Attrs.getNumSlots() + 1);
Duncan Sands48b81112008-01-14 19:52:09 +00007276
Duncan Sands74833f22007-09-17 10:26:40 +00007277 // Insert the nest argument into the call argument list, which may
Duncan Sands48b81112008-01-14 19:52:09 +00007278 // mean appending it. Likewise for attributes.
7279
Devang Patelf2a4a922008-09-26 22:53:05 +00007280 // Add any result attributes.
7281 if (Attributes Attr = Attrs.getRetAttributes())
Devang Pateld222f862008-09-25 21:00:45 +00007282 NewAttrs.push_back(AttributeWithIndex::get(0, Attr));
Duncan Sands48b81112008-01-14 19:52:09 +00007283
Duncan Sands74833f22007-09-17 10:26:40 +00007284 {
7285 unsigned Idx = 1;
7286 CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
7287 do {
7288 if (Idx == NestIdx) {
Duncan Sands48b81112008-01-14 19:52:09 +00007289 // Add the chain argument and attributes.
Duncan Sands74833f22007-09-17 10:26:40 +00007290 Value *NestVal = Tramp->getOperand(3);
7291 if (NestVal->getType() != NestTy)
7292 NestVal = new BitCastInst(NestVal, NestTy, "nest", Caller);
7293 NewArgs.push_back(NestVal);
Devang Pateld222f862008-09-25 21:00:45 +00007294 NewAttrs.push_back(AttributeWithIndex::get(NestIdx, NestAttr));
Duncan Sands74833f22007-09-17 10:26:40 +00007295 }
7296
7297 if (I == E)
7298 break;
7299
Duncan Sands48b81112008-01-14 19:52:09 +00007300 // Add the original argument and attributes.
Duncan Sands74833f22007-09-17 10:26:40 +00007301 NewArgs.push_back(*I);
Devang Patelf2a4a922008-09-26 22:53:05 +00007302 if (Attributes Attr = Attrs.getParamAttributes(Idx))
Duncan Sands48b81112008-01-14 19:52:09 +00007303 NewAttrs.push_back
Devang Pateld222f862008-09-25 21:00:45 +00007304 (AttributeWithIndex::get(Idx + (Idx >= NestIdx), Attr));
Duncan Sands74833f22007-09-17 10:26:40 +00007305
7306 ++Idx, ++I;
7307 } while (1);
7308 }
7309
Devang Patelf2a4a922008-09-26 22:53:05 +00007310 // Add any function attributes.
7311 if (Attributes Attr = Attrs.getFnAttributes())
7312 NewAttrs.push_back(AttributeWithIndex::get(~0, Attr));
7313
Duncan Sands74833f22007-09-17 10:26:40 +00007314 // The trampoline may have been bitcast to a bogus type (FTy).
7315 // Handle this by synthesizing a new function type, equal to FTy
Duncan Sands48b81112008-01-14 19:52:09 +00007316 // with the chain parameter inserted.
Duncan Sands74833f22007-09-17 10:26:40 +00007317
Duncan Sands74833f22007-09-17 10:26:40 +00007318 std::vector<const Type*> NewTypes;
Duncan Sands74833f22007-09-17 10:26:40 +00007319 NewTypes.reserve(FTy->getNumParams()+1);
7320
Duncan Sands74833f22007-09-17 10:26:40 +00007321 // Insert the chain's type into the list of parameter types, which may
Duncan Sands48b81112008-01-14 19:52:09 +00007322 // mean appending it.
Duncan Sands74833f22007-09-17 10:26:40 +00007323 {
7324 unsigned Idx = 1;
7325 FunctionType::param_iterator I = FTy->param_begin(),
7326 E = FTy->param_end();
7327
7328 do {
Duncan Sands48b81112008-01-14 19:52:09 +00007329 if (Idx == NestIdx)
7330 // Add the chain's type.
Duncan Sands74833f22007-09-17 10:26:40 +00007331 NewTypes.push_back(NestTy);
Duncan Sands74833f22007-09-17 10:26:40 +00007332
7333 if (I == E)
7334 break;
7335
Duncan Sands48b81112008-01-14 19:52:09 +00007336 // Add the original type.
Duncan Sands74833f22007-09-17 10:26:40 +00007337 NewTypes.push_back(*I);
Duncan Sands74833f22007-09-17 10:26:40 +00007338
7339 ++Idx, ++I;
7340 } while (1);
7341 }
7342
7343 // Replace the trampoline call with a direct call. Let the generic
7344 // code sort out any function type mismatches.
Owen Anderson6b6e2d92009-07-29 22:17:13 +00007345 FunctionType *NewFTy = FunctionType::get(FTy->getReturnType(), NewTypes,
Owen Anderson24be4c12009-07-03 00:17:18 +00007346 FTy->isVarArg());
7347 Constant *NewCallee =
Owen Anderson6b6e2d92009-07-29 22:17:13 +00007348 NestF->getType() == PointerType::getUnqual(NewFTy) ?
Owen Anderson02b48c32009-07-29 18:55:55 +00007349 NestF : ConstantExpr::getBitCast(NestF,
Owen Anderson6b6e2d92009-07-29 22:17:13 +00007350 PointerType::getUnqual(NewFTy));
Eric Christopher3e7381f2009-07-25 02:45:27 +00007351 const AttrListPtr &NewPAL = AttrListPtr::get(NewAttrs.begin(),
7352 NewAttrs.end());
Duncan Sands74833f22007-09-17 10:26:40 +00007353
7354 Instruction *NewCaller;
7355 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Gabor Greifd6da1d02008-04-06 20:25:17 +00007356 NewCaller = InvokeInst::Create(NewCallee,
7357 II->getNormalDest(), II->getUnwindDest(),
7358 NewArgs.begin(), NewArgs.end(),
7359 Caller->getName(), Caller);
Duncan Sands74833f22007-09-17 10:26:40 +00007360 cast<InvokeInst>(NewCaller)->setCallingConv(II->getCallingConv());
Devang Pateld222f862008-09-25 21:00:45 +00007361 cast<InvokeInst>(NewCaller)->setAttributes(NewPAL);
Duncan Sands74833f22007-09-17 10:26:40 +00007362 } else {
Gabor Greifd6da1d02008-04-06 20:25:17 +00007363 NewCaller = CallInst::Create(NewCallee, NewArgs.begin(), NewArgs.end(),
7364 Caller->getName(), Caller);
Duncan Sands74833f22007-09-17 10:26:40 +00007365 if (cast<CallInst>(Caller)->isTailCall())
7366 cast<CallInst>(NewCaller)->setTailCall();
7367 cast<CallInst>(NewCaller)->
7368 setCallingConv(cast<CallInst>(Caller)->getCallingConv());
Devang Pateld222f862008-09-25 21:00:45 +00007369 cast<CallInst>(NewCaller)->setAttributes(NewPAL);
Duncan Sands74833f22007-09-17 10:26:40 +00007370 }
Devang Patele9d08b82009-10-14 17:29:00 +00007371 if (!Caller->getType()->isVoidTy())
Duncan Sands74833f22007-09-17 10:26:40 +00007372 Caller->replaceAllUsesWith(NewCaller);
7373 Caller->eraseFromParent();
Chris Lattner3183fb62009-08-30 06:13:40 +00007374 Worklist.Remove(Caller);
Duncan Sands74833f22007-09-17 10:26:40 +00007375 return 0;
7376 }
7377 }
7378
7379 // Replace the trampoline call with a direct call. Since there is no 'nest'
7380 // parameter, there is no need to adjust the argument list. Let the generic
7381 // code sort out any function type mismatches.
7382 Constant *NewCallee =
Owen Anderson24be4c12009-07-03 00:17:18 +00007383 NestF->getType() == PTy ? NestF :
Owen Anderson02b48c32009-07-29 18:55:55 +00007384 ConstantExpr::getBitCast(NestF, PTy);
Duncan Sands74833f22007-09-17 10:26:40 +00007385 CS.setCalledFunction(NewCallee);
7386 return CS.getInstruction();
7387}
7388
Dan Gohman09cf2b62009-09-16 16:50:24 +00007389/// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(a,c)]
7390/// and if a/b/c and the add's all have a single use, turn this into a phi
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007391/// and a single binop.
7392Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
7393 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
Chris Lattner30078012008-12-01 03:42:51 +00007394 assert(isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007395 unsigned Opc = FirstInst->getOpcode();
7396 Value *LHSVal = FirstInst->getOperand(0);
7397 Value *RHSVal = FirstInst->getOperand(1);
7398
7399 const Type *LHSType = LHSVal->getType();
7400 const Type *RHSType = RHSVal->getType();
7401
Dan Gohman09cf2b62009-09-16 16:50:24 +00007402 // Scan to see if all operands are the same opcode, and all have one use.
Chris Lattner9e1916e2008-12-01 02:34:36 +00007403 for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007404 Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
7405 if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
7406 // Verify type of the LHS matches so we don't fold cmp's of different
7407 // types or GEP's with different index types.
7408 I->getOperand(0)->getType() != LHSType ||
7409 I->getOperand(1)->getType() != RHSType)
7410 return 0;
7411
7412 // If they are CmpInst instructions, check their predicates
7413 if (Opc == Instruction::ICmp || Opc == Instruction::FCmp)
7414 if (cast<CmpInst>(I)->getPredicate() !=
7415 cast<CmpInst>(FirstInst)->getPredicate())
7416 return 0;
7417
7418 // Keep track of which operand needs a phi node.
7419 if (I->getOperand(0) != LHSVal) LHSVal = 0;
7420 if (I->getOperand(1) != RHSVal) RHSVal = 0;
7421 }
Dan Gohman09cf2b62009-09-16 16:50:24 +00007422
7423 // If both LHS and RHS would need a PHI, don't do this transformation,
7424 // because it would increase the number of PHIs entering the block,
7425 // which leads to higher register pressure. This is especially
7426 // bad when the PHIs are in the header of a loop.
7427 if (!LHSVal && !RHSVal)
7428 return 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007429
Chris Lattner30078012008-12-01 03:42:51 +00007430 // Otherwise, this is safe to transform!
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007431
7432 Value *InLHS = FirstInst->getOperand(0);
7433 Value *InRHS = FirstInst->getOperand(1);
7434 PHINode *NewLHS = 0, *NewRHS = 0;
7435 if (LHSVal == 0) {
Gabor Greifb91ea9d2008-05-15 10:04:30 +00007436 NewLHS = PHINode::Create(LHSType,
7437 FirstInst->getOperand(0)->getName() + ".pn");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007438 NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
7439 NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
7440 InsertNewInstBefore(NewLHS, PN);
7441 LHSVal = NewLHS;
7442 }
7443
7444 if (RHSVal == 0) {
Gabor Greifb91ea9d2008-05-15 10:04:30 +00007445 NewRHS = PHINode::Create(RHSType,
7446 FirstInst->getOperand(1)->getName() + ".pn");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007447 NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
7448 NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
7449 InsertNewInstBefore(NewRHS, PN);
7450 RHSVal = NewRHS;
7451 }
7452
7453 // Add all operands to the new PHIs.
Chris Lattner9e1916e2008-12-01 02:34:36 +00007454 if (NewLHS || NewRHS) {
7455 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
7456 Instruction *InInst = cast<Instruction>(PN.getIncomingValue(i));
7457 if (NewLHS) {
7458 Value *NewInLHS = InInst->getOperand(0);
7459 NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
7460 }
7461 if (NewRHS) {
7462 Value *NewInRHS = InInst->getOperand(1);
7463 NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
7464 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007465 }
7466 }
7467
7468 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Gabor Greifa645dd32008-05-16 19:29:10 +00007469 return BinaryOperator::Create(BinOp->getOpcode(), LHSVal, RHSVal);
Chris Lattner30078012008-12-01 03:42:51 +00007470 CmpInst *CIOp = cast<CmpInst>(FirstInst);
Dan Gohmane6803b82009-08-25 23:17:54 +00007471 return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(),
Owen Anderson6601fcd2009-07-09 23:48:35 +00007472 LHSVal, RHSVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007473}
7474
Chris Lattner9e1916e2008-12-01 02:34:36 +00007475Instruction *InstCombiner::FoldPHIArgGEPIntoPHI(PHINode &PN) {
7476 GetElementPtrInst *FirstInst =cast<GetElementPtrInst>(PN.getIncomingValue(0));
7477
7478 SmallVector<Value*, 16> FixedOperands(FirstInst->op_begin(),
7479 FirstInst->op_end());
Chris Lattneradf354b2009-02-21 00:46:50 +00007480 // This is true if all GEP bases are allocas and if all indices into them are
7481 // constants.
7482 bool AllBasePointersAreAllocas = true;
Dan Gohman37a534b2009-09-16 02:01:52 +00007483
7484 // We don't want to replace this phi if the replacement would require
Dan Gohman09cf2b62009-09-16 16:50:24 +00007485 // more than one phi, which leads to higher register pressure. This is
7486 // especially bad when the PHIs are in the header of a loop.
Dan Gohman37a534b2009-09-16 02:01:52 +00007487 bool NeededPhi = false;
Chris Lattner9e1916e2008-12-01 02:34:36 +00007488
Dan Gohman09cf2b62009-09-16 16:50:24 +00007489 // Scan to see if all operands are the same opcode, and all have one use.
Chris Lattner9e1916e2008-12-01 02:34:36 +00007490 for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
7491 GetElementPtrInst *GEP= dyn_cast<GetElementPtrInst>(PN.getIncomingValue(i));
7492 if (!GEP || !GEP->hasOneUse() || GEP->getType() != FirstInst->getType() ||
7493 GEP->getNumOperands() != FirstInst->getNumOperands())
7494 return 0;
7495
Chris Lattneradf354b2009-02-21 00:46:50 +00007496 // Keep track of whether or not all GEPs are of alloca pointers.
7497 if (AllBasePointersAreAllocas &&
7498 (!isa<AllocaInst>(GEP->getOperand(0)) ||
7499 !GEP->hasAllConstantIndices()))
7500 AllBasePointersAreAllocas = false;
7501
Chris Lattner9e1916e2008-12-01 02:34:36 +00007502 // Compare the operand lists.
7503 for (unsigned op = 0, e = FirstInst->getNumOperands(); op != e; ++op) {
7504 if (FirstInst->getOperand(op) == GEP->getOperand(op))
7505 continue;
7506
7507 // Don't merge two GEPs when two operands differ (introducing phi nodes)
7508 // if one of the PHIs has a constant for the index. The index may be
7509 // substantially cheaper to compute for the constants, so making it a
7510 // variable index could pessimize the path. This also handles the case
7511 // for struct indices, which must always be constant.
7512 if (isa<ConstantInt>(FirstInst->getOperand(op)) ||
7513 isa<ConstantInt>(GEP->getOperand(op)))
7514 return 0;
7515
7516 if (FirstInst->getOperand(op)->getType() !=GEP->getOperand(op)->getType())
7517 return 0;
Dan Gohman37a534b2009-09-16 02:01:52 +00007518
7519 // If we already needed a PHI for an earlier operand, and another operand
7520 // also requires a PHI, we'd be introducing more PHIs than we're
7521 // eliminating, which increases register pressure on entry to the PHI's
7522 // block.
7523 if (NeededPhi)
7524 return 0;
7525
Chris Lattner9e1916e2008-12-01 02:34:36 +00007526 FixedOperands[op] = 0; // Needs a PHI.
Dan Gohman37a534b2009-09-16 02:01:52 +00007527 NeededPhi = true;
Chris Lattner9e1916e2008-12-01 02:34:36 +00007528 }
7529 }
7530
Chris Lattneradf354b2009-02-21 00:46:50 +00007531 // If all of the base pointers of the PHI'd GEPs are from allocas, don't
Chris Lattnerf1e30c82009-02-23 05:56:17 +00007532 // bother doing this transformation. At best, this will just save a bit of
Chris Lattneradf354b2009-02-21 00:46:50 +00007533 // offset calculation, but all the predecessors will have to materialize the
7534 // stack address into a register anyway. We'd actually rather *clone* the
7535 // load up into the predecessors so that we have a load of a gep of an alloca,
7536 // which can usually all be folded into the load.
7537 if (AllBasePointersAreAllocas)
7538 return 0;
7539
Chris Lattner9e1916e2008-12-01 02:34:36 +00007540 // Otherwise, this is safe to transform. Insert PHI nodes for each operand
7541 // that is variable.
7542 SmallVector<PHINode*, 16> OperandPhis(FixedOperands.size());
7543
7544 bool HasAnyPHIs = false;
7545 for (unsigned i = 0, e = FixedOperands.size(); i != e; ++i) {
7546 if (FixedOperands[i]) continue; // operand doesn't need a phi.
7547 Value *FirstOp = FirstInst->getOperand(i);
7548 PHINode *NewPN = PHINode::Create(FirstOp->getType(),
7549 FirstOp->getName()+".pn");
7550 InsertNewInstBefore(NewPN, PN);
7551
7552 NewPN->reserveOperandSpace(e);
7553 NewPN->addIncoming(FirstOp, PN.getIncomingBlock(0));
7554 OperandPhis[i] = NewPN;
7555 FixedOperands[i] = NewPN;
7556 HasAnyPHIs = true;
7557 }
7558
7559
7560 // Add all operands to the new PHIs.
7561 if (HasAnyPHIs) {
7562 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
7563 GetElementPtrInst *InGEP =cast<GetElementPtrInst>(PN.getIncomingValue(i));
7564 BasicBlock *InBB = PN.getIncomingBlock(i);
7565
7566 for (unsigned op = 0, e = OperandPhis.size(); op != e; ++op)
7567 if (PHINode *OpPhi = OperandPhis[op])
7568 OpPhi->addIncoming(InGEP->getOperand(op), InBB);
7569 }
7570 }
7571
7572 Value *Base = FixedOperands[0];
Dan Gohmanf3a08b82009-09-07 23:54:19 +00007573 return cast<GEPOperator>(FirstInst)->isInBounds() ?
7574 GetElementPtrInst::CreateInBounds(Base, FixedOperands.begin()+1,
7575 FixedOperands.end()) :
Dan Gohman17f46f72009-07-28 01:40:03 +00007576 GetElementPtrInst::Create(Base, FixedOperands.begin()+1,
7577 FixedOperands.end());
Chris Lattner9e1916e2008-12-01 02:34:36 +00007578}
7579
7580
Chris Lattnerf1e30c82009-02-23 05:56:17 +00007581/// isSafeAndProfitableToSinkLoad - Return true if we know that it is safe to
7582/// sink the load out of the block that defines it. This means that it must be
Chris Lattneradf354b2009-02-21 00:46:50 +00007583/// obvious the value of the load is not changed from the point of the load to
7584/// the end of the block it is in.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007585///
7586/// Finally, it is safe, but not profitable, to sink a load targetting a
7587/// non-address-taken alloca. Doing so will cause us to not promote the alloca
7588/// to a register.
Chris Lattneradf354b2009-02-21 00:46:50 +00007589static bool isSafeAndProfitableToSinkLoad(LoadInst *L) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007590 BasicBlock::iterator BBI = L, E = L->getParent()->end();
7591
7592 for (++BBI; BBI != E; ++BBI)
7593 if (BBI->mayWriteToMemory())
7594 return false;
7595
7596 // Check for non-address taken alloca. If not address-taken already, it isn't
7597 // profitable to do this xform.
7598 if (AllocaInst *AI = dyn_cast<AllocaInst>(L->getOperand(0))) {
7599 bool isAddressTaken = false;
7600 for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
7601 UI != E; ++UI) {
7602 if (isa<LoadInst>(UI)) continue;
7603 if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
7604 // If storing TO the alloca, then the address isn't taken.
7605 if (SI->getOperand(1) == AI) continue;
7606 }
7607 isAddressTaken = true;
7608 break;
7609 }
7610
Chris Lattneradf354b2009-02-21 00:46:50 +00007611 if (!isAddressTaken && AI->isStaticAlloca())
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007612 return false;
7613 }
7614
Chris Lattneradf354b2009-02-21 00:46:50 +00007615 // If this load is a load from a GEP with a constant offset from an alloca,
7616 // then we don't want to sink it. In its present form, it will be
7617 // load [constant stack offset]. Sinking it will cause us to have to
7618 // materialize the stack addresses in each predecessor in a register only to
7619 // do a shared load from register in the successor.
7620 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(L->getOperand(0)))
7621 if (AllocaInst *AI = dyn_cast<AllocaInst>(GEP->getOperand(0)))
7622 if (AI->isStaticAlloca() && GEP->hasAllConstantIndices())
7623 return false;
7624
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007625 return true;
7626}
7627
Chris Lattner38751f82009-11-01 20:04:24 +00007628Instruction *InstCombiner::FoldPHIArgLoadIntoPHI(PHINode &PN) {
7629 LoadInst *FirstLI = cast<LoadInst>(PN.getIncomingValue(0));
7630
7631 // When processing loads, we need to propagate two bits of information to the
7632 // sunk load: whether it is volatile, and what its alignment is. We currently
7633 // don't sink loads when some have their alignment specified and some don't.
7634 // visitLoadInst will propagate an alignment onto the load when TD is around,
7635 // and if TD isn't around, we can't handle the mixed case.
7636 bool isVolatile = FirstLI->isVolatile();
7637 unsigned LoadAlignment = FirstLI->getAlignment();
7638
7639 // We can't sink the load if the loaded value could be modified between the
7640 // load and the PHI.
7641 if (FirstLI->getParent() != PN.getIncomingBlock(0) ||
7642 !isSafeAndProfitableToSinkLoad(FirstLI))
7643 return 0;
7644
7645 // If the PHI is of volatile loads and the load block has multiple
7646 // successors, sinking it would remove a load of the volatile value from
7647 // the path through the other successor.
7648 if (isVolatile &&
7649 FirstLI->getParent()->getTerminator()->getNumSuccessors() != 1)
7650 return 0;
7651
7652 // Check to see if all arguments are the same operation.
7653 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
7654 LoadInst *LI = dyn_cast<LoadInst>(PN.getIncomingValue(i));
7655 if (!LI || !LI->hasOneUse())
7656 return 0;
7657
7658 // We can't sink the load if the loaded value could be modified between
7659 // the load and the PHI.
7660 if (LI->isVolatile() != isVolatile ||
7661 LI->getParent() != PN.getIncomingBlock(i) ||
7662 !isSafeAndProfitableToSinkLoad(LI))
7663 return 0;
7664
7665 // If some of the loads have an alignment specified but not all of them,
7666 // we can't do the transformation.
7667 if ((LoadAlignment != 0) != (LI->getAlignment() != 0))
7668 return 0;
7669
Chris Lattner52fe1bc2009-11-01 20:07:07 +00007670 LoadAlignment = std::min(LoadAlignment, LI->getAlignment());
Chris Lattner38751f82009-11-01 20:04:24 +00007671
7672 // If the PHI is of volatile loads and the load block has multiple
7673 // successors, sinking it would remove a load of the volatile value from
7674 // the path through the other successor.
7675 if (isVolatile &&
7676 LI->getParent()->getTerminator()->getNumSuccessors() != 1)
7677 return 0;
7678 }
7679
7680 // Okay, they are all the same operation. Create a new PHI node of the
7681 // correct type, and PHI together all of the LHS's of the instructions.
7682 PHINode *NewPN = PHINode::Create(FirstLI->getOperand(0)->getType(),
7683 PN.getName()+".in");
7684 NewPN->reserveOperandSpace(PN.getNumOperands()/2);
7685
7686 Value *InVal = FirstLI->getOperand(0);
7687 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
7688
7689 // Add all operands to the new PHI.
7690 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
7691 Value *NewInVal = cast<LoadInst>(PN.getIncomingValue(i))->getOperand(0);
7692 if (NewInVal != InVal)
7693 InVal = 0;
7694 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
7695 }
7696
7697 Value *PhiVal;
7698 if (InVal) {
7699 // The new PHI unions all of the same values together. This is really
7700 // common, so we handle it intelligently here for compile-time speed.
7701 PhiVal = InVal;
7702 delete NewPN;
7703 } else {
7704 InsertNewInstBefore(NewPN, PN);
7705 PhiVal = NewPN;
7706 }
7707
7708 // If this was a volatile load that we are merging, make sure to loop through
7709 // and mark all the input loads as non-volatile. If we don't do this, we will
7710 // insert a new volatile load and the old ones will not be deletable.
7711 if (isVolatile)
7712 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
7713 cast<LoadInst>(PN.getIncomingValue(i))->setVolatile(false);
7714
7715 return new LoadInst(PhiVal, "", isVolatile, LoadAlignment);
7716}
7717
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007718
Chris Lattnerd0011092009-11-10 07:23:37 +00007719
7720/// FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
7721/// operator and they all are only used by the PHI, PHI together their
7722/// inputs, and do the operation once, to the result of the PHI.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007723Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
7724 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
7725
Chris Lattner38751f82009-11-01 20:04:24 +00007726 if (isa<GetElementPtrInst>(FirstInst))
7727 return FoldPHIArgGEPIntoPHI(PN);
7728 if (isa<LoadInst>(FirstInst))
7729 return FoldPHIArgLoadIntoPHI(PN);
7730
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007731 // Scan the instruction, looking for input operations that can be folded away.
7732 // If all input operands to the phi are the same instruction (e.g. a cast from
7733 // the same type or "+42") we can pull the operation through the PHI, reducing
7734 // code size and simplifying code.
7735 Constant *ConstantOp = 0;
7736 const Type *CastSrcTy = 0;
Chris Lattner310a00f2009-11-01 19:50:13 +00007737
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007738 if (isa<CastInst>(FirstInst)) {
7739 CastSrcTy = FirstInst->getOperand(0)->getType();
Chris Lattner4ca73902009-11-08 21:20:06 +00007740
7741 // Be careful about transforming integer PHIs. We don't want to pessimize
7742 // the code by turning an i32 into an i1293.
7743 if (isa<IntegerType>(PN.getType()) && isa<IntegerType>(CastSrcTy)) {
Chris Lattnerd0011092009-11-10 07:23:37 +00007744 if (!ShouldChangeType(PN.getType(), CastSrcTy, TD))
Chris Lattner4ca73902009-11-08 21:20:06 +00007745 return 0;
7746 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007747 } else if (isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst)) {
7748 // Can fold binop, compare or shift here if the RHS is a constant,
7749 // otherwise call FoldPHIArgBinOpIntoPHI.
7750 ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
7751 if (ConstantOp == 0)
7752 return FoldPHIArgBinOpIntoPHI(PN);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007753 } else {
7754 return 0; // Cannot fold this operation.
7755 }
7756
7757 // Check to see if all arguments are the same operation.
7758 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
Chris Lattner38751f82009-11-01 20:04:24 +00007759 Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
7760 if (I == 0 || !I->hasOneUse() || !I->isSameOperationAs(FirstInst))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007761 return 0;
7762 if (CastSrcTy) {
7763 if (I->getOperand(0)->getType() != CastSrcTy)
7764 return 0; // Cast operation must match.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007765 } else if (I->getOperand(1) != ConstantOp) {
7766 return 0;
7767 }
7768 }
7769
7770 // Okay, they are all the same operation. Create a new PHI node of the
7771 // correct type, and PHI together all of the LHS's of the instructions.
Gabor Greifd6da1d02008-04-06 20:25:17 +00007772 PHINode *NewPN = PHINode::Create(FirstInst->getOperand(0)->getType(),
7773 PN.getName()+".in");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007774 NewPN->reserveOperandSpace(PN.getNumOperands()/2);
7775
7776 Value *InVal = FirstInst->getOperand(0);
7777 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
7778
7779 // Add all operands to the new PHI.
7780 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
7781 Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
7782 if (NewInVal != InVal)
7783 InVal = 0;
7784 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
7785 }
7786
7787 Value *PhiVal;
7788 if (InVal) {
7789 // The new PHI unions all of the same values together. This is really
7790 // common, so we handle it intelligently here for compile-time speed.
7791 PhiVal = InVal;
7792 delete NewPN;
7793 } else {
7794 InsertNewInstBefore(NewPN, PN);
7795 PhiVal = NewPN;
7796 }
7797
7798 // Insert and return the new operation.
Chris Lattner310a00f2009-11-01 19:50:13 +00007799 if (CastInst *FirstCI = dyn_cast<CastInst>(FirstInst))
Gabor Greifa645dd32008-05-16 19:29:10 +00007800 return CastInst::Create(FirstCI->getOpcode(), PhiVal, PN.getType());
Chris Lattner310a00f2009-11-01 19:50:13 +00007801
Chris Lattnerfc984e92008-04-29 17:13:43 +00007802 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Gabor Greifa645dd32008-05-16 19:29:10 +00007803 return BinaryOperator::Create(BinOp->getOpcode(), PhiVal, ConstantOp);
Chris Lattner310a00f2009-11-01 19:50:13 +00007804
Chris Lattner38751f82009-11-01 20:04:24 +00007805 CmpInst *CIOp = cast<CmpInst>(FirstInst);
7806 return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(),
7807 PhiVal, ConstantOp);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007808}
7809
7810/// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
7811/// that is dead.
7812static bool DeadPHICycle(PHINode *PN,
7813 SmallPtrSet<PHINode*, 16> &PotentiallyDeadPHIs) {
7814 if (PN->use_empty()) return true;
7815 if (!PN->hasOneUse()) return false;
7816
7817 // Remember this node, and if we find the cycle, return.
7818 if (!PotentiallyDeadPHIs.insert(PN))
7819 return true;
Chris Lattneradf2e342007-08-28 04:23:55 +00007820
7821 // Don't scan crazily complex things.
7822 if (PotentiallyDeadPHIs.size() == 16)
7823 return false;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007824
7825 if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
7826 return DeadPHICycle(PU, PotentiallyDeadPHIs);
7827
7828 return false;
7829}
7830
Chris Lattner27b695d2007-11-06 21:52:06 +00007831/// PHIsEqualValue - Return true if this phi node is always equal to
7832/// NonPhiInVal. This happens with mutually cyclic phi nodes like:
7833/// z = some value; x = phi (y, z); y = phi (x, z)
7834static bool PHIsEqualValue(PHINode *PN, Value *NonPhiInVal,
7835 SmallPtrSet<PHINode*, 16> &ValueEqualPHIs) {
7836 // See if we already saw this PHI node.
7837 if (!ValueEqualPHIs.insert(PN))
7838 return true;
7839
7840 // Don't scan crazily complex things.
7841 if (ValueEqualPHIs.size() == 16)
7842 return false;
7843
7844 // Scan the operands to see if they are either phi nodes or are equal to
7845 // the value.
7846 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
7847 Value *Op = PN->getIncomingValue(i);
7848 if (PHINode *OpPN = dyn_cast<PHINode>(Op)) {
7849 if (!PHIsEqualValue(OpPN, NonPhiInVal, ValueEqualPHIs))
7850 return false;
7851 } else if (Op != NonPhiInVal)
7852 return false;
7853 }
7854
7855 return true;
7856}
7857
7858
Chris Lattner1cd526b2009-11-08 19:23:30 +00007859namespace {
7860struct PHIUsageRecord {
Chris Lattner073c12c2009-11-09 01:38:00 +00007861 unsigned PHIId; // The ID # of the PHI (something determinstic to sort on)
Chris Lattner1cd526b2009-11-08 19:23:30 +00007862 unsigned Shift; // The amount shifted.
7863 Instruction *Inst; // The trunc instruction.
7864
Chris Lattner073c12c2009-11-09 01:38:00 +00007865 PHIUsageRecord(unsigned pn, unsigned Sh, Instruction *User)
7866 : PHIId(pn), Shift(Sh), Inst(User) {}
Chris Lattner1cd526b2009-11-08 19:23:30 +00007867
7868 bool operator<(const PHIUsageRecord &RHS) const {
Chris Lattner073c12c2009-11-09 01:38:00 +00007869 if (PHIId < RHS.PHIId) return true;
7870 if (PHIId > RHS.PHIId) return false;
Chris Lattner1cd526b2009-11-08 19:23:30 +00007871 if (Shift < RHS.Shift) return true;
Chris Lattner073c12c2009-11-09 01:38:00 +00007872 if (Shift > RHS.Shift) return false;
7873 return Inst->getType()->getPrimitiveSizeInBits() <
Chris Lattner1cd526b2009-11-08 19:23:30 +00007874 RHS.Inst->getType()->getPrimitiveSizeInBits();
7875 }
7876};
Chris Lattner073c12c2009-11-09 01:38:00 +00007877
7878struct LoweredPHIRecord {
7879 PHINode *PN; // The PHI that was lowered.
7880 unsigned Shift; // The amount shifted.
7881 unsigned Width; // The width extracted.
7882
7883 LoweredPHIRecord(PHINode *pn, unsigned Sh, const Type *Ty)
7884 : PN(pn), Shift(Sh), Width(Ty->getPrimitiveSizeInBits()) {}
7885
7886 // Ctor form used by DenseMap.
7887 LoweredPHIRecord(PHINode *pn, unsigned Sh)
7888 : PN(pn), Shift(Sh), Width(0) {}
7889};
7890}
7891
7892namespace llvm {
7893 template<>
7894 struct DenseMapInfo<LoweredPHIRecord> {
7895 static inline LoweredPHIRecord getEmptyKey() {
7896 return LoweredPHIRecord(0, 0);
7897 }
7898 static inline LoweredPHIRecord getTombstoneKey() {
7899 return LoweredPHIRecord(0, 1);
7900 }
7901 static unsigned getHashValue(const LoweredPHIRecord &Val) {
7902 return DenseMapInfo<PHINode*>::getHashValue(Val.PN) ^ (Val.Shift>>3) ^
7903 (Val.Width>>3);
7904 }
7905 static bool isEqual(const LoweredPHIRecord &LHS,
7906 const LoweredPHIRecord &RHS) {
7907 return LHS.PN == RHS.PN && LHS.Shift == RHS.Shift &&
7908 LHS.Width == RHS.Width;
7909 }
Chris Lattner073c12c2009-11-09 01:38:00 +00007910 };
Chris Lattner169f3a22009-12-15 07:26:43 +00007911 template <>
7912 struct isPodLike<LoweredPHIRecord> { static const bool value = true; };
Chris Lattner1cd526b2009-11-08 19:23:30 +00007913}
7914
7915
7916/// SliceUpIllegalIntegerPHI - This is an integer PHI and we know that it has an
7917/// illegal type: see if it is only used by trunc or trunc(lshr) operations. If
7918/// so, we split the PHI into the various pieces being extracted. This sort of
7919/// thing is introduced when SROA promotes an aggregate to large integer values.
7920///
7921/// TODO: The user of the trunc may be an bitcast to float/double/vector or an
7922/// inttoptr. We should produce new PHIs in the right type.
7923///
Chris Lattner073c12c2009-11-09 01:38:00 +00007924Instruction *InstCombiner::SliceUpIllegalIntegerPHI(PHINode &FirstPhi) {
7925 // PHIUsers - Keep track of all of the truncated values extracted from a set
7926 // of PHIs, along with their offset. These are the things we want to rewrite.
Chris Lattner1cd526b2009-11-08 19:23:30 +00007927 SmallVector<PHIUsageRecord, 16> PHIUsers;
7928
Chris Lattner073c12c2009-11-09 01:38:00 +00007929 // PHIs are often mutually cyclic, so we keep track of a whole set of PHI
7930 // nodes which are extracted from. PHIsToSlice is a set we use to avoid
7931 // revisiting PHIs, PHIsInspected is a ordered list of PHIs that we need to
7932 // check the uses of (to ensure they are all extracts).
7933 SmallVector<PHINode*, 8> PHIsToSlice;
7934 SmallPtrSet<PHINode*, 8> PHIsInspected;
7935
7936 PHIsToSlice.push_back(&FirstPhi);
7937 PHIsInspected.insert(&FirstPhi);
7938
7939 for (unsigned PHIId = 0; PHIId != PHIsToSlice.size(); ++PHIId) {
7940 PHINode *PN = PHIsToSlice[PHIId];
Chris Lattner1cd526b2009-11-08 19:23:30 +00007941
Chris Lattner4a01aaa2009-12-19 07:01:15 +00007942 // Scan the input list of the PHI. If any input is an invoke, and if the
7943 // input is defined in the predecessor, then we won't be split the critical
7944 // edge which is required to insert a truncate. Because of this, we have to
7945 // bail out.
7946 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
7947 InvokeInst *II = dyn_cast<InvokeInst>(PN->getIncomingValue(i));
7948 if (II == 0) continue;
7949 if (II->getParent() != PN->getIncomingBlock(i))
7950 continue;
7951
7952 // If we have a phi, and if it's directly in the predecessor, then we have
7953 // a critical edge where we need to put the truncate. Since we can't
7954 // split the edge in instcombine, we have to bail out.
7955 return 0;
7956 }
7957
7958
Chris Lattner073c12c2009-11-09 01:38:00 +00007959 for (Value::use_iterator UI = PN->use_begin(), E = PN->use_end();
7960 UI != E; ++UI) {
7961 Instruction *User = cast<Instruction>(*UI);
7962
7963 // If the user is a PHI, inspect its uses recursively.
7964 if (PHINode *UserPN = dyn_cast<PHINode>(User)) {
7965 if (PHIsInspected.insert(UserPN))
7966 PHIsToSlice.push_back(UserPN);
7967 continue;
7968 }
7969
7970 // Truncates are always ok.
7971 if (isa<TruncInst>(User)) {
7972 PHIUsers.push_back(PHIUsageRecord(PHIId, 0, User));
7973 continue;
7974 }
7975
7976 // Otherwise it must be a lshr which can only be used by one trunc.
7977 if (User->getOpcode() != Instruction::LShr ||
7978 !User->hasOneUse() || !isa<TruncInst>(User->use_back()) ||
7979 !isa<ConstantInt>(User->getOperand(1)))
7980 return 0;
7981
7982 unsigned Shift = cast<ConstantInt>(User->getOperand(1))->getZExtValue();
7983 PHIUsers.push_back(PHIUsageRecord(PHIId, Shift, User->use_back()));
Chris Lattner1cd526b2009-11-08 19:23:30 +00007984 }
Chris Lattner1cd526b2009-11-08 19:23:30 +00007985 }
7986
7987 // If we have no users, they must be all self uses, just nuke the PHI.
7988 if (PHIUsers.empty())
Chris Lattner073c12c2009-11-09 01:38:00 +00007989 return ReplaceInstUsesWith(FirstPhi, UndefValue::get(FirstPhi.getType()));
Chris Lattner1cd526b2009-11-08 19:23:30 +00007990
7991 // If this phi node is transformable, create new PHIs for all the pieces
7992 // extracted out of it. First, sort the users by their offset and size.
7993 array_pod_sort(PHIUsers.begin(), PHIUsers.end());
7994
Chris Lattner073c12c2009-11-09 01:38:00 +00007995 DEBUG(errs() << "SLICING UP PHI: " << FirstPhi << '\n';
7996 for (unsigned i = 1, e = PHIsToSlice.size(); i != e; ++i)
7997 errs() << "AND USER PHI #" << i << ": " << *PHIsToSlice[i] <<'\n';
7998 );
Chris Lattner1cd526b2009-11-08 19:23:30 +00007999
Chris Lattner073c12c2009-11-09 01:38:00 +00008000 // PredValues - This is a temporary used when rewriting PHI nodes. It is
8001 // hoisted out here to avoid construction/destruction thrashing.
Chris Lattner1cd526b2009-11-08 19:23:30 +00008002 DenseMap<BasicBlock*, Value*> PredValues;
8003
Chris Lattner073c12c2009-11-09 01:38:00 +00008004 // ExtractedVals - Each new PHI we introduce is saved here so we don't
8005 // introduce redundant PHIs.
8006 DenseMap<LoweredPHIRecord, PHINode*> ExtractedVals;
8007
8008 for (unsigned UserI = 0, UserE = PHIUsers.size(); UserI != UserE; ++UserI) {
8009 unsigned PHIId = PHIUsers[UserI].PHIId;
8010 PHINode *PN = PHIsToSlice[PHIId];
Chris Lattner1cd526b2009-11-08 19:23:30 +00008011 unsigned Offset = PHIUsers[UserI].Shift;
8012 const Type *Ty = PHIUsers[UserI].Inst->getType();
Chris Lattner1cd526b2009-11-08 19:23:30 +00008013
Chris Lattner073c12c2009-11-09 01:38:00 +00008014 PHINode *EltPHI;
8015
8016 // If we've already lowered a user like this, reuse the previously lowered
8017 // value.
8018 if ((EltPHI = ExtractedVals[LoweredPHIRecord(PN, Offset, Ty)]) == 0) {
Chris Lattner1cd526b2009-11-08 19:23:30 +00008019
Chris Lattner073c12c2009-11-09 01:38:00 +00008020 // Otherwise, Create the new PHI node for this user.
8021 EltPHI = PHINode::Create(Ty, PN->getName()+".off"+Twine(Offset), PN);
8022 assert(EltPHI->getType() != PN->getType() &&
8023 "Truncate didn't shrink phi?");
8024
8025 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
8026 BasicBlock *Pred = PN->getIncomingBlock(i);
8027 Value *&PredVal = PredValues[Pred];
8028
8029 // If we already have a value for this predecessor, reuse it.
8030 if (PredVal) {
8031 EltPHI->addIncoming(PredVal, Pred);
8032 continue;
8033 }
Chris Lattner1cd526b2009-11-08 19:23:30 +00008034
Chris Lattner073c12c2009-11-09 01:38:00 +00008035 // Handle the PHI self-reuse case.
8036 Value *InVal = PN->getIncomingValue(i);
8037 if (InVal == PN) {
8038 PredVal = EltPHI;
8039 EltPHI->addIncoming(PredVal, Pred);
8040 continue;
Chris Lattner4a01aaa2009-12-19 07:01:15 +00008041 }
8042
8043 if (PHINode *InPHI = dyn_cast<PHINode>(PN)) {
Chris Lattner073c12c2009-11-09 01:38:00 +00008044 // If the incoming value was a PHI, and if it was one of the PHIs we
8045 // already rewrote it, just use the lowered value.
8046 if (Value *Res = ExtractedVals[LoweredPHIRecord(InPHI, Offset, Ty)]) {
8047 PredVal = Res;
8048 EltPHI->addIncoming(PredVal, Pred);
8049 continue;
8050 }
8051 }
8052
8053 // Otherwise, do an extract in the predecessor.
8054 Builder->SetInsertPoint(Pred, Pred->getTerminator());
8055 Value *Res = InVal;
8056 if (Offset)
8057 Res = Builder->CreateLShr(Res, ConstantInt::get(InVal->getType(),
8058 Offset), "extract");
8059 Res = Builder->CreateTrunc(Res, Ty, "extract.t");
8060 PredVal = Res;
8061 EltPHI->addIncoming(Res, Pred);
8062
8063 // If the incoming value was a PHI, and if it was one of the PHIs we are
8064 // rewriting, we will ultimately delete the code we inserted. This
8065 // means we need to revisit that PHI to make sure we extract out the
8066 // needed piece.
8067 if (PHINode *OldInVal = dyn_cast<PHINode>(PN->getIncomingValue(i)))
8068 if (PHIsInspected.count(OldInVal)) {
8069 unsigned RefPHIId = std::find(PHIsToSlice.begin(),PHIsToSlice.end(),
8070 OldInVal)-PHIsToSlice.begin();
8071 PHIUsers.push_back(PHIUsageRecord(RefPHIId, Offset,
8072 cast<Instruction>(Res)));
8073 ++UserE;
8074 }
Chris Lattner1cd526b2009-11-08 19:23:30 +00008075 }
Chris Lattner073c12c2009-11-09 01:38:00 +00008076 PredValues.clear();
Chris Lattner1cd526b2009-11-08 19:23:30 +00008077
Chris Lattner073c12c2009-11-09 01:38:00 +00008078 DEBUG(errs() << " Made element PHI for offset " << Offset << ": "
8079 << *EltPHI << '\n');
8080 ExtractedVals[LoweredPHIRecord(PN, Offset, Ty)] = EltPHI;
Chris Lattner1cd526b2009-11-08 19:23:30 +00008081 }
Chris Lattner1cd526b2009-11-08 19:23:30 +00008082
Chris Lattner073c12c2009-11-09 01:38:00 +00008083 // Replace the use of this piece with the PHI node.
8084 ReplaceInstUsesWith(*PHIUsers[UserI].Inst, EltPHI);
Chris Lattner1cd526b2009-11-08 19:23:30 +00008085 }
Chris Lattner073c12c2009-11-09 01:38:00 +00008086
8087 // Replace all the remaining uses of the PHI nodes (self uses and the lshrs)
8088 // with undefs.
8089 Value *Undef = UndefValue::get(FirstPhi.getType());
8090 for (unsigned i = 1, e = PHIsToSlice.size(); i != e; ++i)
8091 ReplaceInstUsesWith(*PHIsToSlice[i], Undef);
8092 return ReplaceInstUsesWith(FirstPhi, Undef);
Chris Lattner1cd526b2009-11-08 19:23:30 +00008093}
8094
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008095// PHINode simplification
8096//
8097Instruction *InstCombiner::visitPHINode(PHINode &PN) {
8098 // If LCSSA is around, don't mess with Phi nodes
8099 if (MustPreserveLCSSA) return 0;
8100
8101 if (Value *V = PN.hasConstantValue())
8102 return ReplaceInstUsesWith(PN, V);
8103
8104 // If all PHI operands are the same operation, pull them through the PHI,
8105 // reducing code size.
8106 if (isa<Instruction>(PN.getIncomingValue(0)) &&
Chris Lattner9e1916e2008-12-01 02:34:36 +00008107 isa<Instruction>(PN.getIncomingValue(1)) &&
8108 cast<Instruction>(PN.getIncomingValue(0))->getOpcode() ==
8109 cast<Instruction>(PN.getIncomingValue(1))->getOpcode() &&
8110 // FIXME: The hasOneUse check will fail for PHIs that use the value more
8111 // than themselves more than once.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008112 PN.getIncomingValue(0)->hasOneUse())
8113 if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
8114 return Result;
8115
8116 // If this is a trivial cycle in the PHI node graph, remove it. Basically, if
8117 // this PHI only has a single use (a PHI), and if that PHI only has one use (a
8118 // PHI)... break the cycle.
8119 if (PN.hasOneUse()) {
8120 Instruction *PHIUser = cast<Instruction>(PN.use_back());
8121 if (PHINode *PU = dyn_cast<PHINode>(PHIUser)) {
8122 SmallPtrSet<PHINode*, 16> PotentiallyDeadPHIs;
8123 PotentiallyDeadPHIs.insert(&PN);
8124 if (DeadPHICycle(PU, PotentiallyDeadPHIs))
Owen Andersonb99ecca2009-07-30 23:03:37 +00008125 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008126 }
8127
8128 // If this phi has a single use, and if that use just computes a value for
8129 // the next iteration of a loop, delete the phi. This occurs with unused
8130 // induction variables, e.g. "for (int j = 0; ; ++j);". Detecting this
8131 // common case here is good because the only other things that catch this
8132 // are induction variable analysis (sometimes) and ADCE, which is only run
8133 // late.
8134 if (PHIUser->hasOneUse() &&
8135 (isa<BinaryOperator>(PHIUser) || isa<GetElementPtrInst>(PHIUser)) &&
8136 PHIUser->use_back() == &PN) {
Owen Andersonb99ecca2009-07-30 23:03:37 +00008137 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008138 }
8139 }
8140
Chris Lattner27b695d2007-11-06 21:52:06 +00008141 // We sometimes end up with phi cycles that non-obviously end up being the
8142 // same value, for example:
8143 // z = some value; x = phi (y, z); y = phi (x, z)
8144 // where the phi nodes don't necessarily need to be in the same block. Do a
8145 // quick check to see if the PHI node only contains a single non-phi value, if
8146 // so, scan to see if the phi cycle is actually equal to that value.
8147 {
8148 unsigned InValNo = 0, NumOperandVals = PN.getNumIncomingValues();
8149 // Scan for the first non-phi operand.
8150 while (InValNo != NumOperandVals &&
8151 isa<PHINode>(PN.getIncomingValue(InValNo)))
8152 ++InValNo;
8153
8154 if (InValNo != NumOperandVals) {
8155 Value *NonPhiInVal = PN.getOperand(InValNo);
8156
8157 // Scan the rest of the operands to see if there are any conflicts, if so
8158 // there is no need to recursively scan other phis.
8159 for (++InValNo; InValNo != NumOperandVals; ++InValNo) {
8160 Value *OpVal = PN.getIncomingValue(InValNo);
8161 if (OpVal != NonPhiInVal && !isa<PHINode>(OpVal))
8162 break;
8163 }
8164
8165 // If we scanned over all operands, then we have one unique value plus
8166 // phi values. Scan PHI nodes to see if they all merge in each other or
8167 // the value.
8168 if (InValNo == NumOperandVals) {
8169 SmallPtrSet<PHINode*, 16> ValueEqualPHIs;
8170 if (PHIsEqualValue(&PN, NonPhiInVal, ValueEqualPHIs))
8171 return ReplaceInstUsesWith(PN, NonPhiInVal);
8172 }
8173 }
8174 }
Dan Gohman012d03d2009-10-30 22:22:22 +00008175
Dan Gohman2cc8e842009-10-31 14:22:52 +00008176 // If there are multiple PHIs, sort their operands so that they all list
8177 // the blocks in the same order. This will help identical PHIs be eliminated
8178 // by other passes. Other passes shouldn't depend on this for correctness
8179 // however.
8180 PHINode *FirstPN = cast<PHINode>(PN.getParent()->begin());
8181 if (&PN != FirstPN)
8182 for (unsigned i = 0, e = FirstPN->getNumIncomingValues(); i != e; ++i) {
Dan Gohman012d03d2009-10-30 22:22:22 +00008183 BasicBlock *BBA = PN.getIncomingBlock(i);
Dan Gohman2cc8e842009-10-31 14:22:52 +00008184 BasicBlock *BBB = FirstPN->getIncomingBlock(i);
8185 if (BBA != BBB) {
8186 Value *VA = PN.getIncomingValue(i);
8187 unsigned j = PN.getBasicBlockIndex(BBB);
8188 Value *VB = PN.getIncomingValue(j);
8189 PN.setIncomingBlock(i, BBB);
8190 PN.setIncomingValue(i, VB);
8191 PN.setIncomingBlock(j, BBA);
8192 PN.setIncomingValue(j, VA);
Chris Lattnerd56c0cb2009-10-31 17:48:31 +00008193 // NOTE: Instcombine normally would want us to "return &PN" if we
8194 // modified any of the operands of an instruction. However, since we
8195 // aren't adding or removing uses (just rearranging them) we don't do
8196 // this in this case.
Dan Gohman2cc8e842009-10-31 14:22:52 +00008197 }
Dan Gohman012d03d2009-10-30 22:22:22 +00008198 }
8199
Chris Lattner1cd526b2009-11-08 19:23:30 +00008200 // If this is an integer PHI and we know that it has an illegal type, see if
8201 // it is only used by trunc or trunc(lshr) operations. If so, we split the
8202 // PHI into the various pieces being extracted. This sort of thing is
8203 // introduced when SROA promotes an aggregate to a single large integer type.
Chris Lattner4ca73902009-11-08 21:20:06 +00008204 if (isa<IntegerType>(PN.getType()) && TD &&
Chris Lattner1cd526b2009-11-08 19:23:30 +00008205 !TD->isLegalInteger(PN.getType()->getPrimitiveSizeInBits()))
8206 if (Instruction *Res = SliceUpIllegalIntegerPHI(PN))
8207 return Res;
8208
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008209 return 0;
8210}
8211
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008212Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
Chris Lattner5594a482009-11-27 00:29:05 +00008213 SmallVector<Value*, 8> Ops(GEP.op_begin(), GEP.op_end());
8214
8215 if (Value *V = SimplifyGEPInst(&Ops[0], Ops.size(), TD))
8216 return ReplaceInstUsesWith(GEP, V);
8217
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008218 Value *PtrOp = GEP.getOperand(0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008219
8220 if (isa<UndefValue>(GEP.getOperand(0)))
Owen Andersonb99ecca2009-07-30 23:03:37 +00008221 return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008222
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008223 // Eliminate unneeded casts for indices.
Chris Lattnerc0f553e2009-08-30 04:49:01 +00008224 if (TD) {
8225 bool MadeChange = false;
8226 unsigned PtrSize = TD->getPointerSizeInBits();
8227
8228 gep_type_iterator GTI = gep_type_begin(GEP);
8229 for (User::op_iterator I = GEP.op_begin() + 1, E = GEP.op_end();
8230 I != E; ++I, ++GTI) {
8231 if (!isa<SequentialType>(*GTI)) continue;
8232
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008233 // If we are using a wider index than needed for this platform, shrink it
Chris Lattnerc0f553e2009-08-30 04:49:01 +00008234 // to what we need. If narrower, sign-extend it to what we need. This
8235 // explicit cast can make subsequent optimizations more obvious.
8236 unsigned OpBits = cast<IntegerType>((*I)->getType())->getBitWidth();
Chris Lattnerc0f553e2009-08-30 04:49:01 +00008237 if (OpBits == PtrSize)
8238 continue;
8239
Chris Lattnerd6164c22009-08-30 20:01:10 +00008240 *I = Builder->CreateIntCast(*I, TD->getIntPtrType(GEP.getContext()),true);
Chris Lattnerc0f553e2009-08-30 04:49:01 +00008241 MadeChange = true;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008242 }
Chris Lattnerc0f553e2009-08-30 04:49:01 +00008243 if (MadeChange) return &GEP;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008244 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008245
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008246 // Combine Indices - If the source pointer to this getelementptr instruction
8247 // is a getelementptr instruction, combine the indices of the two
8248 // getelementptr instructions into a single instruction.
8249 //
Dan Gohman17f46f72009-07-28 01:40:03 +00008250 if (GEPOperator *Src = dyn_cast<GEPOperator>(PtrOp)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008251 // Note that if our source is a gep chain itself that we wait for that
8252 // chain to be resolved before we perform this transformation. This
8253 // avoids us creating a TON of code in some cases.
8254 //
Chris Lattnerc2c8a0a2009-08-30 05:08:50 +00008255 if (GetElementPtrInst *SrcGEP =
8256 dyn_cast<GetElementPtrInst>(Src->getOperand(0)))
8257 if (SrcGEP->getNumOperands() == 2)
8258 return 0; // Wait until our source is folded to completion.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008259
8260 SmallVector<Value*, 8> Indices;
8261
8262 // Find out whether the last index in the source GEP is a sequential idx.
8263 bool EndsWithSequential = false;
Chris Lattner1c641fc2009-08-30 05:30:55 +00008264 for (gep_type_iterator I = gep_type_begin(*Src), E = gep_type_end(*Src);
8265 I != E; ++I)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008266 EndsWithSequential = !isa<StructType>(*I);
8267
8268 // Can we combine the two pointer arithmetics offsets?
8269 if (EndsWithSequential) {
8270 // Replace: gep (gep %P, long B), long A, ...
8271 // With: T = long A+B; gep %P, T, ...
8272 //
Chris Lattnerc2c8a0a2009-08-30 05:08:50 +00008273 Value *Sum;
8274 Value *SO1 = Src->getOperand(Src->getNumOperands()-1);
8275 Value *GO1 = GEP.getOperand(1);
Owen Andersonaac28372009-07-31 20:28:14 +00008276 if (SO1 == Constant::getNullValue(SO1->getType())) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008277 Sum = GO1;
Owen Andersonaac28372009-07-31 20:28:14 +00008278 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008279 Sum = SO1;
8280 } else {
Chris Lattner1c641fc2009-08-30 05:30:55 +00008281 // If they aren't the same type, then the input hasn't been processed
8282 // by the loop above yet (which canonicalizes sequential index types to
8283 // intptr_t). Just avoid transforming this until the input has been
8284 // normalized.
8285 if (SO1->getType() != GO1->getType())
8286 return 0;
Chris Lattnerad7516a2009-08-30 18:50:58 +00008287 Sum = Builder->CreateAdd(SO1, GO1, PtrOp->getName()+".sum");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008288 }
8289
Chris Lattner1c641fc2009-08-30 05:30:55 +00008290 // Update the GEP in place if possible.
Chris Lattnerc2c8a0a2009-08-30 05:08:50 +00008291 if (Src->getNumOperands() == 2) {
8292 GEP.setOperand(0, Src->getOperand(0));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008293 GEP.setOperand(1, Sum);
8294 return &GEP;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008295 }
Chris Lattner1c641fc2009-08-30 05:30:55 +00008296 Indices.append(Src->op_begin()+1, Src->op_end()-1);
Chris Lattnerc0f553e2009-08-30 04:49:01 +00008297 Indices.push_back(Sum);
Chris Lattner1c641fc2009-08-30 05:30:55 +00008298 Indices.append(GEP.op_begin()+2, GEP.op_end());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008299 } else if (isa<Constant>(*GEP.idx_begin()) &&
8300 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
Chris Lattnerc2c8a0a2009-08-30 05:08:50 +00008301 Src->getNumOperands() != 1) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008302 // Otherwise we can do the fold if the first index of the GEP is a zero
Chris Lattner1c641fc2009-08-30 05:30:55 +00008303 Indices.append(Src->op_begin()+1, Src->op_end());
8304 Indices.append(GEP.idx_begin()+1, GEP.idx_end());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008305 }
8306
Dan Gohmanf3a08b82009-09-07 23:54:19 +00008307 if (!Indices.empty())
8308 return (cast<GEPOperator>(&GEP)->isInBounds() &&
8309 Src->isInBounds()) ?
8310 GetElementPtrInst::CreateInBounds(Src->getOperand(0), Indices.begin(),
8311 Indices.end(), GEP.getName()) :
Chris Lattnerc2c8a0a2009-08-30 05:08:50 +00008312 GetElementPtrInst::Create(Src->getOperand(0), Indices.begin(),
Chris Lattnerc0f553e2009-08-30 04:49:01 +00008313 Indices.end(), GEP.getName());
Chris Lattner95ba1ec2009-08-30 05:00:50 +00008314 }
8315
Chris Lattnerc2c8a0a2009-08-30 05:08:50 +00008316 // Handle gep(bitcast x) and gep(gep x, 0, 0, 0).
8317 if (Value *X = getBitCastOperand(PtrOp)) {
Chris Lattner95ba1ec2009-08-30 05:00:50 +00008318 assert(isa<PointerType>(X->getType()) && "Must be cast from pointer");
Chris Lattnerf3a23592009-08-30 20:36:46 +00008319
Chris Lattner83288fa2009-08-30 20:38:21 +00008320 // If the input bitcast is actually "bitcast(bitcast(x))", then we don't
8321 // want to change the gep until the bitcasts are eliminated.
8322 if (getBitCastOperand(X)) {
8323 Worklist.AddValue(PtrOp);
8324 return 0;
8325 }
8326
Chris Lattner5594a482009-11-27 00:29:05 +00008327 bool HasZeroPointerIndex = false;
8328 if (ConstantInt *C = dyn_cast<ConstantInt>(GEP.getOperand(1)))
8329 HasZeroPointerIndex = C->isZero();
8330
Chris Lattnerf3a23592009-08-30 20:36:46 +00008331 // Transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ...
8332 // into : GEP [10 x i8]* X, i32 0, ...
8333 //
8334 // Likewise, transform: GEP (bitcast i8* X to [0 x i8]*), i32 0, ...
8335 // into : GEP i8* X, ...
8336 //
8337 // This occurs when the program declares an array extern like "int X[];"
Chris Lattner95ba1ec2009-08-30 05:00:50 +00008338 if (HasZeroPointerIndex) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008339 const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
8340 const PointerType *XTy = cast<PointerType>(X->getType());
Duncan Sandscf866e62009-03-02 09:18:21 +00008341 if (const ArrayType *CATy =
8342 dyn_cast<ArrayType>(CPTy->getElementType())) {
8343 // GEP (bitcast i8* X to [0 x i8]*), i32 0, ... ?
8344 if (CATy->getElementType() == XTy->getElementType()) {
8345 // -> GEP i8* X, ...
8346 SmallVector<Value*, 8> Indices(GEP.idx_begin()+1, GEP.idx_end());
Dan Gohmanf3a08b82009-09-07 23:54:19 +00008347 return cast<GEPOperator>(&GEP)->isInBounds() ?
8348 GetElementPtrInst::CreateInBounds(X, Indices.begin(), Indices.end(),
8349 GEP.getName()) :
Dan Gohman17f46f72009-07-28 01:40:03 +00008350 GetElementPtrInst::Create(X, Indices.begin(), Indices.end(),
8351 GEP.getName());
Chris Lattnerf3a23592009-08-30 20:36:46 +00008352 }
8353
8354 if (const ArrayType *XATy = dyn_cast<ArrayType>(XTy->getElementType())){
Duncan Sandscf866e62009-03-02 09:18:21 +00008355 // GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ... ?
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008356 if (CATy->getElementType() == XATy->getElementType()) {
Duncan Sandscf866e62009-03-02 09:18:21 +00008357 // -> GEP [10 x i8]* X, i32 0, ...
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008358 // At this point, we know that the cast source type is a pointer
8359 // to an array of the same type as the destination pointer
8360 // array. Because the array type is never stepped over (there
8361 // is a leading zero) we can fold the cast into this GEP.
8362 GEP.setOperand(0, X);
8363 return &GEP;
8364 }
Duncan Sandscf866e62009-03-02 09:18:21 +00008365 }
8366 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008367 } else if (GEP.getNumOperands() == 2) {
8368 // Transform things like:
Wojciech Matyjewicz5b5ab532007-12-12 15:21:32 +00008369 // %t = getelementptr i32* bitcast ([2 x i32]* %str to i32*), i32 %V
8370 // into: %t1 = getelementptr [2 x i32]* %str, i32 0, i32 %V; bitcast
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008371 const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
8372 const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
Dan Gohmana80e2712009-07-21 23:21:54 +00008373 if (TD && isa<ArrayType>(SrcElTy) &&
Duncan Sandsec4f97d2009-05-09 07:06:46 +00008374 TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
8375 TD->getTypeAllocSize(ResElTy)) {
David Greene393be882007-09-04 15:46:09 +00008376 Value *Idx[2];
Chris Lattner03a27b42010-01-04 07:02:48 +00008377 Idx[0] = Constant::getNullValue(Type::getInt32Ty(GEP.getContext()));
David Greene393be882007-09-04 15:46:09 +00008378 Idx[1] = GEP.getOperand(1);
Dan Gohmanf3a08b82009-09-07 23:54:19 +00008379 Value *NewGEP = cast<GEPOperator>(&GEP)->isInBounds() ?
8380 Builder->CreateInBoundsGEP(X, Idx, Idx + 2, GEP.getName()) :
Chris Lattnerad7516a2009-08-30 18:50:58 +00008381 Builder->CreateGEP(X, Idx, Idx + 2, GEP.getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008382 // V and GEP are both pointer types --> BitCast
Chris Lattnerad7516a2009-08-30 18:50:58 +00008383 return new BitCastInst(NewGEP, GEP.getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008384 }
8385
8386 // Transform things like:
Wojciech Matyjewicz5b5ab532007-12-12 15:21:32 +00008387 // getelementptr i8* bitcast ([100 x double]* X to i8*), i32 %tmp
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008388 // (where tmp = 8*tmp2) into:
Wojciech Matyjewicz5b5ab532007-12-12 15:21:32 +00008389 // getelementptr [100 x double]* %arr, i32 0, i32 %tmp2; bitcast
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008390
Chris Lattner03a27b42010-01-04 07:02:48 +00008391 if (TD && isa<ArrayType>(SrcElTy) &&
8392 ResElTy == Type::getInt8Ty(GEP.getContext())) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008393 uint64_t ArrayEltSize =
Duncan Sandsec4f97d2009-05-09 07:06:46 +00008394 TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008395
8396 // Check to see if "tmp" is a scale by a multiple of ArrayEltSize. We
8397 // allow either a mul, shift, or constant here.
8398 Value *NewIdx = 0;
8399 ConstantInt *Scale = 0;
8400 if (ArrayEltSize == 1) {
8401 NewIdx = GEP.getOperand(1);
Chris Lattner1c641fc2009-08-30 05:30:55 +00008402 Scale = ConstantInt::get(cast<IntegerType>(NewIdx->getType()), 1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008403 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
Owen Andersoneacb44d2009-07-24 23:12:02 +00008404 NewIdx = ConstantInt::get(CI->getType(), 1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008405 Scale = CI;
8406 } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
8407 if (Inst->getOpcode() == Instruction::Shl &&
8408 isa<ConstantInt>(Inst->getOperand(1))) {
8409 ConstantInt *ShAmt = cast<ConstantInt>(Inst->getOperand(1));
8410 uint32_t ShAmtVal = ShAmt->getLimitedValue(64);
Owen Andersoneacb44d2009-07-24 23:12:02 +00008411 Scale = ConstantInt::get(cast<IntegerType>(Inst->getType()),
Dan Gohman8fd520a2009-06-15 22:12:54 +00008412 1ULL << ShAmtVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008413 NewIdx = Inst->getOperand(0);
8414 } else if (Inst->getOpcode() == Instruction::Mul &&
8415 isa<ConstantInt>(Inst->getOperand(1))) {
8416 Scale = cast<ConstantInt>(Inst->getOperand(1));
8417 NewIdx = Inst->getOperand(0);
8418 }
8419 }
Wojciech Matyjewicz5b5ab532007-12-12 15:21:32 +00008420
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008421 // If the index will be to exactly the right offset with the scale taken
Wojciech Matyjewicz5b5ab532007-12-12 15:21:32 +00008422 // out, perform the transformation. Note, we don't know whether Scale is
8423 // signed or not. We'll use unsigned version of division/modulo
8424 // operation after making sure Scale doesn't have the sign bit set.
Chris Lattner02962712009-02-25 18:20:01 +00008425 if (ArrayEltSize && Scale && Scale->getSExtValue() >= 0LL &&
Wojciech Matyjewicz5b5ab532007-12-12 15:21:32 +00008426 Scale->getZExtValue() % ArrayEltSize == 0) {
Owen Andersoneacb44d2009-07-24 23:12:02 +00008427 Scale = ConstantInt::get(Scale->getType(),
Wojciech Matyjewicz5b5ab532007-12-12 15:21:32 +00008428 Scale->getZExtValue() / ArrayEltSize);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008429 if (Scale->getZExtValue() != 1) {
Chris Lattnerbf09d632009-08-30 05:56:44 +00008430 Constant *C = ConstantExpr::getIntegerCast(Scale, NewIdx->getType(),
8431 false /*ZExt*/);
Chris Lattnerad7516a2009-08-30 18:50:58 +00008432 NewIdx = Builder->CreateMul(NewIdx, C, "idxscale");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008433 }
8434
8435 // Insert the new GEP instruction.
David Greene393be882007-09-04 15:46:09 +00008436 Value *Idx[2];
Chris Lattner03a27b42010-01-04 07:02:48 +00008437 Idx[0] = Constant::getNullValue(Type::getInt32Ty(GEP.getContext()));
David Greene393be882007-09-04 15:46:09 +00008438 Idx[1] = NewIdx;
Dan Gohmanf3a08b82009-09-07 23:54:19 +00008439 Value *NewGEP = cast<GEPOperator>(&GEP)->isInBounds() ?
8440 Builder->CreateInBoundsGEP(X, Idx, Idx + 2, GEP.getName()) :
8441 Builder->CreateGEP(X, Idx, Idx + 2, GEP.getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008442 // The NewGEP must be pointer typed, so must the old one -> BitCast
8443 return new BitCastInst(NewGEP, GEP.getType());
8444 }
8445 }
8446 }
8447 }
Chris Lattner111ea772009-01-09 04:53:57 +00008448
Chris Lattner94ccd5f2009-01-09 05:44:56 +00008449 /// See if we can simplify:
Chris Lattner5119c702009-08-30 05:55:36 +00008450 /// X = bitcast A* to B*
Chris Lattner94ccd5f2009-01-09 05:44:56 +00008451 /// Y = gep X, <...constant indices...>
8452 /// into a gep of the original struct. This is important for SROA and alias
8453 /// analysis of unions. If "A" is also a bitcast, wait for A/X to be merged.
Chris Lattner111ea772009-01-09 04:53:57 +00008454 if (BitCastInst *BCI = dyn_cast<BitCastInst>(PtrOp)) {
Dan Gohmana80e2712009-07-21 23:21:54 +00008455 if (TD &&
8456 !isa<BitCastInst>(BCI->getOperand(0)) && GEP.hasAllConstantIndices()) {
Chris Lattner94ccd5f2009-01-09 05:44:56 +00008457 // Determine how much the GEP moves the pointer. We are guaranteed to get
8458 // a constant back from EmitGEPOffset.
Chris Lattner63ac8422010-01-04 07:37:31 +00008459 ConstantInt *OffsetV = cast<ConstantInt>(EmitGEPOffset(&GEP));
Chris Lattner94ccd5f2009-01-09 05:44:56 +00008460 int64_t Offset = OffsetV->getSExtValue();
8461
8462 // If this GEP instruction doesn't move the pointer, just replace the GEP
8463 // with a bitcast of the real input to the dest type.
8464 if (Offset == 0) {
8465 // If the bitcast is of an allocation, and the allocation will be
8466 // converted to match the type of the cast, don't touch this.
Victor Hernandezb1687302009-10-23 21:09:37 +00008467 if (isa<AllocaInst>(BCI->getOperand(0)) ||
Victor Hernandez48c3c542009-09-18 22:35:49 +00008468 isMalloc(BCI->getOperand(0))) {
Chris Lattner94ccd5f2009-01-09 05:44:56 +00008469 // See if the bitcast simplifies, if so, don't nuke this GEP yet.
8470 if (Instruction *I = visitBitCast(*BCI)) {
8471 if (I != BCI) {
8472 I->takeName(BCI);
8473 BCI->getParent()->getInstList().insert(BCI, I);
8474 ReplaceInstUsesWith(*BCI, I);
8475 }
8476 return &GEP;
Chris Lattner111ea772009-01-09 04:53:57 +00008477 }
Chris Lattner111ea772009-01-09 04:53:57 +00008478 }
Chris Lattner94ccd5f2009-01-09 05:44:56 +00008479 return new BitCastInst(BCI->getOperand(0), GEP.getType());
Chris Lattner111ea772009-01-09 04:53:57 +00008480 }
Chris Lattner94ccd5f2009-01-09 05:44:56 +00008481
8482 // Otherwise, if the offset is non-zero, we need to find out if there is a
8483 // field at Offset in 'A's type. If so, we can pull the cast through the
8484 // GEP.
8485 SmallVector<Value*, 8> NewIndices;
8486 const Type *InTy =
8487 cast<PointerType>(BCI->getOperand(0)->getType())->getElementType();
Chris Lattner03a27b42010-01-04 07:02:48 +00008488 if (FindElementAtOffset(InTy, Offset, NewIndices, TD)) {
Dan Gohmanf3a08b82009-09-07 23:54:19 +00008489 Value *NGEP = cast<GEPOperator>(&GEP)->isInBounds() ?
8490 Builder->CreateInBoundsGEP(BCI->getOperand(0), NewIndices.begin(),
8491 NewIndices.end()) :
8492 Builder->CreateGEP(BCI->getOperand(0), NewIndices.begin(),
8493 NewIndices.end());
Chris Lattnerad7516a2009-08-30 18:50:58 +00008494
8495 if (NGEP->getType() == GEP.getType())
8496 return ReplaceInstUsesWith(GEP, NGEP);
Chris Lattner94ccd5f2009-01-09 05:44:56 +00008497 NGEP->takeName(&GEP);
8498 return new BitCastInst(NGEP, GEP.getType());
8499 }
Chris Lattner111ea772009-01-09 04:53:57 +00008500 }
8501 }
8502
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008503 return 0;
8504}
8505
Victor Hernandezb1687302009-10-23 21:09:37 +00008506Instruction *InstCombiner::visitAllocaInst(AllocaInst &AI) {
Chris Lattner310a00f2009-11-01 19:50:13 +00008507 // Convert: alloca Ty, C - where C is a constant != 1 into: alloca [C x Ty], 1
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00008508 if (AI.isArrayAllocation()) { // Check C != 1
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008509 if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
8510 const Type *NewTy =
Owen Anderson6b6e2d92009-07-29 22:17:13 +00008511 ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
Victor Hernandez37f513d2009-10-17 01:18:07 +00008512 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
Victor Hernandezb1687302009-10-23 21:09:37 +00008513 AllocaInst *New = Builder->CreateAlloca(NewTy, 0, AI.getName());
Chris Lattnerad7516a2009-08-30 18:50:58 +00008514 New->setAlignment(AI.getAlignment());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008515
8516 // Scan to the end of the allocation instructions, to skip over a block of
Dale Johannesena499d0d2009-03-11 22:19:43 +00008517 // allocas if possible...also skip interleaved debug info
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008518 //
8519 BasicBlock::iterator It = New;
Victor Hernandezb1687302009-10-23 21:09:37 +00008520 while (isa<AllocaInst>(*It) || isa<DbgInfoIntrinsic>(*It)) ++It;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008521
8522 // Now that I is pointing to the first non-allocation-inst in the block,
8523 // insert our getelementptr instruction...
8524 //
Chris Lattner03a27b42010-01-04 07:02:48 +00008525 Value *NullIdx =Constant::getNullValue(Type::getInt32Ty(AI.getContext()));
David Greene393be882007-09-04 15:46:09 +00008526 Value *Idx[2];
8527 Idx[0] = NullIdx;
8528 Idx[1] = NullIdx;
Dan Gohmanf3a08b82009-09-07 23:54:19 +00008529 Value *V = GetElementPtrInst::CreateInBounds(New, Idx, Idx + 2,
8530 New->getName()+".sub", It);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008531
8532 // Now make everything use the getelementptr instead of the original
8533 // allocation.
8534 return ReplaceInstUsesWith(AI, V);
8535 } else if (isa<UndefValue>(AI.getArraySize())) {
Owen Andersonaac28372009-07-31 20:28:14 +00008536 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008537 }
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00008538 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008539
Dan Gohmana80e2712009-07-21 23:21:54 +00008540 if (TD && isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized()) {
Dan Gohman28e78f02009-01-13 20:18:38 +00008541 // If alloca'ing a zero byte object, replace the alloca with a null pointer.
Chris Lattner27cc5472009-03-17 17:55:15 +00008542 // Note that we only do this for alloca's, because malloc should allocate
8543 // and return a unique pointer, even for a zero byte allocation.
Duncan Sandsec4f97d2009-05-09 07:06:46 +00008544 if (TD->getTypeAllocSize(AI.getAllocatedType()) == 0)
Owen Andersonaac28372009-07-31 20:28:14 +00008545 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
Dan Gohman28e78f02009-01-13 20:18:38 +00008546
8547 // If the alignment is 0 (unspecified), assign it the preferred alignment.
8548 if (AI.getAlignment() == 0)
8549 AI.setAlignment(TD->getPrefTypeAlignment(AI.getAllocatedType()));
8550 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008551
8552 return 0;
8553}
8554
Victor Hernandez93946082009-10-24 04:23:03 +00008555Instruction *InstCombiner::visitFree(Instruction &FI) {
8556 Value *Op = FI.getOperand(1);
8557
8558 // free undef -> unreachable.
8559 if (isa<UndefValue>(Op)) {
8560 // Insert a new store to null because we cannot modify the CFG here.
Chris Lattner03a27b42010-01-04 07:02:48 +00008561 new StoreInst(ConstantInt::getTrue(FI.getContext()),
8562 UndefValue::get(Type::getInt1PtrTy(FI.getContext())), &FI);
Victor Hernandez93946082009-10-24 04:23:03 +00008563 return EraseInstFromFunction(FI);
8564 }
8565
8566 // If we have 'free null' delete the instruction. This can happen in stl code
8567 // when lots of inlining happens.
8568 if (isa<ConstantPointerNull>(Op))
8569 return EraseInstFromFunction(FI);
8570
Victor Hernandezf9a7a332009-10-26 23:43:48 +00008571 // If we have a malloc call whose only use is a free call, delete both.
Dan Gohman1674ea52009-10-27 00:11:02 +00008572 if (isMalloc(Op)) {
Victor Hernandez93946082009-10-24 04:23:03 +00008573 if (CallInst* CI = extractMallocCallFromBitCast(Op)) {
8574 if (Op->hasOneUse() && CI->hasOneUse()) {
8575 EraseInstFromFunction(FI);
8576 EraseInstFromFunction(*CI);
8577 return EraseInstFromFunction(*cast<Instruction>(Op));
8578 }
8579 } else {
8580 // Op is a call to malloc
8581 if (Op->hasOneUse()) {
8582 EraseInstFromFunction(FI);
8583 return EraseInstFromFunction(*cast<Instruction>(Op));
8584 }
8585 }
Dan Gohman1674ea52009-10-27 00:11:02 +00008586 }
Victor Hernandez93946082009-10-24 04:23:03 +00008587
8588 return 0;
8589}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008590
8591/// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
Devang Patela0f8ea82007-10-18 19:52:32 +00008592static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI,
Bill Wendling44a36ea2008-02-26 10:53:30 +00008593 const TargetData *TD) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008594 User *CI = cast<User>(LI.getOperand(0));
8595 Value *CastOp = CI->getOperand(0);
8596
Mon P Wangbd05ed82009-02-07 22:19:29 +00008597 const PointerType *DestTy = cast<PointerType>(CI->getType());
8598 const Type *DestPTy = DestTy->getElementType();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008599 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
Mon P Wangbd05ed82009-02-07 22:19:29 +00008600
8601 // If the address spaces don't match, don't eliminate the cast.
8602 if (DestTy->getAddressSpace() != SrcTy->getAddressSpace())
8603 return 0;
8604
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008605 const Type *SrcPTy = SrcTy->getElementType();
8606
8607 if (DestPTy->isInteger() || isa<PointerType>(DestPTy) ||
8608 isa<VectorType>(DestPTy)) {
8609 // If the source is an array, the code below will not succeed. Check to
8610 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
8611 // constants.
8612 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
8613 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
8614 if (ASrcTy->getNumElements() != 0) {
8615 Value *Idxs[2];
Chris Lattner03a27b42010-01-04 07:02:48 +00008616 Idxs[0] = Constant::getNullValue(Type::getInt32Ty(LI.getContext()));
Chris Lattner7bdc6d52009-10-22 06:44:07 +00008617 Idxs[1] = Idxs[0];
Owen Anderson02b48c32009-07-29 18:55:55 +00008618 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008619 SrcTy = cast<PointerType>(CastOp->getType());
8620 SrcPTy = SrcTy->getElementType();
8621 }
8622
Dan Gohmana80e2712009-07-21 23:21:54 +00008623 if (IC.getTargetData() &&
8624 (SrcPTy->isInteger() || isa<PointerType>(SrcPTy) ||
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008625 isa<VectorType>(SrcPTy)) &&
8626 // Do not allow turning this into a load of an integer, which is then
8627 // casted to a pointer, this pessimizes pointer analysis a lot.
8628 (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
Dan Gohmana80e2712009-07-21 23:21:54 +00008629 IC.getTargetData()->getTypeSizeInBits(SrcPTy) ==
8630 IC.getTargetData()->getTypeSizeInBits(DestPTy)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008631
8632 // Okay, we are casting from one integer or pointer type to another of
8633 // the same size. Instead of casting the pointer before the load, cast
8634 // the result of the loaded value.
Chris Lattnerad7516a2009-08-30 18:50:58 +00008635 Value *NewLoad =
8636 IC.Builder->CreateLoad(CastOp, LI.isVolatile(), CI->getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008637 // Now cast the result of the load.
8638 return new BitCastInst(NewLoad, LI.getType());
8639 }
8640 }
8641 }
8642 return 0;
8643}
8644
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008645Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
8646 Value *Op = LI.getOperand(0);
8647
Dan Gohman5c4d0e12007-07-20 16:34:21 +00008648 // Attempt to improve the alignment.
Dan Gohmana80e2712009-07-21 23:21:54 +00008649 if (TD) {
8650 unsigned KnownAlign =
8651 GetOrEnforceKnownAlignment(Op, TD->getPrefTypeAlignment(LI.getType()));
8652 if (KnownAlign >
8653 (LI.getAlignment() == 0 ? TD->getABITypeAlignment(LI.getType()) :
8654 LI.getAlignment()))
8655 LI.setAlignment(KnownAlign);
8656 }
Dan Gohman5c4d0e12007-07-20 16:34:21 +00008657
Chris Lattnerf3a23592009-08-30 20:36:46 +00008658 // load (cast X) --> cast (load X) iff safe.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008659 if (isa<CastInst>(Op))
Devang Patela0f8ea82007-10-18 19:52:32 +00008660 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008661 return Res;
8662
8663 // None of the following transforms are legal for volatile loads.
8664 if (LI.isVolatile()) return 0;
8665
Dan Gohman0ff5a1f2008-10-15 23:19:35 +00008666 // Do really simple store-to-load forwarding and load CSE, to catch cases
8667 // where there are several consequtive memory accesses to the same location,
8668 // separated by a few arithmetic operations.
8669 BasicBlock::iterator BBI = &LI;
Chris Lattner6fd8c802008-11-27 08:56:30 +00008670 if (Value *AvailableVal = FindAvailableLoadedValue(Op, LI.getParent(), BBI,6))
8671 return ReplaceInstUsesWith(LI, AvailableVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008672
Chris Lattner05274832009-10-22 06:25:11 +00008673 // load(gep null, ...) -> unreachable
Christopher Lamb2c175392007-12-29 07:56:53 +00008674 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
8675 const Value *GEPI0 = GEPI->getOperand(0);
8676 // TODO: Consider a target hook for valid address spaces for this xform.
Chris Lattner6807a242009-08-30 20:06:40 +00008677 if (isa<ConstantPointerNull>(GEPI0) && GEPI->getPointerAddressSpace() == 0){
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008678 // Insert a new store to null instruction before the load to indicate
8679 // that this code is not reachable. We do this instead of inserting
8680 // an unreachable instruction directly because we cannot modify the
8681 // CFG.
Owen Andersonb99ecca2009-07-30 23:03:37 +00008682 new StoreInst(UndefValue::get(LI.getType()),
Owen Andersonaac28372009-07-31 20:28:14 +00008683 Constant::getNullValue(Op->getType()), &LI);
Owen Andersonb99ecca2009-07-30 23:03:37 +00008684 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008685 }
Christopher Lamb2c175392007-12-29 07:56:53 +00008686 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008687
Chris Lattner05274832009-10-22 06:25:11 +00008688 // load null/undef -> unreachable
8689 // TODO: Consider a target hook for valid address spaces for this xform.
8690 if (isa<UndefValue>(Op) ||
8691 (isa<ConstantPointerNull>(Op) && LI.getPointerAddressSpace() == 0)) {
8692 // Insert a new store to null instruction before the load to indicate that
8693 // this code is not reachable. We do this instead of inserting an
8694 // unreachable instruction directly because we cannot modify the CFG.
8695 new StoreInst(UndefValue::get(LI.getType()),
8696 Constant::getNullValue(Op->getType()), &LI);
8697 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008698 }
Chris Lattner05274832009-10-22 06:25:11 +00008699
8700 // Instcombine load (constantexpr_cast global) -> cast (load global)
8701 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op))
8702 if (CE->isCast())
8703 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
8704 return Res;
8705
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008706 if (Op->hasOneUse()) {
8707 // Change select and PHI nodes to select values instead of addresses: this
8708 // helps alias analysis out a lot, allows many others simplifications, and
8709 // exposes redundancy in the code.
8710 //
8711 // Note that we cannot do the transformation unless we know that the
8712 // introduced loads cannot trap! Something like this is valid as long as
8713 // the condition is always false: load (select bool %C, int* null, int* %G),
8714 // but it would not be valid if we transformed it to load from null
8715 // unconditionally.
8716 //
8717 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
8718 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
8719 if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
8720 isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
Chris Lattnerad7516a2009-08-30 18:50:58 +00008721 Value *V1 = Builder->CreateLoad(SI->getOperand(1),
8722 SI->getOperand(1)->getName()+".val");
8723 Value *V2 = Builder->CreateLoad(SI->getOperand(2),
8724 SI->getOperand(2)->getName()+".val");
Gabor Greifd6da1d02008-04-06 20:25:17 +00008725 return SelectInst::Create(SI->getCondition(), V1, V2);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008726 }
8727
8728 // load (select (cond, null, P)) -> load P
8729 if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
8730 if (C->isNullValue()) {
8731 LI.setOperand(0, SI->getOperand(2));
8732 return &LI;
8733 }
8734
8735 // load (select (cond, P, null)) -> load P
8736 if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
8737 if (C->isNullValue()) {
8738 LI.setOperand(0, SI->getOperand(1));
8739 return &LI;
8740 }
8741 }
8742 }
8743 return 0;
8744}
8745
8746/// InstCombineStoreToCast - Fold store V, (cast P) -> store (cast V), P
Chris Lattner54dddc72009-01-24 01:00:13 +00008747/// when possible. This makes it generally easy to do alias analysis and/or
8748/// SROA/mem2reg of the memory object.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008749static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
8750 User *CI = cast<User>(SI.getOperand(1));
8751 Value *CastOp = CI->getOperand(0);
8752
8753 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
Chris Lattnera032c0e2009-01-16 20:08:59 +00008754 const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType());
8755 if (SrcTy == 0) return 0;
8756
8757 const Type *SrcPTy = SrcTy->getElementType();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008758
Chris Lattnera032c0e2009-01-16 20:08:59 +00008759 if (!DestPTy->isInteger() && !isa<PointerType>(DestPTy))
8760 return 0;
8761
Chris Lattner54dddc72009-01-24 01:00:13 +00008762 /// NewGEPIndices - If SrcPTy is an aggregate type, we can emit a "noop gep"
8763 /// to its first element. This allows us to handle things like:
8764 /// store i32 xxx, (bitcast {foo*, float}* %P to i32*)
8765 /// on 32-bit hosts.
8766 SmallVector<Value*, 4> NewGEPIndices;
8767
Chris Lattnera032c0e2009-01-16 20:08:59 +00008768 // If the source is an array, the code below will not succeed. Check to
8769 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
8770 // constants.
Chris Lattner54dddc72009-01-24 01:00:13 +00008771 if (isa<ArrayType>(SrcPTy) || isa<StructType>(SrcPTy)) {
8772 // Index through pointer.
Chris Lattner03a27b42010-01-04 07:02:48 +00008773 Constant *Zero = Constant::getNullValue(Type::getInt32Ty(SI.getContext()));
Chris Lattner54dddc72009-01-24 01:00:13 +00008774 NewGEPIndices.push_back(Zero);
8775
8776 while (1) {
8777 if (const StructType *STy = dyn_cast<StructType>(SrcPTy)) {
edwin7dc0aa32009-01-24 17:16:04 +00008778 if (!STy->getNumElements()) /* Struct can be empty {} */
edwin07d74e72009-01-24 11:30:49 +00008779 break;
Chris Lattner54dddc72009-01-24 01:00:13 +00008780 NewGEPIndices.push_back(Zero);
8781 SrcPTy = STy->getElementType(0);
8782 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcPTy)) {
8783 NewGEPIndices.push_back(Zero);
8784 SrcPTy = ATy->getElementType();
8785 } else {
8786 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008787 }
Chris Lattner54dddc72009-01-24 01:00:13 +00008788 }
8789
Owen Anderson6b6e2d92009-07-29 22:17:13 +00008790 SrcTy = PointerType::get(SrcPTy, SrcTy->getAddressSpace());
Chris Lattner54dddc72009-01-24 01:00:13 +00008791 }
Chris Lattnera032c0e2009-01-16 20:08:59 +00008792
8793 if (!SrcPTy->isInteger() && !isa<PointerType>(SrcPTy))
8794 return 0;
8795
Chris Lattnerc73a0d12009-01-16 20:12:52 +00008796 // If the pointers point into different address spaces or if they point to
8797 // values with different sizes, we can't do the transformation.
Dan Gohmana80e2712009-07-21 23:21:54 +00008798 if (!IC.getTargetData() ||
8799 SrcTy->getAddressSpace() !=
Chris Lattnerc73a0d12009-01-16 20:12:52 +00008800 cast<PointerType>(CI->getType())->getAddressSpace() ||
Dan Gohmana80e2712009-07-21 23:21:54 +00008801 IC.getTargetData()->getTypeSizeInBits(SrcPTy) !=
8802 IC.getTargetData()->getTypeSizeInBits(DestPTy))
Chris Lattnera032c0e2009-01-16 20:08:59 +00008803 return 0;
8804
8805 // Okay, we are casting from one integer or pointer type to another of
8806 // the same size. Instead of casting the pointer before
8807 // the store, cast the value to be stored.
8808 Value *NewCast;
8809 Value *SIOp0 = SI.getOperand(0);
8810 Instruction::CastOps opcode = Instruction::BitCast;
8811 const Type* CastSrcTy = SIOp0->getType();
8812 const Type* CastDstTy = SrcPTy;
8813 if (isa<PointerType>(CastDstTy)) {
8814 if (CastSrcTy->isInteger())
8815 opcode = Instruction::IntToPtr;
8816 } else if (isa<IntegerType>(CastDstTy)) {
8817 if (isa<PointerType>(SIOp0->getType()))
8818 opcode = Instruction::PtrToInt;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008819 }
Chris Lattner54dddc72009-01-24 01:00:13 +00008820
8821 // SIOp0 is a pointer to aggregate and this is a store to the first field,
8822 // emit a GEP to index into its first field.
Dan Gohmanf3a08b82009-09-07 23:54:19 +00008823 if (!NewGEPIndices.empty())
8824 CastOp = IC.Builder->CreateInBoundsGEP(CastOp, NewGEPIndices.begin(),
8825 NewGEPIndices.end());
Chris Lattner54dddc72009-01-24 01:00:13 +00008826
Chris Lattnerad7516a2009-08-30 18:50:58 +00008827 NewCast = IC.Builder->CreateCast(opcode, SIOp0, CastDstTy,
8828 SIOp0->getName()+".c");
Chris Lattnera032c0e2009-01-16 20:08:59 +00008829 return new StoreInst(NewCast, CastOp);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008830}
8831
Chris Lattner6fd8c802008-11-27 08:56:30 +00008832/// equivalentAddressValues - Test if A and B will obviously have the same
8833/// value. This includes recognizing that %t0 and %t1 will have the same
8834/// value in code like this:
Dan Gohman8387bb32009-03-03 02:55:14 +00008835/// %t0 = getelementptr \@a, 0, 3
Chris Lattner6fd8c802008-11-27 08:56:30 +00008836/// store i32 0, i32* %t0
Dan Gohman8387bb32009-03-03 02:55:14 +00008837/// %t1 = getelementptr \@a, 0, 3
Chris Lattner6fd8c802008-11-27 08:56:30 +00008838/// %t2 = load i32* %t1
8839///
8840static bool equivalentAddressValues(Value *A, Value *B) {
8841 // Test if the values are trivially equivalent.
8842 if (A == B) return true;
8843
8844 // Test if the values come form identical arithmetic instructions.
Dan Gohmanfc00c4a2009-08-25 22:11:20 +00008845 // This uses isIdenticalToWhenDefined instead of isIdenticalTo because
8846 // its only used to compare two uses within the same basic block, which
8847 // means that they'll always either have the same value or one of them
8848 // will have an undefined value.
Chris Lattner6fd8c802008-11-27 08:56:30 +00008849 if (isa<BinaryOperator>(A) ||
8850 isa<CastInst>(A) ||
8851 isa<PHINode>(A) ||
8852 isa<GetElementPtrInst>(A))
8853 if (Instruction *BI = dyn_cast<Instruction>(B))
Dan Gohmanfc00c4a2009-08-25 22:11:20 +00008854 if (cast<Instruction>(A)->isIdenticalToWhenDefined(BI))
Chris Lattner6fd8c802008-11-27 08:56:30 +00008855 return true;
8856
8857 // Otherwise they may not be equivalent.
8858 return false;
8859}
8860
Dale Johannesen2c11fe22009-03-03 21:26:39 +00008861// If this instruction has two uses, one of which is a llvm.dbg.declare,
8862// return the llvm.dbg.declare.
8863DbgDeclareInst *InstCombiner::hasOneUsePlusDeclare(Value *V) {
8864 if (!V->hasNUses(2))
8865 return 0;
8866 for (Value::use_iterator UI = V->use_begin(), E = V->use_end();
8867 UI != E; ++UI) {
8868 if (DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(UI))
8869 return DI;
8870 if (isa<BitCastInst>(UI) && UI->hasOneUse()) {
8871 if (DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(UI->use_begin()))
8872 return DI;
8873 }
8874 }
8875 return 0;
8876}
8877
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008878Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
8879 Value *Val = SI.getOperand(0);
8880 Value *Ptr = SI.getOperand(1);
8881
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008882 // If the RHS is an alloca with a single use, zapify the store, making the
8883 // alloca dead.
Dale Johannesen2c11fe22009-03-03 21:26:39 +00008884 // If the RHS is an alloca with a two uses, the other one being a
8885 // llvm.dbg.declare, zapify the store and the declare, making the
8886 // alloca dead. We must do this to prevent declare's from affecting
8887 // codegen.
8888 if (!SI.isVolatile()) {
8889 if (Ptr->hasOneUse()) {
8890 if (isa<AllocaInst>(Ptr)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008891 EraseInstFromFunction(SI);
8892 ++NumCombined;
8893 return 0;
8894 }
Dale Johannesen2c11fe22009-03-03 21:26:39 +00008895 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr)) {
8896 if (isa<AllocaInst>(GEP->getOperand(0))) {
8897 if (GEP->getOperand(0)->hasOneUse()) {
8898 EraseInstFromFunction(SI);
8899 ++NumCombined;
8900 return 0;
8901 }
8902 if (DbgDeclareInst *DI = hasOneUsePlusDeclare(GEP->getOperand(0))) {
8903 EraseInstFromFunction(*DI);
8904 EraseInstFromFunction(SI);
8905 ++NumCombined;
8906 return 0;
8907 }
8908 }
8909 }
8910 }
8911 if (DbgDeclareInst *DI = hasOneUsePlusDeclare(Ptr)) {
8912 EraseInstFromFunction(*DI);
8913 EraseInstFromFunction(SI);
8914 ++NumCombined;
8915 return 0;
8916 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008917 }
8918
Dan Gohman5c4d0e12007-07-20 16:34:21 +00008919 // Attempt to improve the alignment.
Dan Gohmana80e2712009-07-21 23:21:54 +00008920 if (TD) {
8921 unsigned KnownAlign =
8922 GetOrEnforceKnownAlignment(Ptr, TD->getPrefTypeAlignment(Val->getType()));
8923 if (KnownAlign >
8924 (SI.getAlignment() == 0 ? TD->getABITypeAlignment(Val->getType()) :
8925 SI.getAlignment()))
8926 SI.setAlignment(KnownAlign);
8927 }
Dan Gohman5c4d0e12007-07-20 16:34:21 +00008928
Dale Johannesen2bf6a6b2009-03-03 01:43:03 +00008929 // Do really simple DSE, to catch cases where there are several consecutive
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008930 // stores to the same location, separated by a few arithmetic operations. This
8931 // situation often occurs with bitfield accesses.
8932 BasicBlock::iterator BBI = &SI;
8933 for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
8934 --ScanInsts) {
Dale Johannesenb773a552009-03-04 01:20:34 +00008935 --BBI;
Dale Johannesenc9612322009-03-04 01:53:05 +00008936 // Don't count debug info directives, lest they affect codegen,
8937 // and we skip pointer-to-pointer bitcasts, which are NOPs.
8938 // It is necessary for correctness to skip those that feed into a
8939 // llvm.dbg.declare, as these are not present when debugging is off.
Dale Johannesen605879d2009-03-03 22:36:47 +00008940 if (isa<DbgInfoIntrinsic>(BBI) ||
Dale Johannesenc9612322009-03-04 01:53:05 +00008941 (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType()))) {
Dale Johannesen2bf6a6b2009-03-03 01:43:03 +00008942 ScanInsts++;
Dale Johannesen2bf6a6b2009-03-03 01:43:03 +00008943 continue;
8944 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008945
8946 if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
8947 // Prev store isn't volatile, and stores to the same location?
Chris Lattner6fd8c802008-11-27 08:56:30 +00008948 if (!PrevSI->isVolatile() &&equivalentAddressValues(PrevSI->getOperand(1),
8949 SI.getOperand(1))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008950 ++NumDeadStore;
8951 ++BBI;
8952 EraseInstFromFunction(*PrevSI);
8953 continue;
8954 }
8955 break;
8956 }
8957
8958 // If this is a load, we have to stop. However, if the loaded value is from
8959 // the pointer we're loading and is producing the pointer we're storing,
8960 // then *this* store is dead (X = load P; store X -> P).
8961 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
Dan Gohman0ff5a1f2008-10-15 23:19:35 +00008962 if (LI == Val && equivalentAddressValues(LI->getOperand(0), Ptr) &&
8963 !SI.isVolatile()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008964 EraseInstFromFunction(SI);
8965 ++NumCombined;
8966 return 0;
8967 }
8968 // Otherwise, this is a load from some other location. Stores before it
8969 // may not be dead.
8970 break;
8971 }
8972
8973 // Don't skip over loads or things that can modify memory.
Chris Lattner84504282008-05-08 17:20:30 +00008974 if (BBI->mayWriteToMemory() || BBI->mayReadFromMemory())
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008975 break;
8976 }
8977
8978
8979 if (SI.isVolatile()) return 0; // Don't hack volatile stores.
8980
8981 // store X, null -> turns into 'unreachable' in SimplifyCFG
Chris Lattner6807a242009-08-30 20:06:40 +00008982 if (isa<ConstantPointerNull>(Ptr) && SI.getPointerAddressSpace() == 0) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008983 if (!isa<UndefValue>(Val)) {
Owen Andersonb99ecca2009-07-30 23:03:37 +00008984 SI.setOperand(0, UndefValue::get(Val->getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008985 if (Instruction *U = dyn_cast<Instruction>(Val))
Chris Lattner3183fb62009-08-30 06:13:40 +00008986 Worklist.Add(U); // Dropped a use.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008987 ++NumCombined;
8988 }
8989 return 0; // Do not modify these!
8990 }
8991
8992 // store undef, Ptr -> noop
8993 if (isa<UndefValue>(Val)) {
8994 EraseInstFromFunction(SI);
8995 ++NumCombined;
8996 return 0;
8997 }
8998
8999 // If the pointer destination is a cast, see if we can fold the cast into the
9000 // source instead.
9001 if (isa<CastInst>(Ptr))
9002 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
9003 return Res;
9004 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
9005 if (CE->isCast())
9006 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
9007 return Res;
9008
9009
Dale Johannesenb7a9e3e2009-03-05 02:06:48 +00009010 // If this store is the last instruction in the basic block (possibly
9011 // excepting debug info instructions and the pointer bitcasts that feed
9012 // into them), and if the block ends with an unconditional branch, try
9013 // to move it to the successor block.
9014 BBI = &SI;
9015 do {
9016 ++BBI;
9017 } while (isa<DbgInfoIntrinsic>(BBI) ||
9018 (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType())));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009019 if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
9020 if (BI->isUnconditional())
9021 if (SimplifyStoreAtEndOfBlock(SI))
9022 return 0; // xform done!
9023
9024 return 0;
9025}
9026
9027/// SimplifyStoreAtEndOfBlock - Turn things like:
9028/// if () { *P = v1; } else { *P = v2 }
9029/// into a phi node with a store in the successor.
9030///
9031/// Simplify things like:
9032/// *P = v1; if () { *P = v2; }
9033/// into a phi node with a store in the successor.
9034///
9035bool InstCombiner::SimplifyStoreAtEndOfBlock(StoreInst &SI) {
9036 BasicBlock *StoreBB = SI.getParent();
9037
9038 // Check to see if the successor block has exactly two incoming edges. If
9039 // so, see if the other predecessor contains a store to the same location.
9040 // if so, insert a PHI node (if needed) and move the stores down.
9041 BasicBlock *DestBB = StoreBB->getTerminator()->getSuccessor(0);
9042
9043 // Determine whether Dest has exactly two predecessors and, if so, compute
9044 // the other predecessor.
9045 pred_iterator PI = pred_begin(DestBB);
9046 BasicBlock *OtherBB = 0;
9047 if (*PI != StoreBB)
9048 OtherBB = *PI;
9049 ++PI;
9050 if (PI == pred_end(DestBB))
9051 return false;
9052
9053 if (*PI != StoreBB) {
9054 if (OtherBB)
9055 return false;
9056 OtherBB = *PI;
9057 }
9058 if (++PI != pred_end(DestBB))
9059 return false;
Eli Friedmanab39f9a2008-06-13 21:17:49 +00009060
9061 // Bail out if all the relevant blocks aren't distinct (this can happen,
9062 // for example, if SI is in an infinite loop)
9063 if (StoreBB == DestBB || OtherBB == DestBB)
9064 return false;
9065
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009066 // Verify that the other block ends in a branch and is not otherwise empty.
9067 BasicBlock::iterator BBI = OtherBB->getTerminator();
9068 BranchInst *OtherBr = dyn_cast<BranchInst>(BBI);
9069 if (!OtherBr || BBI == OtherBB->begin())
9070 return false;
9071
9072 // If the other block ends in an unconditional branch, check for the 'if then
9073 // else' case. there is an instruction before the branch.
9074 StoreInst *OtherStore = 0;
9075 if (OtherBr->isUnconditional()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009076 --BBI;
Dale Johannesenb7a9e3e2009-03-05 02:06:48 +00009077 // Skip over debugging info.
9078 while (isa<DbgInfoIntrinsic>(BBI) ||
9079 (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType()))) {
9080 if (BBI==OtherBB->begin())
9081 return false;
9082 --BBI;
9083 }
Chris Lattner69fa3f52009-11-02 02:06:37 +00009084 // If this isn't a store, isn't a store to the same location, or if the
9085 // alignments differ, bail out.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009086 OtherStore = dyn_cast<StoreInst>(BBI);
Chris Lattner69fa3f52009-11-02 02:06:37 +00009087 if (!OtherStore || OtherStore->getOperand(1) != SI.getOperand(1) ||
9088 OtherStore->getAlignment() != SI.getAlignment())
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009089 return false;
9090 } else {
9091 // Otherwise, the other block ended with a conditional branch. If one of the
9092 // destinations is StoreBB, then we have the if/then case.
9093 if (OtherBr->getSuccessor(0) != StoreBB &&
9094 OtherBr->getSuccessor(1) != StoreBB)
9095 return false;
9096
9097 // Okay, we know that OtherBr now goes to Dest and StoreBB, so this is an
9098 // if/then triangle. See if there is a store to the same ptr as SI that
9099 // lives in OtherBB.
9100 for (;; --BBI) {
9101 // Check to see if we find the matching store.
9102 if ((OtherStore = dyn_cast<StoreInst>(BBI))) {
Chris Lattner69fa3f52009-11-02 02:06:37 +00009103 if (OtherStore->getOperand(1) != SI.getOperand(1) ||
9104 OtherStore->getAlignment() != SI.getAlignment())
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009105 return false;
9106 break;
9107 }
Eli Friedman3a311d52008-06-13 22:02:12 +00009108 // If we find something that may be using or overwriting the stored
9109 // value, or if we run out of instructions, we can't do the xform.
9110 if (BBI->mayReadFromMemory() || BBI->mayWriteToMemory() ||
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009111 BBI == OtherBB->begin())
9112 return false;
9113 }
9114
9115 // In order to eliminate the store in OtherBr, we have to
Eli Friedman3a311d52008-06-13 22:02:12 +00009116 // make sure nothing reads or overwrites the stored value in
9117 // StoreBB.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009118 for (BasicBlock::iterator I = StoreBB->begin(); &*I != &SI; ++I) {
9119 // FIXME: This should really be AA driven.
Eli Friedman3a311d52008-06-13 22:02:12 +00009120 if (I->mayReadFromMemory() || I->mayWriteToMemory())
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009121 return false;
9122 }
9123 }
9124
9125 // Insert a PHI node now if we need it.
9126 Value *MergedVal = OtherStore->getOperand(0);
9127 if (MergedVal != SI.getOperand(0)) {
Gabor Greifd6da1d02008-04-06 20:25:17 +00009128 PHINode *PN = PHINode::Create(MergedVal->getType(), "storemerge");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009129 PN->reserveOperandSpace(2);
9130 PN->addIncoming(SI.getOperand(0), SI.getParent());
9131 PN->addIncoming(OtherStore->getOperand(0), OtherBB);
9132 MergedVal = InsertNewInstBefore(PN, DestBB->front());
9133 }
9134
9135 // Advance to a place where it is safe to insert the new store and
9136 // insert it.
Dan Gohman514277c2008-05-23 21:05:58 +00009137 BBI = DestBB->getFirstNonPHI();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009138 InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
Chris Lattner69fa3f52009-11-02 02:06:37 +00009139 OtherStore->isVolatile(),
9140 SI.getAlignment()), *BBI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009141
9142 // Nuke the old stores.
9143 EraseInstFromFunction(SI);
9144 EraseInstFromFunction(*OtherStore);
9145 ++NumCombined;
9146 return true;
9147}
9148
9149
9150Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
9151 // Change br (not X), label True, label False to: br X, label False, True
9152 Value *X = 0;
9153 BasicBlock *TrueDest;
9154 BasicBlock *FalseDest;
Dan Gohmancdff2122009-08-12 16:23:25 +00009155 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009156 !isa<Constant>(X)) {
9157 // Swap Destinations and condition...
9158 BI.setCondition(X);
9159 BI.setSuccessor(0, FalseDest);
9160 BI.setSuccessor(1, TrueDest);
9161 return &BI;
9162 }
9163
9164 // Cannonicalize fcmp_one -> fcmp_oeq
9165 FCmpInst::Predicate FPred; Value *Y;
9166 if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)),
Chris Lattner3183fb62009-08-30 06:13:40 +00009167 TrueDest, FalseDest)) &&
9168 BI.getCondition()->hasOneUse())
9169 if (FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
9170 FPred == FCmpInst::FCMP_OGE) {
9171 FCmpInst *Cond = cast<FCmpInst>(BI.getCondition());
9172 Cond->setPredicate(FCmpInst::getInversePredicate(FPred));
9173
9174 // Swap Destinations and condition.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009175 BI.setSuccessor(0, FalseDest);
9176 BI.setSuccessor(1, TrueDest);
Chris Lattner3183fb62009-08-30 06:13:40 +00009177 Worklist.Add(Cond);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009178 return &BI;
9179 }
9180
9181 // Cannonicalize icmp_ne -> icmp_eq
9182 ICmpInst::Predicate IPred;
9183 if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
Chris Lattner3183fb62009-08-30 06:13:40 +00009184 TrueDest, FalseDest)) &&
9185 BI.getCondition()->hasOneUse())
9186 if (IPred == ICmpInst::ICMP_NE || IPred == ICmpInst::ICMP_ULE ||
9187 IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
9188 IPred == ICmpInst::ICMP_SGE) {
9189 ICmpInst *Cond = cast<ICmpInst>(BI.getCondition());
9190 Cond->setPredicate(ICmpInst::getInversePredicate(IPred));
9191 // Swap Destinations and condition.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009192 BI.setSuccessor(0, FalseDest);
9193 BI.setSuccessor(1, TrueDest);
Chris Lattner3183fb62009-08-30 06:13:40 +00009194 Worklist.Add(Cond);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009195 return &BI;
9196 }
9197
9198 return 0;
9199}
9200
9201Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
9202 Value *Cond = SI.getCondition();
9203 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
9204 if (I->getOpcode() == Instruction::Add)
9205 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
9206 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
9207 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
Owen Anderson24be4c12009-07-03 00:17:18 +00009208 SI.setOperand(i,
Owen Anderson02b48c32009-07-29 18:55:55 +00009209 ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009210 AddRHS));
9211 SI.setOperand(0, I->getOperand(0));
Chris Lattner3183fb62009-08-30 06:13:40 +00009212 Worklist.Add(I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009213 return &SI;
9214 }
9215 }
9216 return 0;
9217}
9218
Matthijs Kooijmanda9ef702008-06-11 14:05:05 +00009219Instruction *InstCombiner::visitExtractValueInst(ExtractValueInst &EV) {
Matthijs Kooijman45e8eb42008-07-16 12:55:45 +00009220 Value *Agg = EV.getAggregateOperand();
Matthijs Kooijmanda9ef702008-06-11 14:05:05 +00009221
Matthijs Kooijman45e8eb42008-07-16 12:55:45 +00009222 if (!EV.hasIndices())
9223 return ReplaceInstUsesWith(EV, Agg);
9224
9225 if (Constant *C = dyn_cast<Constant>(Agg)) {
9226 if (isa<UndefValue>(C))
Owen Andersonb99ecca2009-07-30 23:03:37 +00009227 return ReplaceInstUsesWith(EV, UndefValue::get(EV.getType()));
Matthijs Kooijman45e8eb42008-07-16 12:55:45 +00009228
9229 if (isa<ConstantAggregateZero>(C))
Owen Andersonaac28372009-07-31 20:28:14 +00009230 return ReplaceInstUsesWith(EV, Constant::getNullValue(EV.getType()));
Matthijs Kooijman45e8eb42008-07-16 12:55:45 +00009231
9232 if (isa<ConstantArray>(C) || isa<ConstantStruct>(C)) {
9233 // Extract the element indexed by the first index out of the constant
9234 Value *V = C->getOperand(*EV.idx_begin());
9235 if (EV.getNumIndices() > 1)
9236 // Extract the remaining indices out of the constant indexed by the
9237 // first index
9238 return ExtractValueInst::Create(V, EV.idx_begin() + 1, EV.idx_end());
9239 else
9240 return ReplaceInstUsesWith(EV, V);
9241 }
9242 return 0; // Can't handle other constants
9243 }
9244 if (InsertValueInst *IV = dyn_cast<InsertValueInst>(Agg)) {
9245 // We're extracting from an insertvalue instruction, compare the indices
9246 const unsigned *exti, *exte, *insi, *inse;
9247 for (exti = EV.idx_begin(), insi = IV->idx_begin(),
9248 exte = EV.idx_end(), inse = IV->idx_end();
9249 exti != exte && insi != inse;
9250 ++exti, ++insi) {
9251 if (*insi != *exti)
9252 // The insert and extract both reference distinctly different elements.
9253 // This means the extract is not influenced by the insert, and we can
9254 // replace the aggregate operand of the extract with the aggregate
9255 // operand of the insert. i.e., replace
9256 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
9257 // %E = extractvalue { i32, { i32 } } %I, 0
9258 // with
9259 // %E = extractvalue { i32, { i32 } } %A, 0
9260 return ExtractValueInst::Create(IV->getAggregateOperand(),
9261 EV.idx_begin(), EV.idx_end());
9262 }
9263 if (exti == exte && insi == inse)
9264 // Both iterators are at the end: Index lists are identical. Replace
9265 // %B = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
9266 // %C = extractvalue { i32, { i32 } } %B, 1, 0
9267 // with "i32 42"
9268 return ReplaceInstUsesWith(EV, IV->getInsertedValueOperand());
9269 if (exti == exte) {
9270 // The extract list is a prefix of the insert list. i.e. replace
9271 // %I = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
9272 // %E = extractvalue { i32, { i32 } } %I, 1
9273 // with
9274 // %X = extractvalue { i32, { i32 } } %A, 1
9275 // %E = insertvalue { i32 } %X, i32 42, 0
9276 // by switching the order of the insert and extract (though the
9277 // insertvalue should be left in, since it may have other uses).
Chris Lattnerad7516a2009-08-30 18:50:58 +00009278 Value *NewEV = Builder->CreateExtractValue(IV->getAggregateOperand(),
9279 EV.idx_begin(), EV.idx_end());
Matthijs Kooijman45e8eb42008-07-16 12:55:45 +00009280 return InsertValueInst::Create(NewEV, IV->getInsertedValueOperand(),
9281 insi, inse);
9282 }
9283 if (insi == inse)
9284 // The insert list is a prefix of the extract list
9285 // We can simply remove the common indices from the extract and make it
9286 // operate on the inserted value instead of the insertvalue result.
9287 // i.e., replace
9288 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
9289 // %E = extractvalue { i32, { i32 } } %I, 1, 0
9290 // with
9291 // %E extractvalue { i32 } { i32 42 }, 0
9292 return ExtractValueInst::Create(IV->getInsertedValueOperand(),
9293 exti, exte);
9294 }
Chris Lattner69a70752009-11-09 07:07:56 +00009295 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Agg)) {
9296 // We're extracting from an intrinsic, see if we're the only user, which
9297 // allows us to simplify multiple result intrinsics to simpler things that
9298 // just get one value..
9299 if (II->hasOneUse()) {
9300 // Check if we're grabbing the overflow bit or the result of a 'with
9301 // overflow' intrinsic. If it's the latter we can remove the intrinsic
9302 // and replace it with a traditional binary instruction.
9303 switch (II->getIntrinsicID()) {
9304 case Intrinsic::uadd_with_overflow:
9305 case Intrinsic::sadd_with_overflow:
9306 if (*EV.idx_begin() == 0) { // Normal result.
9307 Value *LHS = II->getOperand(1), *RHS = II->getOperand(2);
9308 II->replaceAllUsesWith(UndefValue::get(II->getType()));
9309 EraseInstFromFunction(*II);
9310 return BinaryOperator::CreateAdd(LHS, RHS);
9311 }
9312 break;
9313 case Intrinsic::usub_with_overflow:
9314 case Intrinsic::ssub_with_overflow:
9315 if (*EV.idx_begin() == 0) { // Normal result.
9316 Value *LHS = II->getOperand(1), *RHS = II->getOperand(2);
9317 II->replaceAllUsesWith(UndefValue::get(II->getType()));
9318 EraseInstFromFunction(*II);
9319 return BinaryOperator::CreateSub(LHS, RHS);
9320 }
9321 break;
9322 case Intrinsic::umul_with_overflow:
9323 case Intrinsic::smul_with_overflow:
9324 if (*EV.idx_begin() == 0) { // Normal result.
9325 Value *LHS = II->getOperand(1), *RHS = II->getOperand(2);
9326 II->replaceAllUsesWith(UndefValue::get(II->getType()));
9327 EraseInstFromFunction(*II);
9328 return BinaryOperator::CreateMul(LHS, RHS);
9329 }
9330 break;
9331 default:
9332 break;
9333 }
9334 }
9335 }
Matthijs Kooijman45e8eb42008-07-16 12:55:45 +00009336 // Can't simplify extracts from other values. Note that nested extracts are
9337 // already simplified implicitely by the above (extract ( extract (insert) )
9338 // will be translated into extract ( insert ( extract ) ) first and then just
9339 // the value inserted, if appropriate).
Matthijs Kooijmanda9ef702008-06-11 14:05:05 +00009340 return 0;
9341}
9342
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009343/// CheapToScalarize - Return true if the value is cheaper to scalarize than it
9344/// is to leave as a vector operation.
9345static bool CheapToScalarize(Value *V, bool isConstant) {
9346 if (isa<ConstantAggregateZero>(V))
9347 return true;
9348 if (ConstantVector *C = dyn_cast<ConstantVector>(V)) {
9349 if (isConstant) return true;
9350 // If all elts are the same, we can extract.
9351 Constant *Op0 = C->getOperand(0);
9352 for (unsigned i = 1; i < C->getNumOperands(); ++i)
9353 if (C->getOperand(i) != Op0)
9354 return false;
9355 return true;
9356 }
9357 Instruction *I = dyn_cast<Instruction>(V);
9358 if (!I) return false;
9359
9360 // Insert element gets simplified to the inserted element or is deleted if
9361 // this is constant idx extract element and its a constant idx insertelt.
9362 if (I->getOpcode() == Instruction::InsertElement && isConstant &&
9363 isa<ConstantInt>(I->getOperand(2)))
9364 return true;
9365 if (I->getOpcode() == Instruction::Load && I->hasOneUse())
9366 return true;
9367 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
9368 if (BO->hasOneUse() &&
9369 (CheapToScalarize(BO->getOperand(0), isConstant) ||
9370 CheapToScalarize(BO->getOperand(1), isConstant)))
9371 return true;
9372 if (CmpInst *CI = dyn_cast<CmpInst>(I))
9373 if (CI->hasOneUse() &&
9374 (CheapToScalarize(CI->getOperand(0), isConstant) ||
9375 CheapToScalarize(CI->getOperand(1), isConstant)))
9376 return true;
9377
9378 return false;
9379}
9380
9381/// Read and decode a shufflevector mask.
9382///
9383/// It turns undef elements into values that are larger than the number of
9384/// elements in the input.
9385static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
9386 unsigned NElts = SVI->getType()->getNumElements();
9387 if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
9388 return std::vector<unsigned>(NElts, 0);
9389 if (isa<UndefValue>(SVI->getOperand(2)))
9390 return std::vector<unsigned>(NElts, 2*NElts);
9391
9392 std::vector<unsigned> Result;
9393 const ConstantVector *CP = cast<ConstantVector>(SVI->getOperand(2));
Gabor Greif17396002008-06-12 21:37:33 +00009394 for (User::const_op_iterator i = CP->op_begin(), e = CP->op_end(); i!=e; ++i)
9395 if (isa<UndefValue>(*i))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009396 Result.push_back(NElts*2); // undef -> 8
9397 else
Gabor Greif17396002008-06-12 21:37:33 +00009398 Result.push_back(cast<ConstantInt>(*i)->getZExtValue());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009399 return Result;
9400}
9401
9402/// FindScalarElement - Given a vector and an element number, see if the scalar
9403/// value is already around as a register, for example if it were inserted then
9404/// extracted from the vector.
Chris Lattner03a27b42010-01-04 07:02:48 +00009405static Value *FindScalarElement(Value *V, unsigned EltNo) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009406 assert(isa<VectorType>(V->getType()) && "Not looking at a vector?");
9407 const VectorType *PTy = cast<VectorType>(V->getType());
9408 unsigned Width = PTy->getNumElements();
9409 if (EltNo >= Width) // Out of range access.
Owen Andersonb99ecca2009-07-30 23:03:37 +00009410 return UndefValue::get(PTy->getElementType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009411
9412 if (isa<UndefValue>(V))
Owen Andersonb99ecca2009-07-30 23:03:37 +00009413 return UndefValue::get(PTy->getElementType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009414 else if (isa<ConstantAggregateZero>(V))
Owen Andersonaac28372009-07-31 20:28:14 +00009415 return Constant::getNullValue(PTy->getElementType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009416 else if (ConstantVector *CP = dyn_cast<ConstantVector>(V))
9417 return CP->getOperand(EltNo);
9418 else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
9419 // If this is an insert to a variable element, we don't know what it is.
9420 if (!isa<ConstantInt>(III->getOperand(2)))
9421 return 0;
9422 unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
9423
9424 // If this is an insert to the element we are looking for, return the
9425 // inserted value.
9426 if (EltNo == IIElt)
9427 return III->getOperand(1);
9428
9429 // Otherwise, the insertelement doesn't modify the value, recurse on its
9430 // vector input.
Chris Lattner03a27b42010-01-04 07:02:48 +00009431 return FindScalarElement(III->getOperand(0), EltNo);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009432 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
Mon P Wangbff5d9c2008-11-10 04:46:22 +00009433 unsigned LHSWidth =
9434 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009435 unsigned InEl = getShuffleMask(SVI)[EltNo];
Mon P Wangbff5d9c2008-11-10 04:46:22 +00009436 if (InEl < LHSWidth)
Chris Lattner03a27b42010-01-04 07:02:48 +00009437 return FindScalarElement(SVI->getOperand(0), InEl);
Mon P Wangbff5d9c2008-11-10 04:46:22 +00009438 else if (InEl < LHSWidth*2)
Chris Lattner03a27b42010-01-04 07:02:48 +00009439 return FindScalarElement(SVI->getOperand(1), InEl - LHSWidth);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009440 else
Owen Andersonb99ecca2009-07-30 23:03:37 +00009441 return UndefValue::get(PTy->getElementType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009442 }
9443
9444 // Otherwise, we don't know.
9445 return 0;
9446}
9447
9448Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009449 // If vector val is undef, replace extract with scalar undef.
9450 if (isa<UndefValue>(EI.getOperand(0)))
Owen Andersonb99ecca2009-07-30 23:03:37 +00009451 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009452
9453 // If vector val is constant 0, replace extract with scalar 0.
9454 if (isa<ConstantAggregateZero>(EI.getOperand(0)))
Owen Andersonaac28372009-07-31 20:28:14 +00009455 return ReplaceInstUsesWith(EI, Constant::getNullValue(EI.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009456
9457 if (ConstantVector *C = dyn_cast<ConstantVector>(EI.getOperand(0))) {
Matthijs Kooijmandd3425f2008-06-11 09:00:12 +00009458 // If vector val is constant with all elements the same, replace EI with
9459 // that element. When the elements are not identical, we cannot replace yet
9460 // (we do that below, but only when the index is constant).
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009461 Constant *op0 = C->getOperand(0);
Chris Lattner1ba36b72009-09-08 03:44:51 +00009462 for (unsigned i = 1; i != C->getNumOperands(); ++i)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009463 if (C->getOperand(i) != op0) {
9464 op0 = 0;
9465 break;
9466 }
9467 if (op0)
9468 return ReplaceInstUsesWith(EI, op0);
9469 }
Eli Friedmanf34209b2009-07-18 19:04:16 +00009470
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009471 // If extracting a specified index from the vector, see if we can recursively
9472 // find a previously computed scalar that was inserted into the vector.
9473 if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
9474 unsigned IndexVal = IdxC->getZExtValue();
Chris Lattner1ba36b72009-09-08 03:44:51 +00009475 unsigned VectorWidth = EI.getVectorOperandType()->getNumElements();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009476
9477 // If this is extracting an invalid index, turn this into undef, to avoid
9478 // crashing the code below.
9479 if (IndexVal >= VectorWidth)
Owen Andersonb99ecca2009-07-30 23:03:37 +00009480 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009481
9482 // This instruction only demands the single element from the input vector.
9483 // If the input vector has a single use, simplify it based on this use
9484 // property.
Eli Friedmanf34209b2009-07-18 19:04:16 +00009485 if (EI.getOperand(0)->hasOneUse() && VectorWidth != 1) {
Evan Cheng63295ab2009-02-03 10:05:09 +00009486 APInt UndefElts(VectorWidth, 0);
9487 APInt DemandedMask(VectorWidth, 1 << IndexVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009488 if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
Evan Cheng63295ab2009-02-03 10:05:09 +00009489 DemandedMask, UndefElts)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009490 EI.setOperand(0, V);
9491 return &EI;
9492 }
9493 }
9494
Chris Lattner03a27b42010-01-04 07:02:48 +00009495 if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009496 return ReplaceInstUsesWith(EI, Elt);
9497
9498 // If the this extractelement is directly using a bitcast from a vector of
9499 // the same number of elements, see if we can find the source element from
9500 // it. In this case, we will end up needing to bitcast the scalars.
9501 if (BitCastInst *BCI = dyn_cast<BitCastInst>(EI.getOperand(0))) {
9502 if (const VectorType *VT =
9503 dyn_cast<VectorType>(BCI->getOperand(0)->getType()))
9504 if (VT->getNumElements() == VectorWidth)
Chris Lattner03a27b42010-01-04 07:02:48 +00009505 if (Value *Elt = FindScalarElement(BCI->getOperand(0), IndexVal))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009506 return new BitCastInst(Elt, EI.getType());
9507 }
9508 }
9509
9510 if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
Chris Lattnera97bc602009-09-08 18:48:01 +00009511 // Push extractelement into predecessor operation if legal and
9512 // profitable to do so
9513 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
9514 if (I->hasOneUse() &&
9515 CheapToScalarize(BO, isa<ConstantInt>(EI.getOperand(1)))) {
9516 Value *newEI0 =
9517 Builder->CreateExtractElement(BO->getOperand(0), EI.getOperand(1),
9518 EI.getName()+".lhs");
9519 Value *newEI1 =
9520 Builder->CreateExtractElement(BO->getOperand(1), EI.getOperand(1),
9521 EI.getName()+".rhs");
9522 return BinaryOperator::Create(BO->getOpcode(), newEI0, newEI1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009523 }
Chris Lattnera97bc602009-09-08 18:48:01 +00009524 } else if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009525 // Extracting the inserted element?
9526 if (IE->getOperand(2) == EI.getOperand(1))
9527 return ReplaceInstUsesWith(EI, IE->getOperand(1));
9528 // If the inserted and extracted elements are constants, they must not
9529 // be the same value, extract from the pre-inserted value instead.
Chris Lattner78628292009-08-30 19:47:22 +00009530 if (isa<Constant>(IE->getOperand(2)) && isa<Constant>(EI.getOperand(1))) {
Chris Lattnerc5ad98f2009-08-30 06:27:41 +00009531 Worklist.AddValue(EI.getOperand(0));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009532 EI.setOperand(0, IE->getOperand(0));
9533 return &EI;
9534 }
9535 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
9536 // If this is extracting an element from a shufflevector, figure out where
9537 // it came from and extract from the appropriate input element instead.
9538 if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
9539 unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
9540 Value *Src;
Mon P Wangbff5d9c2008-11-10 04:46:22 +00009541 unsigned LHSWidth =
9542 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
9543
9544 if (SrcIdx < LHSWidth)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009545 Src = SVI->getOperand(0);
Mon P Wangbff5d9c2008-11-10 04:46:22 +00009546 else if (SrcIdx < LHSWidth*2) {
9547 SrcIdx -= LHSWidth;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009548 Src = SVI->getOperand(1);
9549 } else {
Owen Andersonb99ecca2009-07-30 23:03:37 +00009550 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009551 }
Eric Christopher1ba36872009-07-25 02:28:41 +00009552 return ExtractElementInst::Create(Src,
Chris Lattner03a27b42010-01-04 07:02:48 +00009553 ConstantInt::get(Type::getInt32Ty(EI.getContext()),
9554 SrcIdx, false));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009555 }
9556 }
Eli Friedman1d31dee2009-07-18 23:06:53 +00009557 // FIXME: Canonicalize extractelement(bitcast) -> bitcast(extractelement)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009558 }
9559 return 0;
9560}
9561
9562/// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
9563/// elements from either LHS or RHS, return the shuffle mask and true.
9564/// Otherwise, return false.
9565static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
Chris Lattner03a27b42010-01-04 07:02:48 +00009566 std::vector<Constant*> &Mask) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009567 assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
9568 "Invalid CollectSingleShuffleElements");
9569 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
9570
9571 if (isa<UndefValue>(V)) {
Chris Lattner03a27b42010-01-04 07:02:48 +00009572 Mask.assign(NumElts, UndefValue::get(Type::getInt32Ty(V->getContext())));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009573 return true;
Chris Lattner03a27b42010-01-04 07:02:48 +00009574 }
9575
9576 if (V == LHS) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009577 for (unsigned i = 0; i != NumElts; ++i)
Chris Lattner03a27b42010-01-04 07:02:48 +00009578 Mask.push_back(ConstantInt::get(Type::getInt32Ty(V->getContext()), i));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009579 return true;
Chris Lattner03a27b42010-01-04 07:02:48 +00009580 }
9581
9582 if (V == RHS) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009583 for (unsigned i = 0; i != NumElts; ++i)
Chris Lattner03a27b42010-01-04 07:02:48 +00009584 Mask.push_back(ConstantInt::get(Type::getInt32Ty(V->getContext()),
9585 i+NumElts));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009586 return true;
Chris Lattner03a27b42010-01-04 07:02:48 +00009587 }
9588
9589 if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009590 // If this is an insert of an extract from some other vector, include it.
9591 Value *VecOp = IEI->getOperand(0);
9592 Value *ScalarOp = IEI->getOperand(1);
9593 Value *IdxOp = IEI->getOperand(2);
9594
9595 if (!isa<ConstantInt>(IdxOp))
9596 return false;
9597 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
9598
9599 if (isa<UndefValue>(ScalarOp)) { // inserting undef into vector.
9600 // Okay, we can handle this if the vector we are insertinting into is
9601 // transitively ok.
Chris Lattner03a27b42010-01-04 07:02:48 +00009602 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009603 // If so, update the mask to reflect the inserted undef.
Chris Lattner03a27b42010-01-04 07:02:48 +00009604 Mask[InsertedIdx] = UndefValue::get(Type::getInt32Ty(V->getContext()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009605 return true;
9606 }
9607 } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
9608 if (isa<ConstantInt>(EI->getOperand(1)) &&
9609 EI->getOperand(0)->getType() == V->getType()) {
9610 unsigned ExtractedIdx =
9611 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
9612
9613 // This must be extracting from either LHS or RHS.
9614 if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
9615 // Okay, we can handle this if the vector we are insertinting into is
9616 // transitively ok.
Chris Lattner03a27b42010-01-04 07:02:48 +00009617 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009618 // If so, update the mask to reflect the inserted value.
9619 if (EI->getOperand(0) == LHS) {
Mon P Wang6bf3c592008-08-20 02:23:25 +00009620 Mask[InsertedIdx % NumElts] =
Chris Lattner03a27b42010-01-04 07:02:48 +00009621 ConstantInt::get(Type::getInt32Ty(V->getContext()),
9622 ExtractedIdx);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009623 } else {
9624 assert(EI->getOperand(0) == RHS);
Mon P Wang6bf3c592008-08-20 02:23:25 +00009625 Mask[InsertedIdx % NumElts] =
Chris Lattner03a27b42010-01-04 07:02:48 +00009626 ConstantInt::get(Type::getInt32Ty(V->getContext()),
9627 ExtractedIdx+NumElts);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009628
9629 }
9630 return true;
9631 }
9632 }
9633 }
9634 }
9635 }
9636 // TODO: Handle shufflevector here!
9637
9638 return false;
9639}
9640
9641/// CollectShuffleElements - We are building a shuffle of V, using RHS as the
9642/// RHS of the shuffle instruction, if it is not null. Return a shuffle mask
9643/// that computes V and the LHS value of the shuffle.
9644static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
Chris Lattner03a27b42010-01-04 07:02:48 +00009645 Value *&RHS) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009646 assert(isa<VectorType>(V->getType()) &&
9647 (RHS == 0 || V->getType() == RHS->getType()) &&
9648 "Invalid shuffle!");
9649 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
9650
9651 if (isa<UndefValue>(V)) {
Chris Lattner03a27b42010-01-04 07:02:48 +00009652 Mask.assign(NumElts, UndefValue::get(Type::getInt32Ty(V->getContext())));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009653 return V;
9654 } else if (isa<ConstantAggregateZero>(V)) {
Chris Lattner03a27b42010-01-04 07:02:48 +00009655 Mask.assign(NumElts, ConstantInt::get(Type::getInt32Ty(V->getContext()),0));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009656 return V;
9657 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
9658 // If this is an insert of an extract from some other vector, include it.
9659 Value *VecOp = IEI->getOperand(0);
9660 Value *ScalarOp = IEI->getOperand(1);
9661 Value *IdxOp = IEI->getOperand(2);
9662
9663 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
9664 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
9665 EI->getOperand(0)->getType() == V->getType()) {
9666 unsigned ExtractedIdx =
9667 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
9668 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
9669
9670 // Either the extracted from or inserted into vector must be RHSVec,
9671 // otherwise we'd end up with a shuffle of three inputs.
9672 if (EI->getOperand(0) == RHS || RHS == 0) {
9673 RHS = EI->getOperand(0);
Chris Lattner03a27b42010-01-04 07:02:48 +00009674 Value *V = CollectShuffleElements(VecOp, Mask, RHS);
Mon P Wang6bf3c592008-08-20 02:23:25 +00009675 Mask[InsertedIdx % NumElts] =
Chris Lattner03a27b42010-01-04 07:02:48 +00009676 ConstantInt::get(Type::getInt32Ty(V->getContext()),
9677 NumElts+ExtractedIdx);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009678 return V;
9679 }
9680
9681 if (VecOp == RHS) {
Chris Lattner03a27b42010-01-04 07:02:48 +00009682 Value *V = CollectShuffleElements(EI->getOperand(0), Mask, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009683 // Everything but the extracted element is replaced with the RHS.
9684 for (unsigned i = 0; i != NumElts; ++i) {
9685 if (i != InsertedIdx)
Chris Lattner03a27b42010-01-04 07:02:48 +00009686 Mask[i] = ConstantInt::get(Type::getInt32Ty(V->getContext()),
9687 NumElts+i);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009688 }
9689 return V;
9690 }
9691
9692 // If this insertelement is a chain that comes from exactly these two
9693 // vectors, return the vector and the effective shuffle.
Chris Lattner03a27b42010-01-04 07:02:48 +00009694 if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009695 return EI->getOperand(0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009696 }
9697 }
9698 }
9699 // TODO: Handle shufflevector here!
9700
9701 // Otherwise, can't do anything fancy. Return an identity vector.
9702 for (unsigned i = 0; i != NumElts; ++i)
Chris Lattner03a27b42010-01-04 07:02:48 +00009703 Mask.push_back(ConstantInt::get(Type::getInt32Ty(V->getContext()), i));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009704 return V;
9705}
9706
9707Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
9708 Value *VecOp = IE.getOperand(0);
9709 Value *ScalarOp = IE.getOperand(1);
9710 Value *IdxOp = IE.getOperand(2);
9711
9712 // Inserting an undef or into an undefined place, remove this.
9713 if (isa<UndefValue>(ScalarOp) || isa<UndefValue>(IdxOp))
9714 ReplaceInstUsesWith(IE, VecOp);
Eli Friedmanf34209b2009-07-18 19:04:16 +00009715
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009716 // If the inserted element was extracted from some other vector, and if the
9717 // indexes are constant, try to turn this into a shufflevector operation.
9718 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
9719 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
9720 EI->getOperand(0)->getType() == IE.getType()) {
Eli Friedmanf34209b2009-07-18 19:04:16 +00009721 unsigned NumVectorElts = IE.getType()->getNumElements();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009722 unsigned ExtractedIdx =
9723 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
9724 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
9725
9726 if (ExtractedIdx >= NumVectorElts) // Out of range extract.
9727 return ReplaceInstUsesWith(IE, VecOp);
9728
9729 if (InsertedIdx >= NumVectorElts) // Out of range insert.
Owen Andersonb99ecca2009-07-30 23:03:37 +00009730 return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009731
9732 // If we are extracting a value from a vector, then inserting it right
9733 // back into the same place, just use the input vector.
9734 if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
9735 return ReplaceInstUsesWith(IE, VecOp);
9736
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009737 // If this insertelement isn't used by some other insertelement, turn it
9738 // (and any insertelements it points to), into one big shuffle.
9739 if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
9740 std::vector<Constant*> Mask;
9741 Value *RHS = 0;
Chris Lattner03a27b42010-01-04 07:02:48 +00009742 Value *LHS = CollectShuffleElements(&IE, Mask, RHS);
Owen Andersonb99ecca2009-07-30 23:03:37 +00009743 if (RHS == 0) RHS = UndefValue::get(LHS->getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009744 // We now have a shuffle of LHS, RHS, Mask.
Owen Anderson24be4c12009-07-03 00:17:18 +00009745 return new ShuffleVectorInst(LHS, RHS,
Owen Anderson2f422e02009-07-28 21:19:26 +00009746 ConstantVector::get(Mask));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009747 }
9748 }
9749 }
9750
Eli Friedmanbefee262009-06-06 20:08:03 +00009751 unsigned VWidth = cast<VectorType>(VecOp->getType())->getNumElements();
9752 APInt UndefElts(VWidth, 0);
9753 APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
9754 if (SimplifyDemandedVectorElts(&IE, AllOnesEltMask, UndefElts))
9755 return &IE;
9756
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009757 return 0;
9758}
9759
9760
9761Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
9762 Value *LHS = SVI.getOperand(0);
9763 Value *RHS = SVI.getOperand(1);
9764 std::vector<unsigned> Mask = getShuffleMask(&SVI);
9765
9766 bool MadeChange = false;
Mon P Wangbff5d9c2008-11-10 04:46:22 +00009767
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009768 // Undefined shuffle mask -> undefined value.
9769 if (isa<UndefValue>(SVI.getOperand(2)))
Owen Andersonb99ecca2009-07-30 23:03:37 +00009770 return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
Dan Gohmanda93bbe2008-09-09 18:11:14 +00009771
Dan Gohmanda93bbe2008-09-09 18:11:14 +00009772 unsigned VWidth = cast<VectorType>(SVI.getType())->getNumElements();
Mon P Wangbff5d9c2008-11-10 04:46:22 +00009773
9774 if (VWidth != cast<VectorType>(LHS->getType())->getNumElements())
9775 return 0;
9776
Evan Cheng63295ab2009-02-03 10:05:09 +00009777 APInt UndefElts(VWidth, 0);
9778 APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
9779 if (SimplifyDemandedVectorElts(&SVI, AllOnesEltMask, UndefElts)) {
Dan Gohman83b702d2008-09-11 22:47:57 +00009780 LHS = SVI.getOperand(0);
9781 RHS = SVI.getOperand(1);
Dan Gohmanda93bbe2008-09-09 18:11:14 +00009782 MadeChange = true;
Dan Gohman83b702d2008-09-11 22:47:57 +00009783 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009784
9785 // Canonicalize shuffle(x ,x,mask) -> shuffle(x, undef,mask')
9786 // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
9787 if (LHS == RHS || isa<UndefValue>(LHS)) {
9788 if (isa<UndefValue>(LHS) && LHS == RHS) {
9789 // shuffle(undef,undef,mask) -> undef.
9790 return ReplaceInstUsesWith(SVI, LHS);
9791 }
9792
9793 // Remap any references to RHS to use LHS.
9794 std::vector<Constant*> Elts;
9795 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
9796 if (Mask[i] >= 2*e)
Chris Lattner03a27b42010-01-04 07:02:48 +00009797 Elts.push_back(UndefValue::get(Type::getInt32Ty(SVI.getContext())));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009798 else {
9799 if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
Dan Gohmanbba96b92008-08-06 18:17:32 +00009800 (Mask[i] < e && isa<UndefValue>(LHS))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009801 Mask[i] = 2*e; // Turn into undef.
Chris Lattner03a27b42010-01-04 07:02:48 +00009802 Elts.push_back(UndefValue::get(Type::getInt32Ty(SVI.getContext())));
Dan Gohmanbba96b92008-08-06 18:17:32 +00009803 } else {
Mon P Wang6bf3c592008-08-20 02:23:25 +00009804 Mask[i] = Mask[i] % e; // Force to LHS.
Chris Lattner03a27b42010-01-04 07:02:48 +00009805 Elts.push_back(ConstantInt::get(Type::getInt32Ty(SVI.getContext()),
9806 Mask[i]));
Dan Gohmanbba96b92008-08-06 18:17:32 +00009807 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009808 }
9809 }
9810 SVI.setOperand(0, SVI.getOperand(1));
Owen Andersonb99ecca2009-07-30 23:03:37 +00009811 SVI.setOperand(1, UndefValue::get(RHS->getType()));
Owen Anderson2f422e02009-07-28 21:19:26 +00009812 SVI.setOperand(2, ConstantVector::get(Elts));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009813 LHS = SVI.getOperand(0);
9814 RHS = SVI.getOperand(1);
9815 MadeChange = true;
9816 }
9817
9818 // Analyze the shuffle, are the LHS or RHS and identity shuffles?
9819 bool isLHSID = true, isRHSID = true;
9820
9821 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
9822 if (Mask[i] >= e*2) continue; // Ignore undef values.
9823 // Is this an identity shuffle of the LHS value?
9824 isLHSID &= (Mask[i] == i);
9825
9826 // Is this an identity shuffle of the RHS value?
9827 isRHSID &= (Mask[i]-e == i);
9828 }
9829
9830 // Eliminate identity shuffles.
9831 if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
9832 if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
9833
9834 // If the LHS is a shufflevector itself, see if we can combine it with this
9835 // one without producing an unusual shuffle. Here we are really conservative:
9836 // we are absolutely afraid of producing a shuffle mask not in the input
9837 // program, because the code gen may not be smart enough to turn a merged
9838 // shuffle into two specific shuffles: it may produce worse code. As such,
9839 // we only merge two shuffles if the result is one of the two input shuffle
9840 // masks. In this case, merging the shuffles just removes one instruction,
9841 // which we know is safe. This is good for things like turning:
9842 // (splat(splat)) -> splat.
9843 if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
9844 if (isa<UndefValue>(RHS)) {
9845 std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
9846
David Greeneb736b5d2009-11-16 21:52:23 +00009847 if (LHSMask.size() == Mask.size()) {
9848 std::vector<unsigned> NewMask;
9849 for (unsigned i = 0, e = Mask.size(); i != e; ++i)
Duncan Sandse7f89b02009-11-20 13:19:51 +00009850 if (Mask[i] >= e)
David Greeneb736b5d2009-11-16 21:52:23 +00009851 NewMask.push_back(2*e);
9852 else
9853 NewMask.push_back(LHSMask[Mask[i]]);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009854
David Greeneb736b5d2009-11-16 21:52:23 +00009855 // If the result mask is equal to the src shuffle or this
9856 // shuffle mask, do the replacement.
9857 if (NewMask == LHSMask || NewMask == Mask) {
9858 unsigned LHSInNElts =
9859 cast<VectorType>(LHSSVI->getOperand(0)->getType())->
9860 getNumElements();
9861 std::vector<Constant*> Elts;
9862 for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
9863 if (NewMask[i] >= LHSInNElts*2) {
Chris Lattner03a27b42010-01-04 07:02:48 +00009864 Elts.push_back(UndefValue::get(
9865 Type::getInt32Ty(SVI.getContext())));
David Greeneb736b5d2009-11-16 21:52:23 +00009866 } else {
Chris Lattner03a27b42010-01-04 07:02:48 +00009867 Elts.push_back(ConstantInt::get(
9868 Type::getInt32Ty(SVI.getContext()),
David Greeneb736b5d2009-11-16 21:52:23 +00009869 NewMask[i]));
9870 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009871 }
David Greeneb736b5d2009-11-16 21:52:23 +00009872 return new ShuffleVectorInst(LHSSVI->getOperand(0),
9873 LHSSVI->getOperand(1),
9874 ConstantVector::get(Elts));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009875 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009876 }
9877 }
9878 }
9879
9880 return MadeChange ? &SVI : 0;
9881}
9882
9883
9884
9885
9886/// TryToSinkInstruction - Try to move the specified instruction from its
9887/// current block into the beginning of DestBlock, which can only happen if it's
9888/// safe to move the instruction past all of the instructions between it and the
9889/// end of its block.
9890static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
9891 assert(I->hasOneUse() && "Invariants didn't hold!");
9892
9893 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
Duncan Sands2f500832009-05-06 06:49:50 +00009894 if (isa<PHINode>(I) || I->mayHaveSideEffects() || isa<TerminatorInst>(I))
Chris Lattnercb19a1c2008-05-09 15:07:33 +00009895 return false;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009896
9897 // Do not sink alloca instructions out of the entry block.
9898 if (isa<AllocaInst>(I) && I->getParent() ==
9899 &DestBlock->getParent()->getEntryBlock())
9900 return false;
9901
9902 // We can only sink load instructions if there is nothing between the load and
9903 // the end of block that could change the value.
Chris Lattner0db40a62008-05-08 17:37:37 +00009904 if (I->mayReadFromMemory()) {
9905 for (BasicBlock::iterator Scan = I, E = I->getParent()->end();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009906 Scan != E; ++Scan)
9907 if (Scan->mayWriteToMemory())
9908 return false;
9909 }
9910
Dan Gohman514277c2008-05-23 21:05:58 +00009911 BasicBlock::iterator InsertPos = DestBlock->getFirstNonPHI();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009912
Dale Johannesen24339f12009-03-03 01:09:07 +00009913 CopyPrecedingStopPoint(I, InsertPos);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009914 I->moveBefore(InsertPos);
9915 ++NumSunkInst;
9916 return true;
9917}
9918
9919
9920/// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
9921/// all reachable code to the worklist.
9922///
9923/// This has a couple of tricks to make the code faster and more powerful. In
9924/// particular, we constant fold and DCE instructions as we go, to avoid adding
9925/// them to the worklist (this significantly speeds up instcombine on code where
9926/// many instructions are dead or constant). Additionally, if we find a branch
9927/// whose condition is a known constant, we only visit the reachable successors.
9928///
Chris Lattnerc4269e52009-10-15 04:59:28 +00009929static bool AddReachableCodeToWorklist(BasicBlock *BB,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009930 SmallPtrSet<BasicBlock*, 64> &Visited,
9931 InstCombiner &IC,
9932 const TargetData *TD) {
Chris Lattnerc4269e52009-10-15 04:59:28 +00009933 bool MadeIRChange = false;
Chris Lattnera06291a2008-08-15 04:03:01 +00009934 SmallVector<BasicBlock*, 256> Worklist;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009935 Worklist.push_back(BB);
Chris Lattnerb5663c72009-10-12 03:58:40 +00009936
9937 std::vector<Instruction*> InstrsForInstCombineWorklist;
9938 InstrsForInstCombineWorklist.reserve(128);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009939
Chris Lattnerc4269e52009-10-15 04:59:28 +00009940 SmallPtrSet<ConstantExpr*, 64> FoldedConstants;
9941
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009942 while (!Worklist.empty()) {
9943 BB = Worklist.back();
9944 Worklist.pop_back();
9945
9946 // We have now visited this block! If we've already been here, ignore it.
9947 if (!Visited.insert(BB)) continue;
Devang Patel794140c2008-11-19 18:56:50 +00009948
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009949 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
9950 Instruction *Inst = BBI++;
9951
9952 // DCE instruction if trivially dead.
9953 if (isInstructionTriviallyDead(Inst)) {
9954 ++NumDeadInst;
Chris Lattner8a6411c2009-08-23 04:37:46 +00009955 DEBUG(errs() << "IC: DCE: " << *Inst << '\n');
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009956 Inst->eraseFromParent();
9957 continue;
9958 }
9959
9960 // ConstantProp instruction if trivially constant.
Chris Lattneree5839b2009-10-15 04:13:44 +00009961 if (!Inst->use_empty() && isa<Constant>(Inst->getOperand(0)))
Chris Lattner6070c012009-11-06 04:27:31 +00009962 if (Constant *C = ConstantFoldInstruction(Inst, TD)) {
Chris Lattneree5839b2009-10-15 04:13:44 +00009963 DEBUG(errs() << "IC: ConstFold to: " << *C << " from: "
9964 << *Inst << '\n');
9965 Inst->replaceAllUsesWith(C);
9966 ++NumConstProp;
9967 Inst->eraseFromParent();
9968 continue;
9969 }
Chris Lattnerc4269e52009-10-15 04:59:28 +00009970
9971
9972
9973 if (TD) {
9974 // See if we can constant fold its operands.
9975 for (User::op_iterator i = Inst->op_begin(), e = Inst->op_end();
9976 i != e; ++i) {
9977 ConstantExpr *CE = dyn_cast<ConstantExpr>(i);
9978 if (CE == 0) continue;
9979
9980 // If we already folded this constant, don't try again.
9981 if (!FoldedConstants.insert(CE))
9982 continue;
9983
Chris Lattner6070c012009-11-06 04:27:31 +00009984 Constant *NewC = ConstantFoldConstantExpression(CE, TD);
Chris Lattnerc4269e52009-10-15 04:59:28 +00009985 if (NewC && NewC != CE) {
9986 *i = NewC;
9987 MadeIRChange = true;
9988 }
9989 }
9990 }
9991
Devang Patel794140c2008-11-19 18:56:50 +00009992
Chris Lattnerb5663c72009-10-12 03:58:40 +00009993 InstrsForInstCombineWorklist.push_back(Inst);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009994 }
9995
9996 // Recursively visit successors. If this is a branch or switch on a
9997 // constant, only visit the reachable successor.
9998 TerminatorInst *TI = BB->getTerminator();
9999 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
10000 if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
10001 bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
Nick Lewyckyd551cf12008-03-09 08:50:23 +000010002 BasicBlock *ReachableBB = BI->getSuccessor(!CondVal);
Nick Lewyckyd8aa33a2008-04-25 16:53:59 +000010003 Worklist.push_back(ReachableBB);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010004 continue;
10005 }
10006 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
10007 if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
10008 // See if this is an explicit destination.
10009 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
10010 if (SI->getCaseValue(i) == Cond) {
Nick Lewyckyd551cf12008-03-09 08:50:23 +000010011 BasicBlock *ReachableBB = SI->getSuccessor(i);
Nick Lewyckyd8aa33a2008-04-25 16:53:59 +000010012 Worklist.push_back(ReachableBB);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010013 continue;
10014 }
10015
10016 // Otherwise it is the default destination.
10017 Worklist.push_back(SI->getSuccessor(0));
10018 continue;
10019 }
10020 }
10021
10022 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
10023 Worklist.push_back(TI->getSuccessor(i));
10024 }
Chris Lattnerb5663c72009-10-12 03:58:40 +000010025
10026 // Once we've found all of the instructions to add to instcombine's worklist,
10027 // add them in reverse order. This way instcombine will visit from the top
10028 // of the function down. This jives well with the way that it adds all uses
10029 // of instructions to the worklist after doing a transformation, thus avoiding
10030 // some N^2 behavior in pathological cases.
10031 IC.Worklist.AddInitialGroup(&InstrsForInstCombineWorklist[0],
10032 InstrsForInstCombineWorklist.size());
Chris Lattnerc4269e52009-10-15 04:59:28 +000010033
10034 return MadeIRChange;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010035}
10036
10037bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) {
Chris Lattner21d79e22009-08-31 06:57:37 +000010038 MadeIRChange = false;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010039
Daniel Dunbar005975c2009-07-25 00:23:56 +000010040 DEBUG(errs() << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
10041 << F.getNameStr() << "\n");
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010042
10043 {
10044 // Do a depth-first traversal of the function, populate the worklist with
10045 // the reachable instructions. Ignore blocks that are not reachable. Keep
10046 // track of which blocks we visit.
10047 SmallPtrSet<BasicBlock*, 64> Visited;
Chris Lattnerc4269e52009-10-15 04:59:28 +000010048 MadeIRChange |= AddReachableCodeToWorklist(F.begin(), Visited, *this, TD);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010049
10050 // Do a quick scan over the function. If we find any blocks that are
10051 // unreachable, remove any instructions inside of them. This prevents
10052 // the instcombine code from having to deal with some bad special cases.
10053 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
10054 if (!Visited.count(BB)) {
10055 Instruction *Term = BB->getTerminator();
10056 while (Term != BB->begin()) { // Remove instrs bottom-up
10057 BasicBlock::iterator I = Term; --I;
10058
Chris Lattner8a6411c2009-08-23 04:37:46 +000010059 DEBUG(errs() << "IC: DCE: " << *I << '\n');
Dale Johannesendf356c62009-03-10 21:19:49 +000010060 // A debug intrinsic shouldn't force another iteration if we weren't
10061 // going to do one without it.
10062 if (!isa<DbgInfoIntrinsic>(I)) {
10063 ++NumDeadInst;
Chris Lattner21d79e22009-08-31 06:57:37 +000010064 MadeIRChange = true;
Dale Johannesendf356c62009-03-10 21:19:49 +000010065 }
Devang Patele3829c82009-10-13 22:56:32 +000010066
Devang Patele3829c82009-10-13 22:56:32 +000010067 // If I is not void type then replaceAllUsesWith undef.
10068 // This allows ValueHandlers and custom metadata to adjust itself.
Devang Patele9d08b82009-10-14 17:29:00 +000010069 if (!I->getType()->isVoidTy())
Devang Patele3829c82009-10-13 22:56:32 +000010070 I->replaceAllUsesWith(UndefValue::get(I->getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010071 I->eraseFromParent();
10072 }
10073 }
10074 }
10075
Chris Lattner5119c702009-08-30 05:55:36 +000010076 while (!Worklist.isEmpty()) {
10077 Instruction *I = Worklist.RemoveOne();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010078 if (I == 0) continue; // skip null values.
10079
10080 // Check to see if we can DCE the instruction.
10081 if (isInstructionTriviallyDead(I)) {
Chris Lattner8a6411c2009-08-23 04:37:46 +000010082 DEBUG(errs() << "IC: DCE: " << *I << '\n');
Chris Lattner3183fb62009-08-30 06:13:40 +000010083 EraseInstFromFunction(*I);
10084 ++NumDeadInst;
Chris Lattner21d79e22009-08-31 06:57:37 +000010085 MadeIRChange = true;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010086 continue;
10087 }
10088
10089 // Instruction isn't dead, see if we can constant propagate it.
Chris Lattneree5839b2009-10-15 04:13:44 +000010090 if (!I->use_empty() && isa<Constant>(I->getOperand(0)))
Chris Lattner6070c012009-11-06 04:27:31 +000010091 if (Constant *C = ConstantFoldInstruction(I, TD)) {
Chris Lattneree5839b2009-10-15 04:13:44 +000010092 DEBUG(errs() << "IC: ConstFold to: " << *C << " from: " << *I << '\n');
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010093
Chris Lattneree5839b2009-10-15 04:13:44 +000010094 // Add operands to the worklist.
10095 ReplaceInstUsesWith(*I, C);
10096 ++NumConstProp;
10097 EraseInstFromFunction(*I);
10098 MadeIRChange = true;
10099 continue;
10100 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010101
10102 // See if we can trivially sink this instruction to a successor basic block.
Dan Gohman29474e92008-07-23 00:34:11 +000010103 if (I->hasOneUse()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010104 BasicBlock *BB = I->getParent();
Chris Lattnerf27a0432009-10-14 15:21:58 +000010105 Instruction *UserInst = cast<Instruction>(I->use_back());
10106 BasicBlock *UserParent;
10107
10108 // Get the block the use occurs in.
10109 if (PHINode *PN = dyn_cast<PHINode>(UserInst))
10110 UserParent = PN->getIncomingBlock(I->use_begin().getUse());
10111 else
10112 UserParent = UserInst->getParent();
10113
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010114 if (UserParent != BB) {
10115 bool UserIsSuccessor = false;
10116 // See if the user is one of our successors.
10117 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
10118 if (*SI == UserParent) {
10119 UserIsSuccessor = true;
10120 break;
10121 }
10122
10123 // If the user is one of our immediate successors, and if that successor
10124 // only has us as a predecessors (we'd have to split the critical edge
10125 // otherwise), we can keep going.
Chris Lattnerf27a0432009-10-14 15:21:58 +000010126 if (UserIsSuccessor && UserParent->getSinglePredecessor())
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010127 // Okay, the CFG is simple enough, try to sink this instruction.
Chris Lattner21d79e22009-08-31 06:57:37 +000010128 MadeIRChange |= TryToSinkInstruction(I, UserParent);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010129 }
10130 }
10131
Chris Lattnerc7694852009-08-30 07:44:24 +000010132 // Now that we have an instruction, try combining it to simplify it.
10133 Builder->SetInsertPoint(I->getParent(), I);
10134
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010135#ifndef NDEBUG
10136 std::string OrigI;
10137#endif
Chris Lattner8a6411c2009-08-23 04:37:46 +000010138 DEBUG(raw_string_ostream SS(OrigI); I->print(SS); OrigI = SS.str(););
Jeffrey Yasskin17091f02009-10-08 00:12:24 +000010139 DEBUG(errs() << "IC: Visiting: " << OrigI << '\n');
10140
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010141 if (Instruction *Result = visit(*I)) {
10142 ++NumCombined;
10143 // Should we replace the old instruction with a new one?
10144 if (Result != I) {
Chris Lattner8a6411c2009-08-23 04:37:46 +000010145 DEBUG(errs() << "IC: Old = " << *I << '\n'
10146 << " New = " << *Result << '\n');
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010147
10148 // Everything uses the new instruction now.
10149 I->replaceAllUsesWith(Result);
10150
10151 // Push the new instruction and any users onto the worklist.
Chris Lattner3183fb62009-08-30 06:13:40 +000010152 Worklist.Add(Result);
Chris Lattner4796b622009-08-30 06:22:51 +000010153 Worklist.AddUsersToWorkList(*Result);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010154
10155 // Move the name to the new instruction first.
10156 Result->takeName(I);
10157
10158 // Insert the new instruction into the basic block...
10159 BasicBlock *InstParent = I->getParent();
10160 BasicBlock::iterator InsertPos = I;
10161
10162 if (!isa<PHINode>(Result)) // If combining a PHI, don't insert
10163 while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
10164 ++InsertPos;
10165
10166 InstParent->getInstList().insert(InsertPos, Result);
10167
Chris Lattner3183fb62009-08-30 06:13:40 +000010168 EraseInstFromFunction(*I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010169 } else {
10170#ifndef NDEBUG
Chris Lattner8a6411c2009-08-23 04:37:46 +000010171 DEBUG(errs() << "IC: Mod = " << OrigI << '\n'
10172 << " New = " << *I << '\n');
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010173#endif
10174
10175 // If the instruction was modified, it's possible that it is now dead.
10176 // if so, remove it.
10177 if (isInstructionTriviallyDead(I)) {
Chris Lattner3183fb62009-08-30 06:13:40 +000010178 EraseInstFromFunction(*I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010179 } else {
Chris Lattner3183fb62009-08-30 06:13:40 +000010180 Worklist.Add(I);
Chris Lattner4796b622009-08-30 06:22:51 +000010181 Worklist.AddUsersToWorkList(*I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010182 }
10183 }
Chris Lattner21d79e22009-08-31 06:57:37 +000010184 MadeIRChange = true;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010185 }
10186 }
10187
Chris Lattner5119c702009-08-30 05:55:36 +000010188 Worklist.Zap();
Chris Lattner21d79e22009-08-31 06:57:37 +000010189 return MadeIRChange;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010190}
10191
10192
10193bool InstCombiner::runOnFunction(Function &F) {
10194 MustPreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
Chris Lattneree5839b2009-10-15 04:13:44 +000010195 TD = getAnalysisIfAvailable<TargetData>();
10196
Chris Lattnerc7694852009-08-30 07:44:24 +000010197
10198 /// Builder - This is an IRBuilder that automatically inserts new
10199 /// instructions into the worklist when they are created.
Chris Lattneree5839b2009-10-15 04:13:44 +000010200 IRBuilder<true, TargetFolder, InstCombineIRInserter>
Chris Lattner002e65d2009-11-06 05:59:53 +000010201 TheBuilder(F.getContext(), TargetFolder(TD),
Chris Lattnerc7694852009-08-30 07:44:24 +000010202 InstCombineIRInserter(Worklist));
10203 Builder = &TheBuilder;
10204
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010205 bool EverMadeChange = false;
10206
10207 // Iterate while there is work to do.
10208 unsigned Iteration = 0;
Bill Wendlingd9644a42008-05-14 22:45:20 +000010209 while (DoOneIteration(F, Iteration++))
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010210 EverMadeChange = true;
Chris Lattnerc7694852009-08-30 07:44:24 +000010211
10212 Builder = 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010213 return EverMadeChange;
10214}
10215
10216FunctionPass *llvm::createInstructionCombiningPass() {
10217 return new InstCombiner();
10218}