blob: e99000125cc4d1059047596f3e90ab910eec47fb [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");
Dan Gohmanf17a25c2007-07-18 16:29:46 +000067STATISTIC(NumSunkInst , "Number of instructions sunk");
68
Dan Gohmanf17a25c2007-07-18 16:29:46 +000069
Dan Gohman089efff2008-05-13 00:00:25 +000070char InstCombiner::ID = 0;
71static RegisterPass<InstCombiner>
72X("instcombine", "Combine redundant instructions");
73
Chris Lattnerc1cea3f2010-01-04 07:17:19 +000074void InstCombiner::getAnalysisUsage(AnalysisUsage &AU) const {
75 AU.addPreservedID(LCSSAID);
76 AU.setPreservesCFG();
77}
78
79
Dan Gohmanf17a25c2007-07-18 16:29:46 +000080// isOnlyUse - Return true if this instruction will be deleted if we stop using
81// it.
82static bool isOnlyUse(Value *V) {
83 return V->hasOneUse() || isa<Constant>(V);
84}
85
86// getPromotedType - Return the specified type promoted as it would be to pass
87// though a va_arg area...
88static const Type *getPromotedType(const Type *Ty) {
89 if (const IntegerType* ITy = dyn_cast<IntegerType>(Ty)) {
90 if (ITy->getBitWidth() < 32)
Owen Anderson35b47072009-08-13 21:58:54 +000091 return Type::getInt32Ty(Ty->getContext());
Dan Gohmanf17a25c2007-07-18 16:29:46 +000092 }
93 return Ty;
94}
95
Chris Lattnerd0011092009-11-10 07:23:37 +000096/// ShouldChangeType - Return true if it is desirable to convert a computation
97/// from 'From' to 'To'. We don't want to convert from a legal to an illegal
98/// type for example, or from a smaller to a larger illegal type.
Chris Lattner54826cd2010-01-04 07:53:58 +000099bool InstCombiner::ShouldChangeType(const Type *From, const Type *To) const {
Chris Lattnerd0011092009-11-10 07:23:37 +0000100 assert(isa<IntegerType>(From) && isa<IntegerType>(To));
101
102 // If we don't have TD, we don't know if the source/dest are legal.
103 if (!TD) return false;
104
105 unsigned FromWidth = From->getPrimitiveSizeInBits();
106 unsigned ToWidth = To->getPrimitiveSizeInBits();
107 bool FromLegal = TD->isLegalInteger(FromWidth);
108 bool ToLegal = TD->isLegalInteger(ToWidth);
109
110 // If this is a legal integer from type, and the result would be an illegal
111 // type, don't do the transformation.
112 if (FromLegal && !ToLegal)
113 return false;
114
115 // Otherwise, if both are illegal, do not increase the size of the result. We
116 // do allow things like i160 -> i64, but not i64 -> i160.
117 if (!FromLegal && !ToLegal && ToWidth > FromWidth)
118 return false;
119
120 return true;
121}
122
Matthijs Kooijman5e2a3182008-10-13 15:17:01 +0000123/// getBitCastOperand - If the specified operand is a CastInst, a constant
124/// expression bitcast, or a GetElementPtrInst with all zero indices, return the
125/// operand value, otherwise return null.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000126static Value *getBitCastOperand(Value *V) {
Dan Gohmanae402b02009-07-17 23:55:56 +0000127 if (Operator *O = dyn_cast<Operator>(V)) {
128 if (O->getOpcode() == Instruction::BitCast)
129 return O->getOperand(0);
130 if (GEPOperator *GEP = dyn_cast<GEPOperator>(V))
131 if (GEP->hasAllZeroIndices())
132 return GEP->getPointerOperand();
Matthijs Kooijman5e2a3182008-10-13 15:17:01 +0000133 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000134 return 0;
135}
136
Dan Gohmana80e2712009-07-21 23:21:54 +0000137
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000138
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000139// SimplifyCommutative - This performs a few simplifications for commutative
140// operators:
141//
142// 1. Order operands such that they are listed from right (least complex) to
143// left (most complex). This puts constants before unary operators before
144// binary operators.
145//
146// 2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
147// 3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
148//
149bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
150 bool Changed = false;
Dan Gohman5d138f92009-08-29 23:39:38 +0000151 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000152 Changed = !I.swapOperands();
153
154 if (!I.isAssociative()) return Changed;
155 Instruction::BinaryOps Opcode = I.getOpcode();
156 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
157 if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
158 if (isa<Constant>(I.getOperand(1))) {
Owen Anderson02b48c32009-07-29 18:55:55 +0000159 Constant *Folded = ConstantExpr::get(I.getOpcode(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000160 cast<Constant>(I.getOperand(1)),
161 cast<Constant>(Op->getOperand(1)));
162 I.setOperand(0, Op->getOperand(0));
163 I.setOperand(1, Folded);
164 return true;
165 } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
166 if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
167 isOnlyUse(Op) && isOnlyUse(Op1)) {
168 Constant *C1 = cast<Constant>(Op->getOperand(1));
169 Constant *C2 = cast<Constant>(Op1->getOperand(1));
170
171 // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Owen Anderson02b48c32009-07-29 18:55:55 +0000172 Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
Gabor Greifa645dd32008-05-16 19:29:10 +0000173 Instruction *New = BinaryOperator::Create(Opcode, Op->getOperand(0),
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000174 Op1->getOperand(0),
175 Op1->getName(), &I);
Chris Lattner3183fb62009-08-30 06:13:40 +0000176 Worklist.Add(New);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000177 I.setOperand(0, New);
178 I.setOperand(1, Folded);
179 return true;
180 }
181 }
182 return Changed;
183}
184
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000185// dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
186// if the LHS is a constant zero (which is the 'negate' form).
187//
Chris Lattner63ac8422010-01-04 07:37:31 +0000188Value *InstCombiner::dyn_castNegVal(Value *V) const {
Owen Anderson76f49252009-07-13 22:18:28 +0000189 if (BinaryOperator::isNeg(V))
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000190 return BinaryOperator::getNegArgument(V);
191
192 // Constants can be considered to be negated values if they can be folded.
193 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
Owen Anderson02b48c32009-07-29 18:55:55 +0000194 return ConstantExpr::getNeg(C);
Nick Lewycky58867bc2008-05-23 04:54:45 +0000195
196 if (ConstantVector *C = dyn_cast<ConstantVector>(V))
197 if (C->getType()->getElementType()->isInteger())
Owen Anderson02b48c32009-07-29 18:55:55 +0000198 return ConstantExpr::getNeg(C);
Nick Lewycky58867bc2008-05-23 04:54:45 +0000199
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000200 return 0;
201}
202
Dan Gohman7ce405e2009-06-04 22:49:04 +0000203// dyn_castFNegVal - Given a 'fsub' instruction, return the RHS of the
204// instruction if the LHS is a constant negative zero (which is the 'negate'
205// form).
206//
Dan Gohmanfe91cd62009-08-12 16:04:34 +0000207static inline Value *dyn_castFNegVal(Value *V) {
Owen Anderson76f49252009-07-13 22:18:28 +0000208 if (BinaryOperator::isFNeg(V))
Dan Gohman7ce405e2009-06-04 22:49:04 +0000209 return BinaryOperator::getFNegArgument(V);
210
211 // Constants can be considered to be negated values if they can be folded.
212 if (ConstantFP *C = dyn_cast<ConstantFP>(V))
Owen Anderson02b48c32009-07-29 18:55:55 +0000213 return ConstantExpr::getFNeg(C);
Dan Gohman7ce405e2009-06-04 22:49:04 +0000214
215 if (ConstantVector *C = dyn_cast<ConstantVector>(V))
216 if (C->getType()->getElementType()->isFloatingPoint())
Owen Anderson02b48c32009-07-29 18:55:55 +0000217 return ConstantExpr::getFNeg(C);
Dan Gohman7ce405e2009-06-04 22:49:04 +0000218
219 return 0;
220}
221
Chris Lattner6e060db2009-10-26 15:40:07 +0000222/// isFreeToInvert - Return true if the specified value is free to invert (apply
223/// ~ to). This happens in cases where the ~ can be eliminated.
224static inline bool isFreeToInvert(Value *V) {
225 // ~(~(X)) -> X.
Evan Cheng5d4a07e2009-10-26 03:51:32 +0000226 if (BinaryOperator::isNot(V))
Chris Lattner6e060db2009-10-26 15:40:07 +0000227 return true;
228
229 // Constants can be considered to be not'ed values.
230 if (isa<ConstantInt>(V))
231 return true;
232
233 // Compares can be inverted if they have a single use.
234 if (CmpInst *CI = dyn_cast<CmpInst>(V))
235 return CI->hasOneUse();
236
237 return false;
238}
239
240static inline Value *dyn_castNotVal(Value *V) {
241 // If this is not(not(x)) don't return that this is a not: we want the two
242 // not's to be folded first.
243 if (BinaryOperator::isNot(V)) {
244 Value *Operand = BinaryOperator::getNotArgument(V);
245 if (!isFreeToInvert(Operand))
246 return Operand;
247 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000248
249 // Constants can be considered to be not'ed values...
250 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
Dan Gohmanfe91cd62009-08-12 16:04:34 +0000251 return ConstantInt::get(C->getType(), ~C->getValue());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000252 return 0;
253}
254
Chris Lattner6e060db2009-10-26 15:40:07 +0000255
256
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000257// dyn_castFoldableMul - If this value is a multiply that can be folded into
258// other computations (because it has a constant operand), return the
259// non-constant operand of the multiply, and set CST to point to the multiplier.
260// Otherwise, return null.
261//
Dan Gohmanfe91cd62009-08-12 16:04:34 +0000262static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000263 if (V->hasOneUse() && V->getType()->isInteger())
264 if (Instruction *I = dyn_cast<Instruction>(V)) {
265 if (I->getOpcode() == Instruction::Mul)
266 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
267 return I->getOperand(0);
268 if (I->getOpcode() == Instruction::Shl)
269 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
270 // The multiplier is really 1 << CST.
271 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
272 uint32_t CSTVal = CST->getLimitedValue(BitWidth);
Dan Gohmanfe91cd62009-08-12 16:04:34 +0000273 CST = ConstantInt::get(V->getType()->getContext(),
274 APInt(BitWidth, 1).shl(CSTVal));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000275 return I->getOperand(0);
276 }
277 }
278 return 0;
279}
280
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000281/// AddOne - Add one to a ConstantInt
Dan Gohmanfe91cd62009-08-12 16:04:34 +0000282static Constant *AddOne(Constant *C) {
Chris Lattner63ac8422010-01-04 07:37:31 +0000283 return ConstantExpr::getAdd(C, ConstantInt::get(C->getType(), 1));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000284}
285/// SubOne - Subtract one from a ConstantInt
Dan Gohmanfe91cd62009-08-12 16:04:34 +0000286static Constant *SubOne(ConstantInt *C) {
Chris Lattner63ac8422010-01-04 07:37:31 +0000287 return ConstantExpr::getSub(C, ConstantInt::get(C->getType(), 1));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000288}
Nick Lewycky9d798f92008-02-18 22:48:05 +0000289/// MultiplyOverflows - True if the multiply can not be expressed in an int
290/// this size.
Dan Gohmanfe91cd62009-08-12 16:04:34 +0000291static bool MultiplyOverflows(ConstantInt *C1, ConstantInt *C2, bool sign) {
Nick Lewycky9d798f92008-02-18 22:48:05 +0000292 uint32_t W = C1->getBitWidth();
293 APInt LHSExt = C1->getValue(), RHSExt = C2->getValue();
294 if (sign) {
295 LHSExt.sext(W * 2);
296 RHSExt.sext(W * 2);
297 } else {
298 LHSExt.zext(W * 2);
299 RHSExt.zext(W * 2);
300 }
301
302 APInt MulExt = LHSExt * RHSExt;
303
Chris Lattner78500cb2009-12-21 06:03:05 +0000304 if (!sign)
Nick Lewycky9d798f92008-02-18 22:48:05 +0000305 return MulExt.ugt(APInt::getLowBitsSet(W * 2, W));
Chris Lattner78500cb2009-12-21 06:03:05 +0000306
307 APInt Min = APInt::getSignedMinValue(W).sext(W * 2);
308 APInt Max = APInt::getSignedMaxValue(W).sext(W * 2);
309 return MulExt.slt(Min) || MulExt.sgt(Max);
Nick Lewycky9d798f92008-02-18 22:48:05 +0000310}
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000311
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000312
Dan Gohman5d56fd42008-05-19 22:14:15 +0000313
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000314/// AssociativeOpt - Perform an optimization on an associative operator. This
315/// function is designed to check a chain of associative operators for a
316/// potential to apply a certain optimization. Since the optimization may be
317/// applicable if the expression was reassociated, this checks the chain, then
318/// reassociates the expression as necessary to expose the optimization
319/// opportunity. This makes use of a special Functor, which must define
320/// 'shouldApply' and 'apply' methods.
321///
322template<typename Functor>
Dan Gohmanfe91cd62009-08-12 16:04:34 +0000323static Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000324 unsigned Opcode = Root.getOpcode();
325 Value *LHS = Root.getOperand(0);
326
327 // Quick check, see if the immediate LHS matches...
328 if (F.shouldApply(LHS))
329 return F.apply(Root);
330
331 // Otherwise, if the LHS is not of the same opcode as the root, return.
332 Instruction *LHSI = dyn_cast<Instruction>(LHS);
333 while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
334 // Should we apply this transform to the RHS?
335 bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
336
337 // If not to the RHS, check to see if we should apply to the LHS...
338 if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
339 cast<BinaryOperator>(LHSI)->swapOperands(); // Make the LHS the RHS
340 ShouldApply = true;
341 }
342
343 // If the functor wants to apply the optimization to the RHS of LHSI,
344 // reassociate the expression from ((? op A) op B) to (? op (A op B))
345 if (ShouldApply) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000346 // Now all of the instructions are in the current basic block, go ahead
347 // and perform the reassociation.
348 Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
349
350 // First move the selected RHS to the LHS of the root...
351 Root.setOperand(0, LHSI->getOperand(1));
352
353 // Make what used to be the LHS of the root be the user of the root...
354 Value *ExtraOperand = TmpLHSI->getOperand(1);
355 if (&Root == TmpLHSI) {
Owen Andersonaac28372009-07-31 20:28:14 +0000356 Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000357 return 0;
358 }
359 Root.replaceAllUsesWith(TmpLHSI); // Users now use TmpLHSI
360 TmpLHSI->setOperand(1, &Root); // TmpLHSI now uses the root
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000361 BasicBlock::iterator ARI = &Root; ++ARI;
Dan Gohman0bb9a3d2008-06-19 17:47:47 +0000362 TmpLHSI->moveBefore(ARI); // Move TmpLHSI to after Root
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000363 ARI = Root;
364
365 // Now propagate the ExtraOperand down the chain of instructions until we
366 // get to LHSI.
367 while (TmpLHSI != LHSI) {
368 Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
369 // Move the instruction to immediately before the chain we are
370 // constructing to avoid breaking dominance properties.
Dan Gohman0bb9a3d2008-06-19 17:47:47 +0000371 NextLHSI->moveBefore(ARI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000372 ARI = NextLHSI;
373
374 Value *NextOp = NextLHSI->getOperand(1);
375 NextLHSI->setOperand(1, ExtraOperand);
376 TmpLHSI = NextLHSI;
377 ExtraOperand = NextOp;
378 }
379
380 // Now that the instructions are reassociated, have the functor perform
381 // the transformation...
382 return F.apply(Root);
383 }
384
385 LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
386 }
387 return 0;
388}
389
Dan Gohman089efff2008-05-13 00:00:25 +0000390namespace {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000391
Nick Lewycky27f6c132008-05-23 04:34:58 +0000392// AddRHS - Implements: X + X --> X << 1
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000393struct AddRHS {
394 Value *RHS;
Dan Gohmancdff2122009-08-12 16:23:25 +0000395 explicit AddRHS(Value *rhs) : RHS(rhs) {}
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000396 bool shouldApply(Value *LHS) const { return LHS == RHS; }
397 Instruction *apply(BinaryOperator &Add) const {
Nick Lewycky27f6c132008-05-23 04:34:58 +0000398 return BinaryOperator::CreateShl(Add.getOperand(0),
Owen Andersoneacb44d2009-07-24 23:12:02 +0000399 ConstantInt::get(Add.getType(), 1));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000400 }
401};
402
403// AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
404// iff C1&C2 == 0
405struct AddMaskingAnd {
406 Constant *C2;
Dan Gohmancdff2122009-08-12 16:23:25 +0000407 explicit AddMaskingAnd(Constant *c) : C2(c) {}
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000408 bool shouldApply(Value *LHS) const {
409 ConstantInt *C1;
Dan Gohmancdff2122009-08-12 16:23:25 +0000410 return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
Owen Anderson02b48c32009-07-29 18:55:55 +0000411 ConstantExpr::getAnd(C1, C2)->isNullValue();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000412 }
413 Instruction *apply(BinaryOperator &Add) const {
Gabor Greifa645dd32008-05-16 19:29:10 +0000414 return BinaryOperator::CreateOr(Add.getOperand(0), Add.getOperand(1));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000415 }
416};
417
Dan Gohman089efff2008-05-13 00:00:25 +0000418}
419
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000420static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
421 InstCombiner *IC) {
Chris Lattner78628292009-08-30 19:47:22 +0000422 if (CastInst *CI = dyn_cast<CastInst>(&I))
Chris Lattnerd6164c22009-08-30 20:01:10 +0000423 return IC->Builder->CreateCast(CI->getOpcode(), SO, I.getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000424
425 // Figure out if the constant is the left or the right argument.
426 bool ConstIsRHS = isa<Constant>(I.getOperand(1));
427 Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
428
429 if (Constant *SOC = dyn_cast<Constant>(SO)) {
430 if (ConstIsRHS)
Owen Anderson02b48c32009-07-29 18:55:55 +0000431 return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
432 return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000433 }
434
435 Value *Op0 = SO, *Op1 = ConstOperand;
436 if (!ConstIsRHS)
437 std::swap(Op0, Op1);
Chris Lattnerc7694852009-08-30 07:44:24 +0000438
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000439 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
Chris Lattnerc7694852009-08-30 07:44:24 +0000440 return IC->Builder->CreateBinOp(BO->getOpcode(), Op0, Op1,
441 SO->getName()+".op");
442 if (ICmpInst *CI = dyn_cast<ICmpInst>(&I))
443 return IC->Builder->CreateICmp(CI->getPredicate(), Op0, Op1,
444 SO->getName()+".cmp");
445 if (FCmpInst *CI = dyn_cast<FCmpInst>(&I))
446 return IC->Builder->CreateICmp(CI->getPredicate(), Op0, Op1,
447 SO->getName()+".cmp");
448 llvm_unreachable("Unknown binary instruction type!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000449}
450
451// FoldOpIntoSelect - Given an instruction with a select as one operand and a
452// constant as the other operand, try to fold the binary operator into the
453// select arguments. This also works for Cast instructions, which obviously do
454// not have a second operand.
Chris Lattner54826cd2010-01-04 07:53:58 +0000455Instruction *InstCombiner::FoldOpIntoSelect(Instruction &Op, SelectInst *SI) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000456 // Don't modify shared select instructions
457 if (!SI->hasOneUse()) return 0;
458 Value *TV = SI->getOperand(1);
459 Value *FV = SI->getOperand(2);
460
461 if (isa<Constant>(TV) || isa<Constant>(FV)) {
462 // Bool selects with constant operands can be folded to logical ops.
Chris Lattner03a27b42010-01-04 07:02:48 +0000463 if (SI->getType() == Type::getInt1Ty(SI->getContext())) return 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000464
Chris Lattner54826cd2010-01-04 07:53:58 +0000465 Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, this);
466 Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, this);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000467
Gabor Greifd6da1d02008-04-06 20:25:17 +0000468 return SelectInst::Create(SI->getCondition(), SelectTrueVal,
469 SelectFalseVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000470 }
471 return 0;
472}
473
474
Chris Lattnerf7843b72009-09-27 19:57:57 +0000475/// FoldOpIntoPhi - Given a binary operator, cast instruction, or select which
476/// has a PHI node as operand #0, see if we can fold the instruction into the
477/// PHI (which is only possible if all operands to the PHI are constants).
Chris Lattner9b61abd2009-09-27 20:46:36 +0000478///
479/// If AllowAggressive is true, FoldOpIntoPhi will allow certain transforms
480/// that would normally be unprofitable because they strongly encourage jump
481/// threading.
482Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I,
483 bool AllowAggressive) {
484 AllowAggressive = false;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000485 PHINode *PN = cast<PHINode>(I.getOperand(0));
486 unsigned NumPHIValues = PN->getNumIncomingValues();
Chris Lattner9b61abd2009-09-27 20:46:36 +0000487 if (NumPHIValues == 0 ||
488 // We normally only transform phis with a single use, unless we're trying
489 // hard to make jump threading happen.
490 (!PN->hasOneUse() && !AllowAggressive))
491 return 0;
492
493
Chris Lattnerf7843b72009-09-27 19:57:57 +0000494 // Check to see if all of the operands of the PHI are simple constants
495 // (constantint/constantfp/undef). If there is one non-constant value,
Chris Lattnerff5cd9d2009-09-27 20:18:49 +0000496 // remember the BB it is in. If there is more than one or if *it* is a PHI,
497 // bail out. We don't do arbitrary constant expressions here because moving
498 // their computation can be expensive without a cost model.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000499 BasicBlock *NonConstBB = 0;
500 for (unsigned i = 0; i != NumPHIValues; ++i)
Chris Lattnerf7843b72009-09-27 19:57:57 +0000501 if (!isa<Constant>(PN->getIncomingValue(i)) ||
502 isa<ConstantExpr>(PN->getIncomingValue(i))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000503 if (NonConstBB) return 0; // More than one non-const value.
504 if (isa<PHINode>(PN->getIncomingValue(i))) return 0; // Itself a phi.
505 NonConstBB = PN->getIncomingBlock(i);
506
507 // If the incoming non-constant value is in I's block, we have an infinite
508 // loop.
509 if (NonConstBB == I.getParent())
510 return 0;
511 }
512
513 // If there is exactly one non-constant value, we can insert a copy of the
514 // operation in that block. However, if this is a critical edge, we would be
515 // inserting the computation one some other paths (e.g. inside a loop). Only
516 // do this if the pred block is unconditionally branching into the phi block.
Chris Lattner9b61abd2009-09-27 20:46:36 +0000517 if (NonConstBB != 0 && !AllowAggressive) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000518 BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
519 if (!BI || !BI->isUnconditional()) return 0;
520 }
521
522 // Okay, we can do the transformation: create the new PHI node.
Gabor Greifd6da1d02008-04-06 20:25:17 +0000523 PHINode *NewPN = PHINode::Create(I.getType(), "");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000524 NewPN->reserveOperandSpace(PN->getNumOperands()/2);
Chris Lattner3980f9b2009-10-21 23:41:58 +0000525 InsertNewInstBefore(NewPN, *PN);
526 NewPN->takeName(PN);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000527
528 // Next, add all of the operands to the PHI.
Chris Lattnerf7843b72009-09-27 19:57:57 +0000529 if (SelectInst *SI = dyn_cast<SelectInst>(&I)) {
530 // We only currently try to fold the condition of a select when it is a phi,
531 // not the true/false values.
Chris Lattnerff5cd9d2009-09-27 20:18:49 +0000532 Value *TrueV = SI->getTrueValue();
533 Value *FalseV = SI->getFalseValue();
Chris Lattnerda3ee9c2009-09-28 06:49:44 +0000534 BasicBlock *PhiTransBB = PN->getParent();
Chris Lattnerf7843b72009-09-27 19:57:57 +0000535 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattnerff5cd9d2009-09-27 20:18:49 +0000536 BasicBlock *ThisBB = PN->getIncomingBlock(i);
Chris Lattnerda3ee9c2009-09-28 06:49:44 +0000537 Value *TrueVInPred = TrueV->DoPHITranslation(PhiTransBB, ThisBB);
538 Value *FalseVInPred = FalseV->DoPHITranslation(PhiTransBB, ThisBB);
Chris Lattnerf7843b72009-09-27 19:57:57 +0000539 Value *InV = 0;
540 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Chris Lattnerff5cd9d2009-09-27 20:18:49 +0000541 InV = InC->isNullValue() ? FalseVInPred : TrueVInPred;
Chris Lattnerf7843b72009-09-27 19:57:57 +0000542 } else {
543 assert(PN->getIncomingBlock(i) == NonConstBB);
Chris Lattnerff5cd9d2009-09-27 20:18:49 +0000544 InV = SelectInst::Create(PN->getIncomingValue(i), TrueVInPred,
545 FalseVInPred,
Chris Lattnerf7843b72009-09-27 19:57:57 +0000546 "phitmp", NonConstBB->getTerminator());
Chris Lattner3980f9b2009-10-21 23:41:58 +0000547 Worklist.Add(cast<Instruction>(InV));
Chris Lattnerf7843b72009-09-27 19:57:57 +0000548 }
Chris Lattnerff5cd9d2009-09-27 20:18:49 +0000549 NewPN->addIncoming(InV, ThisBB);
Chris Lattnerf7843b72009-09-27 19:57:57 +0000550 }
551 } else if (I.getNumOperands() == 2) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000552 Constant *C = cast<Constant>(I.getOperand(1));
553 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattnerb933ea62007-08-05 08:47:58 +0000554 Value *InV = 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000555 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
556 if (CmpInst *CI = dyn_cast<CmpInst>(&I))
Owen Anderson02b48c32009-07-29 18:55:55 +0000557 InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000558 else
Owen Anderson02b48c32009-07-29 18:55:55 +0000559 InV = ConstantExpr::get(I.getOpcode(), InC, C);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000560 } else {
561 assert(PN->getIncomingBlock(i) == NonConstBB);
562 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
Gabor Greifa645dd32008-05-16 19:29:10 +0000563 InV = BinaryOperator::Create(BO->getOpcode(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000564 PN->getIncomingValue(i), C, "phitmp",
565 NonConstBB->getTerminator());
566 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
Dan Gohmane6803b82009-08-25 23:17:54 +0000567 InV = CmpInst::Create(CI->getOpcode(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000568 CI->getPredicate(),
569 PN->getIncomingValue(i), C, "phitmp",
570 NonConstBB->getTerminator());
571 else
Edwin Törökbd448e32009-07-14 16:55:14 +0000572 llvm_unreachable("Unknown binop!");
Chris Lattner3980f9b2009-10-21 23:41:58 +0000573
574 Worklist.Add(cast<Instruction>(InV));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000575 }
576 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
577 }
578 } else {
579 CastInst *CI = cast<CastInst>(&I);
580 const Type *RetTy = CI->getType();
581 for (unsigned i = 0; i != NumPHIValues; ++i) {
582 Value *InV;
583 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Owen Anderson02b48c32009-07-29 18:55:55 +0000584 InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000585 } else {
586 assert(PN->getIncomingBlock(i) == NonConstBB);
Gabor Greifa645dd32008-05-16 19:29:10 +0000587 InV = CastInst::Create(CI->getOpcode(), PN->getIncomingValue(i),
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000588 I.getType(), "phitmp",
589 NonConstBB->getTerminator());
Chris Lattner3980f9b2009-10-21 23:41:58 +0000590 Worklist.Add(cast<Instruction>(InV));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000591 }
592 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
593 }
594 }
595 return ReplaceInstUsesWith(I, NewPN);
596}
597
Chris Lattner55476162008-01-29 06:52:45 +0000598
Chris Lattner3554f972008-05-20 05:46:13 +0000599/// WillNotOverflowSignedAdd - Return true if we can prove that:
600/// (sext (add LHS, RHS)) === (add (sext LHS), (sext RHS))
601/// This basically requires proving that the add in the original type would not
602/// overflow to change the sign bit or have a carry out.
603bool InstCombiner::WillNotOverflowSignedAdd(Value *LHS, Value *RHS) {
604 // There are different heuristics we can use for this. Here are some simple
605 // ones.
606
607 // Add has the property that adding any two 2's complement numbers can only
608 // have one carry bit which can change a sign. As such, if LHS and RHS each
Chris Lattner96076f72009-11-27 17:42:22 +0000609 // have at least two sign bits, we know that the addition of the two values
610 // will sign extend fine.
Chris Lattner3554f972008-05-20 05:46:13 +0000611 if (ComputeNumSignBits(LHS) > 1 && ComputeNumSignBits(RHS) > 1)
612 return true;
613
614
615 // If one of the operands only has one non-zero bit, and if the other operand
616 // has a known-zero bit in a more significant place than it (not including the
617 // sign bit) the ripple may go up to and fill the zero, but won't change the
618 // sign. For example, (X & ~4) + 1.
619
620 // TODO: Implement.
621
622 return false;
623}
624
Chris Lattner55476162008-01-29 06:52:45 +0000625
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000626Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
627 bool Changed = SimplifyCommutative(I);
628 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
629
Chris Lattner96076f72009-11-27 17:42:22 +0000630 if (Value *V = SimplifyAddInst(LHS, RHS, I.hasNoSignedWrap(),
631 I.hasNoUnsignedWrap(), TD))
632 return ReplaceInstUsesWith(I, V);
633
634
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000635 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000636 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
637 // X + (signbit) --> X ^ signbit
638 const APInt& Val = CI->getValue();
639 uint32_t BitWidth = Val.getBitWidth();
640 if (Val == APInt::getSignBit(BitWidth))
Gabor Greifa645dd32008-05-16 19:29:10 +0000641 return BinaryOperator::CreateXor(LHS, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000642
643 // See if SimplifyDemandedBits can simplify this. This handles stuff like
644 // (X & 254)+1 -> (X&254)|1
Dan Gohman8fd520a2009-06-15 22:12:54 +0000645 if (SimplifyDemandedInstructionBits(I))
Chris Lattner676c78e2009-01-31 08:15:18 +0000646 return &I;
Dan Gohman35b76162008-10-30 20:40:10 +0000647
Eli Friedmana21526d2009-07-13 22:27:52 +0000648 // zext(bool) + C -> bool ? C + 1 : C
Dan Gohman35b76162008-10-30 20:40:10 +0000649 if (ZExtInst *ZI = dyn_cast<ZExtInst>(LHS))
Chris Lattner03a27b42010-01-04 07:02:48 +0000650 if (ZI->getSrcTy() == Type::getInt1Ty(I.getContext()))
Dan Gohmanfe91cd62009-08-12 16:04:34 +0000651 return SelectInst::Create(ZI->getOperand(0), AddOne(CI), CI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000652 }
653
654 if (isa<PHINode>(LHS))
655 if (Instruction *NV = FoldOpIntoPhi(I))
656 return NV;
657
658 ConstantInt *XorRHS = 0;
659 Value *XorLHS = 0;
660 if (isa<ConstantInt>(RHSC) &&
Dan Gohmancdff2122009-08-12 16:23:25 +0000661 match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
Dan Gohman8fd520a2009-06-15 22:12:54 +0000662 uint32_t TySizeBits = I.getType()->getScalarSizeInBits();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000663 const APInt& RHSVal = cast<ConstantInt>(RHSC)->getValue();
664
665 uint32_t Size = TySizeBits / 2;
666 APInt C0080Val(APInt(TySizeBits, 1ULL).shl(Size - 1));
667 APInt CFF80Val(-C0080Val);
668 do {
669 if (TySizeBits > Size) {
670 // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
671 // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
672 if ((RHSVal == CFF80Val && XorRHS->getValue() == C0080Val) ||
673 (RHSVal == C0080Val && XorRHS->getValue() == CFF80Val)) {
674 // This is a sign extend if the top bits are known zero.
675 if (!MaskedValueIsZero(XorLHS,
676 APInt::getHighBitsSet(TySizeBits, TySizeBits - Size)))
677 Size = 0; // Not a sign ext, but can't be any others either.
678 break;
679 }
680 }
681 Size >>= 1;
682 C0080Val = APIntOps::lshr(C0080Val, Size);
683 CFF80Val = APIntOps::ashr(CFF80Val, Size);
684 } while (Size >= 1);
685
686 // FIXME: This shouldn't be necessary. When the backends can handle types
Chris Lattnerdeef1a72008-05-19 20:25:04 +0000687 // with funny bit widths then this switch statement should be removed. It
688 // is just here to get the size of the "middle" type back up to something
689 // that the back ends can handle.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000690 const Type *MiddleType = 0;
691 switch (Size) {
692 default: break;
Chris Lattner03a27b42010-01-04 07:02:48 +0000693 case 32:
694 case 16:
695 case 8: MiddleType = IntegerType::get(I.getContext(), Size); break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000696 }
697 if (MiddleType) {
Chris Lattnerc7694852009-08-30 07:44:24 +0000698 Value *NewTrunc = Builder->CreateTrunc(XorLHS, MiddleType, "sext");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000699 return new SExtInst(NewTrunc, I.getType(), I.getName());
700 }
701 }
702 }
703
Chris Lattner03a27b42010-01-04 07:02:48 +0000704 if (I.getType() == Type::getInt1Ty(I.getContext()))
Nick Lewyckyd4b63672008-05-31 17:59:52 +0000705 return BinaryOperator::CreateXor(LHS, RHS);
706
Nick Lewycky4d474cd2008-05-23 04:39:38 +0000707 // X + X --> X << 1
Nick Lewyckyd4b63672008-05-31 17:59:52 +0000708 if (I.getType()->isInteger()) {
Dan Gohmancdff2122009-08-12 16:23:25 +0000709 if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS)))
Owen Anderson24be4c12009-07-03 00:17:18 +0000710 return Result;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000711
712 if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
713 if (RHSI->getOpcode() == Instruction::Sub)
714 if (LHS == RHSI->getOperand(1)) // A + (B - A) --> B
715 return ReplaceInstUsesWith(I, RHSI->getOperand(0));
716 }
717 if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
718 if (LHSI->getOpcode() == Instruction::Sub)
719 if (RHS == LHSI->getOperand(1)) // (B - A) + A --> B
720 return ReplaceInstUsesWith(I, LHSI->getOperand(0));
721 }
722 }
723
724 // -A + B --> B - A
Chris Lattner53c9fbf2008-02-17 21:03:36 +0000725 // -A + -B --> -(A + B)
Dan Gohmanfe91cd62009-08-12 16:04:34 +0000726 if (Value *LHSV = dyn_castNegVal(LHS)) {
Chris Lattner322a9192008-02-18 17:50:16 +0000727 if (LHS->getType()->isIntOrIntVector()) {
Dan Gohmanfe91cd62009-08-12 16:04:34 +0000728 if (Value *RHSV = dyn_castNegVal(RHS)) {
Chris Lattnerc7694852009-08-30 07:44:24 +0000729 Value *NewAdd = Builder->CreateAdd(LHSV, RHSV, "sum");
Dan Gohmancdff2122009-08-12 16:23:25 +0000730 return BinaryOperator::CreateNeg(NewAdd);
Chris Lattner322a9192008-02-18 17:50:16 +0000731 }
Chris Lattner53c9fbf2008-02-17 21:03:36 +0000732 }
733
Gabor Greifa645dd32008-05-16 19:29:10 +0000734 return BinaryOperator::CreateSub(RHS, LHSV);
Chris Lattner53c9fbf2008-02-17 21:03:36 +0000735 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000736
737 // A + -B --> A - B
738 if (!isa<Constant>(RHS))
Dan Gohmanfe91cd62009-08-12 16:04:34 +0000739 if (Value *V = dyn_castNegVal(RHS))
Gabor Greifa645dd32008-05-16 19:29:10 +0000740 return BinaryOperator::CreateSub(LHS, V);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000741
742
743 ConstantInt *C2;
Dan Gohmanfe91cd62009-08-12 16:04:34 +0000744 if (Value *X = dyn_castFoldableMul(LHS, C2)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000745 if (X == RHS) // X*C + X --> X * (C+1)
Dan Gohmanfe91cd62009-08-12 16:04:34 +0000746 return BinaryOperator::CreateMul(RHS, AddOne(C2));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000747
748 // X*C1 + X*C2 --> X * (C1+C2)
749 ConstantInt *C1;
Dan Gohmanfe91cd62009-08-12 16:04:34 +0000750 if (X == dyn_castFoldableMul(RHS, C1))
Owen Anderson02b48c32009-07-29 18:55:55 +0000751 return BinaryOperator::CreateMul(X, ConstantExpr::getAdd(C1, C2));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000752 }
753
754 // X + X*C --> X * (C+1)
Dan Gohmanfe91cd62009-08-12 16:04:34 +0000755 if (dyn_castFoldableMul(RHS, C2) == LHS)
756 return BinaryOperator::CreateMul(LHS, AddOne(C2));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000757
758 // X + ~X --> -1 since ~X = -X-1
Dan Gohmanfe91cd62009-08-12 16:04:34 +0000759 if (dyn_castNotVal(LHS) == RHS ||
760 dyn_castNotVal(RHS) == LHS)
Owen Andersonaac28372009-07-31 20:28:14 +0000761 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000762
763
764 // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
Dan Gohmancdff2122009-08-12 16:23:25 +0000765 if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
766 if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2)))
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000767 return R;
Chris Lattnerc1575ce2008-05-19 20:01:56 +0000768
769 // A+B --> A|B iff A and B have no bits set in common.
770 if (const IntegerType *IT = dyn_cast<IntegerType>(I.getType())) {
771 APInt Mask = APInt::getAllOnesValue(IT->getBitWidth());
772 APInt LHSKnownOne(IT->getBitWidth(), 0);
773 APInt LHSKnownZero(IT->getBitWidth(), 0);
774 ComputeMaskedBits(LHS, Mask, LHSKnownZero, LHSKnownOne);
775 if (LHSKnownZero != 0) {
776 APInt RHSKnownOne(IT->getBitWidth(), 0);
777 APInt RHSKnownZero(IT->getBitWidth(), 0);
778 ComputeMaskedBits(RHS, Mask, RHSKnownZero, RHSKnownOne);
779
780 // No bits in common -> bitwise or.
Chris Lattner130443c2008-05-19 20:03:53 +0000781 if ((LHSKnownZero|RHSKnownZero).isAllOnesValue())
Chris Lattnerc1575ce2008-05-19 20:01:56 +0000782 return BinaryOperator::CreateOr(LHS, RHS);
Chris Lattnerc1575ce2008-05-19 20:01:56 +0000783 }
784 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000785
Nick Lewycky83598a72008-02-03 07:42:09 +0000786 // W*X + Y*Z --> W * (X+Z) iff W == Y
Nick Lewycky5d03b512008-02-03 08:19:11 +0000787 if (I.getType()->isIntOrIntVector()) {
Nick Lewycky83598a72008-02-03 07:42:09 +0000788 Value *W, *X, *Y, *Z;
Dan Gohmancdff2122009-08-12 16:23:25 +0000789 if (match(LHS, m_Mul(m_Value(W), m_Value(X))) &&
790 match(RHS, m_Mul(m_Value(Y), m_Value(Z)))) {
Nick Lewycky83598a72008-02-03 07:42:09 +0000791 if (W != Y) {
792 if (W == Z) {
Bill Wendling44a36ea2008-02-26 10:53:30 +0000793 std::swap(Y, Z);
Nick Lewycky83598a72008-02-03 07:42:09 +0000794 } else if (Y == X) {
Bill Wendling44a36ea2008-02-26 10:53:30 +0000795 std::swap(W, X);
796 } else if (X == Z) {
Nick Lewycky83598a72008-02-03 07:42:09 +0000797 std::swap(Y, Z);
798 std::swap(W, X);
799 }
800 }
801
802 if (W == Y) {
Chris Lattnerc7694852009-08-30 07:44:24 +0000803 Value *NewAdd = Builder->CreateAdd(X, Z, LHS->getName());
Gabor Greifa645dd32008-05-16 19:29:10 +0000804 return BinaryOperator::CreateMul(W, NewAdd);
Nick Lewycky83598a72008-02-03 07:42:09 +0000805 }
806 }
807 }
808
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000809 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
810 Value *X = 0;
Dan Gohmancdff2122009-08-12 16:23:25 +0000811 if (match(LHS, m_Not(m_Value(X)))) // ~X + C --> (C-1) - X
Dan Gohmanfe91cd62009-08-12 16:04:34 +0000812 return BinaryOperator::CreateSub(SubOne(CRHS), X);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000813
814 // (X & FF00) + xx00 -> (X+xx00) & FF00
Owen Andersona21eb582009-07-10 17:35:01 +0000815 if (LHS->hasOneUse() &&
Dan Gohmancdff2122009-08-12 16:23:25 +0000816 match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
Owen Anderson02b48c32009-07-29 18:55:55 +0000817 Constant *Anded = ConstantExpr::getAnd(CRHS, C2);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000818 if (Anded == CRHS) {
819 // See if all bits from the first bit set in the Add RHS up are included
820 // in the mask. First, get the rightmost bit.
821 const APInt& AddRHSV = CRHS->getValue();
822
823 // Form a mask of all bits from the lowest bit added through the top.
824 APInt AddRHSHighBits(~((AddRHSV & -AddRHSV)-1));
825
826 // See if the and mask includes all of these bits.
827 APInt AddRHSHighBitsAnd(AddRHSHighBits & C2->getValue());
828
829 if (AddRHSHighBits == AddRHSHighBitsAnd) {
830 // Okay, the xform is safe. Insert the new add pronto.
Chris Lattnerc7694852009-08-30 07:44:24 +0000831 Value *NewAdd = Builder->CreateAdd(X, CRHS, LHS->getName());
Gabor Greifa645dd32008-05-16 19:29:10 +0000832 return BinaryOperator::CreateAnd(NewAdd, C2);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000833 }
834 }
835 }
836
837 // Try to fold constant add into select arguments.
838 if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
Chris Lattner54826cd2010-01-04 07:53:58 +0000839 if (Instruction *R = FoldOpIntoSelect(I, SI))
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000840 return R;
841 }
842
Chris Lattnerbf0c5f32007-12-20 01:56:58 +0000843 // add (select X 0 (sub n A)) A --> select X A n
Christopher Lamb244ec282007-12-18 09:34:41 +0000844 {
845 SelectInst *SI = dyn_cast<SelectInst>(LHS);
Chris Lattner641ea462008-11-16 04:46:19 +0000846 Value *A = RHS;
Christopher Lamb244ec282007-12-18 09:34:41 +0000847 if (!SI) {
848 SI = dyn_cast<SelectInst>(RHS);
Chris Lattner641ea462008-11-16 04:46:19 +0000849 A = LHS;
Christopher Lamb244ec282007-12-18 09:34:41 +0000850 }
Chris Lattnerbf0c5f32007-12-20 01:56:58 +0000851 if (SI && SI->hasOneUse()) {
Christopher Lamb244ec282007-12-18 09:34:41 +0000852 Value *TV = SI->getTrueValue();
853 Value *FV = SI->getFalseValue();
Chris Lattner641ea462008-11-16 04:46:19 +0000854 Value *N;
Christopher Lamb244ec282007-12-18 09:34:41 +0000855
856 // Can we fold the add into the argument of the select?
857 // We check both true and false select arguments for a matching subtract.
Dan Gohmancdff2122009-08-12 16:23:25 +0000858 if (match(FV, m_Zero()) &&
859 match(TV, m_Sub(m_Value(N), m_Specific(A))))
Chris Lattner641ea462008-11-16 04:46:19 +0000860 // Fold the add into the true select value.
Gabor Greifd6da1d02008-04-06 20:25:17 +0000861 return SelectInst::Create(SI->getCondition(), N, A);
Dan Gohmancdff2122009-08-12 16:23:25 +0000862 if (match(TV, m_Zero()) &&
863 match(FV, m_Sub(m_Value(N), m_Specific(A))))
Chris Lattner641ea462008-11-16 04:46:19 +0000864 // Fold the add into the false select value.
Gabor Greifd6da1d02008-04-06 20:25:17 +0000865 return SelectInst::Create(SI->getCondition(), A, N);
Christopher Lamb244ec282007-12-18 09:34:41 +0000866 }
867 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000868
Chris Lattner3554f972008-05-20 05:46:13 +0000869 // Check for (add (sext x), y), see if we can merge this into an
870 // integer add followed by a sext.
871 if (SExtInst *LHSConv = dyn_cast<SExtInst>(LHS)) {
872 // (add (sext x), cst) --> (sext (add x, cst'))
873 if (ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS)) {
874 Constant *CI =
Owen Anderson02b48c32009-07-29 18:55:55 +0000875 ConstantExpr::getTrunc(RHSC, LHSConv->getOperand(0)->getType());
Chris Lattner3554f972008-05-20 05:46:13 +0000876 if (LHSConv->hasOneUse() &&
Owen Anderson02b48c32009-07-29 18:55:55 +0000877 ConstantExpr::getSExt(CI, I.getType()) == RHSC &&
Chris Lattner3554f972008-05-20 05:46:13 +0000878 WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
879 // Insert the new, smaller add.
Dan Gohman4dcf7c02009-10-26 22:14:22 +0000880 Value *NewAdd = Builder->CreateNSWAdd(LHSConv->getOperand(0),
881 CI, "addconv");
Chris Lattner3554f972008-05-20 05:46:13 +0000882 return new SExtInst(NewAdd, I.getType());
883 }
884 }
885
886 // (add (sext x), (sext y)) --> (sext (add int x, y))
887 if (SExtInst *RHSConv = dyn_cast<SExtInst>(RHS)) {
888 // Only do this if x/y have the same type, if at last one of them has a
889 // single use (so we don't increase the number of sexts), and if the
890 // integer add will not overflow.
891 if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
892 (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
893 WillNotOverflowSignedAdd(LHSConv->getOperand(0),
894 RHSConv->getOperand(0))) {
895 // Insert the new integer add.
Dan Gohman4dcf7c02009-10-26 22:14:22 +0000896 Value *NewAdd = Builder->CreateNSWAdd(LHSConv->getOperand(0),
897 RHSConv->getOperand(0), "addconv");
Chris Lattner3554f972008-05-20 05:46:13 +0000898 return new SExtInst(NewAdd, I.getType());
899 }
900 }
901 }
Dan Gohman7ce405e2009-06-04 22:49:04 +0000902
903 return Changed ? &I : 0;
904}
905
906Instruction *InstCombiner::visitFAdd(BinaryOperator &I) {
907 bool Changed = SimplifyCommutative(I);
908 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
909
910 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
911 // X + 0 --> X
912 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
Owen Andersond363a0e2009-07-27 20:59:43 +0000913 if (CFP->isExactlyValue(ConstantFP::getNegativeZero
Dan Gohman7ce405e2009-06-04 22:49:04 +0000914 (I.getType())->getValueAPF()))
915 return ReplaceInstUsesWith(I, LHS);
916 }
917
918 if (isa<PHINode>(LHS))
919 if (Instruction *NV = FoldOpIntoPhi(I))
920 return NV;
921 }
922
923 // -A + B --> B - A
924 // -A + -B --> -(A + B)
Dan Gohmanfe91cd62009-08-12 16:04:34 +0000925 if (Value *LHSV = dyn_castFNegVal(LHS))
Dan Gohman7ce405e2009-06-04 22:49:04 +0000926 return BinaryOperator::CreateFSub(RHS, LHSV);
927
928 // A + -B --> A - B
929 if (!isa<Constant>(RHS))
Dan Gohmanfe91cd62009-08-12 16:04:34 +0000930 if (Value *V = dyn_castFNegVal(RHS))
Dan Gohman7ce405e2009-06-04 22:49:04 +0000931 return BinaryOperator::CreateFSub(LHS, V);
932
933 // Check for X+0.0. Simplify it to X if we know X is not -0.0.
934 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS))
935 if (CFP->getValueAPF().isPosZero() && CannotBeNegativeZero(LHS))
936 return ReplaceInstUsesWith(I, LHS);
937
Chris Lattner3554f972008-05-20 05:46:13 +0000938 // Check for (add double (sitofp x), y), see if we can merge this into an
939 // integer add followed by a promotion.
940 if (SIToFPInst *LHSConv = dyn_cast<SIToFPInst>(LHS)) {
941 // (add double (sitofp x), fpcst) --> (sitofp (add int x, intcst))
942 // ... if the constant fits in the integer value. This is useful for things
943 // like (double)(x & 1234) + 4.0 -> (double)((X & 1234)+4) which no longer
944 // requires a constant pool load, and generally allows the add to be better
945 // instcombined.
946 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS)) {
947 Constant *CI =
Owen Anderson02b48c32009-07-29 18:55:55 +0000948 ConstantExpr::getFPToSI(CFP, LHSConv->getOperand(0)->getType());
Chris Lattner3554f972008-05-20 05:46:13 +0000949 if (LHSConv->hasOneUse() &&
Owen Anderson02b48c32009-07-29 18:55:55 +0000950 ConstantExpr::getSIToFP(CI, I.getType()) == CFP &&
Chris Lattner3554f972008-05-20 05:46:13 +0000951 WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
952 // Insert the new integer add.
Dan Gohman4dcf7c02009-10-26 22:14:22 +0000953 Value *NewAdd = Builder->CreateNSWAdd(LHSConv->getOperand(0),
954 CI, "addconv");
Chris Lattner3554f972008-05-20 05:46:13 +0000955 return new SIToFPInst(NewAdd, I.getType());
956 }
957 }
958
959 // (add double (sitofp x), (sitofp y)) --> (sitofp (add int x, y))
960 if (SIToFPInst *RHSConv = dyn_cast<SIToFPInst>(RHS)) {
961 // Only do this if x/y have the same type, if at last one of them has a
962 // single use (so we don't increase the number of int->fp conversions),
963 // and if the integer add will not overflow.
964 if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
965 (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
966 WillNotOverflowSignedAdd(LHSConv->getOperand(0),
967 RHSConv->getOperand(0))) {
968 // Insert the new integer add.
Dan Gohman4dcf7c02009-10-26 22:14:22 +0000969 Value *NewAdd = Builder->CreateNSWAdd(LHSConv->getOperand(0),
Chris Lattner93e6ff92009-11-04 08:05:20 +0000970 RHSConv->getOperand(0),"addconv");
Chris Lattner3554f972008-05-20 05:46:13 +0000971 return new SIToFPInst(NewAdd, I.getType());
972 }
973 }
974 }
975
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000976 return Changed ? &I : 0;
977}
978
Chris Lattner93e6ff92009-11-04 08:05:20 +0000979
980/// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
981/// code necessary to compute the offset from the base pointer (without adding
982/// in the base pointer). Return the result as a signed integer of intptr size.
Chris Lattner63ac8422010-01-04 07:37:31 +0000983Value *InstCombiner::EmitGEPOffset(User *GEP) {
984 TargetData &TD = *getTargetData();
Chris Lattner93e6ff92009-11-04 08:05:20 +0000985 gep_type_iterator GTI = gep_type_begin(GEP);
986 const Type *IntPtrTy = TD.getIntPtrType(GEP->getContext());
987 Value *Result = Constant::getNullValue(IntPtrTy);
988
989 // Build a mask for high order bits.
990 unsigned IntPtrWidth = TD.getPointerSizeInBits();
991 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
992
993 for (User::op_iterator i = GEP->op_begin() + 1, e = GEP->op_end(); i != e;
994 ++i, ++GTI) {
995 Value *Op = *i;
996 uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType()) & PtrSizeMask;
997 if (ConstantInt *OpC = dyn_cast<ConstantInt>(Op)) {
998 if (OpC->isZero()) continue;
999
1000 // Handle a struct index, which adds its field offset to the pointer.
1001 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
1002 Size = TD.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
1003
Chris Lattner63ac8422010-01-04 07:37:31 +00001004 Result = Builder->CreateAdd(Result,
1005 ConstantInt::get(IntPtrTy, Size),
1006 GEP->getName()+".offs");
Chris Lattner93e6ff92009-11-04 08:05:20 +00001007 continue;
1008 }
1009
1010 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
1011 Constant *OC =
1012 ConstantExpr::getIntegerCast(OpC, IntPtrTy, true /*SExt*/);
1013 Scale = ConstantExpr::getMul(OC, Scale);
1014 // Emit an add instruction.
Chris Lattner63ac8422010-01-04 07:37:31 +00001015 Result = Builder->CreateAdd(Result, Scale, GEP->getName()+".offs");
Chris Lattner93e6ff92009-11-04 08:05:20 +00001016 continue;
1017 }
1018 // Convert to correct type.
1019 if (Op->getType() != IntPtrTy)
Chris Lattner63ac8422010-01-04 07:37:31 +00001020 Op = Builder->CreateIntCast(Op, IntPtrTy, true, Op->getName()+".c");
Chris Lattner93e6ff92009-11-04 08:05:20 +00001021 if (Size != 1) {
1022 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
1023 // We'll let instcombine(mul) convert this to a shl if possible.
Chris Lattner63ac8422010-01-04 07:37:31 +00001024 Op = Builder->CreateMul(Op, Scale, GEP->getName()+".idx");
Chris Lattner93e6ff92009-11-04 08:05:20 +00001025 }
1026
1027 // Emit an add instruction.
Chris Lattner63ac8422010-01-04 07:37:31 +00001028 Result = Builder->CreateAdd(Op, Result, GEP->getName()+".offs");
Chris Lattner93e6ff92009-11-04 08:05:20 +00001029 }
1030 return Result;
1031}
1032
1033
Chris Lattner93e6ff92009-11-04 08:05:20 +00001034
1035
1036/// Optimize pointer differences into the same array into a size. Consider:
1037/// &A[10] - &A[0]: we should compile this to "10". LHS/RHS are the pointer
1038/// operands to the ptrtoint instructions for the LHS/RHS of the subtract.
1039///
1040Value *InstCombiner::OptimizePointerDifference(Value *LHS, Value *RHS,
1041 const Type *Ty) {
1042 assert(TD && "Must have target data info for this");
1043
1044 // If LHS is a gep based on RHS or RHS is a gep based on LHS, we can optimize
1045 // this.
Chris Lattner483868d2010-01-04 18:48:26 +00001046 bool Swapped = false;
Chris Lattner08be8ff2010-01-01 22:42:29 +00001047 GetElementPtrInst *GEP = 0;
1048 ConstantExpr *CstGEP = 0;
Chris Lattner93e6ff92009-11-04 08:05:20 +00001049
Chris Lattner08be8ff2010-01-01 22:42:29 +00001050 // TODO: Could also optimize &A[i] - &A[j] -> "i-j", and "&A.foo[i] - &A.foo".
1051 // For now we require one side to be the base pointer "A" or a constant
1052 // expression derived from it.
1053 if (GetElementPtrInst *LHSGEP = dyn_cast<GetElementPtrInst>(LHS)) {
1054 // (gep X, ...) - X
1055 if (LHSGEP->getOperand(0) == RHS) {
1056 GEP = LHSGEP;
1057 Swapped = false;
1058 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(RHS)) {
1059 // (gep X, ...) - (ce_gep X, ...)
1060 if (CE->getOpcode() == Instruction::GetElementPtr &&
1061 LHSGEP->getOperand(0) == CE->getOperand(0)) {
1062 CstGEP = CE;
1063 GEP = LHSGEP;
1064 Swapped = false;
1065 }
1066 }
1067 }
1068
1069 if (GetElementPtrInst *RHSGEP = dyn_cast<GetElementPtrInst>(RHS)) {
1070 // X - (gep X, ...)
1071 if (RHSGEP->getOperand(0) == LHS) {
1072 GEP = RHSGEP;
1073 Swapped = true;
1074 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(LHS)) {
1075 // (ce_gep X, ...) - (gep X, ...)
1076 if (CE->getOpcode() == Instruction::GetElementPtr &&
1077 RHSGEP->getOperand(0) == CE->getOperand(0)) {
1078 CstGEP = CE;
1079 GEP = RHSGEP;
1080 Swapped = true;
1081 }
1082 }
1083 }
1084
1085 if (GEP == 0)
Chris Lattner93e6ff92009-11-04 08:05:20 +00001086 return 0;
1087
Chris Lattner93e6ff92009-11-04 08:05:20 +00001088 // Emit the offset of the GEP and an intptr_t.
Chris Lattner63ac8422010-01-04 07:37:31 +00001089 Value *Result = EmitGEPOffset(GEP);
Chris Lattner08be8ff2010-01-01 22:42:29 +00001090
1091 // If we had a constant expression GEP on the other side offsetting the
1092 // pointer, subtract it from the offset we have.
1093 if (CstGEP) {
Chris Lattner63ac8422010-01-04 07:37:31 +00001094 Value *CstOffset = EmitGEPOffset(CstGEP);
Chris Lattner08be8ff2010-01-01 22:42:29 +00001095 Result = Builder->CreateSub(Result, CstOffset);
1096 }
1097
Chris Lattner93e6ff92009-11-04 08:05:20 +00001098
1099 // If we have p - gep(p, ...) then we have to negate the result.
1100 if (Swapped)
1101 Result = Builder->CreateNeg(Result, "diff.neg");
1102
1103 return Builder->CreateIntCast(Result, Ty, true);
1104}
1105
1106
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001107Instruction *InstCombiner::visitSub(BinaryOperator &I) {
1108 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1109
Dan Gohman7ce405e2009-06-04 22:49:04 +00001110 if (Op0 == Op1) // sub X, X -> 0
Owen Andersonaac28372009-07-31 20:28:14 +00001111 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001112
Chris Lattnera54b96b2009-12-21 04:04:05 +00001113 // If this is a 'B = x-(-A)', change to B = x+A. This preserves NSW/NUW.
1114 if (Value *V = dyn_castNegVal(Op1)) {
1115 BinaryOperator *Res = BinaryOperator::CreateAdd(Op0, V);
1116 Res->setHasNoSignedWrap(I.hasNoSignedWrap());
1117 Res->setHasNoUnsignedWrap(I.hasNoUnsignedWrap());
1118 return Res;
1119 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001120
1121 if (isa<UndefValue>(Op0))
1122 return ReplaceInstUsesWith(I, Op0); // undef - X -> undef
1123 if (isa<UndefValue>(Op1))
1124 return ReplaceInstUsesWith(I, Op1); // X - undef -> undef
Chris Lattner03a27b42010-01-04 07:02:48 +00001125 if (I.getType() == Type::getInt1Ty(I.getContext()))
Chris Lattner93e6ff92009-11-04 08:05:20 +00001126 return BinaryOperator::CreateXor(Op0, Op1);
1127
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001128 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
Chris Lattner93e6ff92009-11-04 08:05:20 +00001129 // Replace (-1 - A) with (~A).
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001130 if (C->isAllOnesValue())
Dan Gohmancdff2122009-08-12 16:23:25 +00001131 return BinaryOperator::CreateNot(Op1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001132
1133 // C - ~X == X + (1+C)
1134 Value *X = 0;
Dan Gohmancdff2122009-08-12 16:23:25 +00001135 if (match(Op1, m_Not(m_Value(X))))
Dan Gohmanfe91cd62009-08-12 16:04:34 +00001136 return BinaryOperator::CreateAdd(X, AddOne(C));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001137
1138 // -(X >>u 31) -> (X >>s 31)
1139 // -(X >>s 31) -> (X >>u 31)
1140 if (C->isZero()) {
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00001141 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op1)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001142 if (SI->getOpcode() == Instruction::LShr) {
1143 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
1144 // Check to see if we are shifting out everything but the sign bit.
1145 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
1146 SI->getType()->getPrimitiveSizeInBits()-1) {
1147 // Ok, the transformation is safe. Insert AShr.
Gabor Greifa645dd32008-05-16 19:29:10 +00001148 return BinaryOperator::Create(Instruction::AShr,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001149 SI->getOperand(0), CU, SI->getName());
1150 }
1151 }
Chris Lattner93e6ff92009-11-04 08:05:20 +00001152 } else if (SI->getOpcode() == Instruction::AShr) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001153 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
1154 // Check to see if we are shifting out everything but the sign bit.
1155 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
1156 SI->getType()->getPrimitiveSizeInBits()-1) {
1157 // Ok, the transformation is safe. Insert LShr.
Gabor Greifa645dd32008-05-16 19:29:10 +00001158 return BinaryOperator::CreateLShr(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001159 SI->getOperand(0), CU, SI->getName());
1160 }
1161 }
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00001162 }
1163 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001164 }
1165
1166 // Try to fold constant sub into select arguments.
1167 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner54826cd2010-01-04 07:53:58 +00001168 if (Instruction *R = FoldOpIntoSelect(I, SI))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001169 return R;
Eli Friedmana21526d2009-07-13 22:27:52 +00001170
1171 // C - zext(bool) -> bool ? C - 1 : C
1172 if (ZExtInst *ZI = dyn_cast<ZExtInst>(Op1))
Chris Lattner03a27b42010-01-04 07:02:48 +00001173 if (ZI->getSrcTy() == Type::getInt1Ty(I.getContext()))
Dan Gohmanfe91cd62009-08-12 16:04:34 +00001174 return SelectInst::Create(ZI->getOperand(0), SubOne(C), C);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001175 }
1176
1177 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
Dan Gohman7ce405e2009-06-04 22:49:04 +00001178 if (Op1I->getOpcode() == Instruction::Add) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001179 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
Dan Gohmancdff2122009-08-12 16:23:25 +00001180 return BinaryOperator::CreateNeg(Op1I->getOperand(1),
Owen Anderson15b39322009-07-13 04:09:18 +00001181 I.getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001182 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
Dan Gohmancdff2122009-08-12 16:23:25 +00001183 return BinaryOperator::CreateNeg(Op1I->getOperand(0),
Owen Anderson15b39322009-07-13 04:09:18 +00001184 I.getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001185 else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
1186 if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
1187 // C1-(X+C2) --> (C1-C2)-X
Owen Anderson24be4c12009-07-03 00:17:18 +00001188 return BinaryOperator::CreateSub(
Owen Anderson02b48c32009-07-29 18:55:55 +00001189 ConstantExpr::getSub(CI1, CI2), Op1I->getOperand(0));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001190 }
1191 }
1192
1193 if (Op1I->hasOneUse()) {
1194 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
1195 // is not used by anyone else...
1196 //
Dan Gohman7ce405e2009-06-04 22:49:04 +00001197 if (Op1I->getOpcode() == Instruction::Sub) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001198 // Swap the two operands of the subexpr...
1199 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
1200 Op1I->setOperand(0, IIOp1);
1201 Op1I->setOperand(1, IIOp0);
1202
1203 // Create the new top level add instruction...
Gabor Greifa645dd32008-05-16 19:29:10 +00001204 return BinaryOperator::CreateAdd(Op0, Op1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001205 }
1206
1207 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
1208 //
1209 if (Op1I->getOpcode() == Instruction::And &&
1210 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
1211 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
1212
Chris Lattnerc7694852009-08-30 07:44:24 +00001213 Value *NewNot = Builder->CreateNot(OtherOp, "B.not");
Gabor Greifa645dd32008-05-16 19:29:10 +00001214 return BinaryOperator::CreateAnd(Op0, NewNot);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001215 }
1216
1217 // 0 - (X sdiv C) -> (X sdiv -C)
1218 if (Op1I->getOpcode() == Instruction::SDiv)
1219 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
1220 if (CSI->isZero())
1221 if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
Gabor Greifa645dd32008-05-16 19:29:10 +00001222 return BinaryOperator::CreateSDiv(Op1I->getOperand(0),
Owen Anderson02b48c32009-07-29 18:55:55 +00001223 ConstantExpr::getNeg(DivRHS));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001224
1225 // X - X*C --> X * (1-C)
1226 ConstantInt *C2 = 0;
Dan Gohmanfe91cd62009-08-12 16:04:34 +00001227 if (dyn_castFoldableMul(Op1I, C2) == Op0) {
Owen Anderson24be4c12009-07-03 00:17:18 +00001228 Constant *CP1 =
Owen Anderson02b48c32009-07-29 18:55:55 +00001229 ConstantExpr::getSub(ConstantInt::get(I.getType(), 1),
Dan Gohman8fd520a2009-06-15 22:12:54 +00001230 C2);
Gabor Greifa645dd32008-05-16 19:29:10 +00001231 return BinaryOperator::CreateMul(Op0, CP1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001232 }
1233 }
1234 }
1235
Dan Gohman7ce405e2009-06-04 22:49:04 +00001236 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
1237 if (Op0I->getOpcode() == Instruction::Add) {
1238 if (Op0I->getOperand(0) == Op1) // (Y+X)-Y == X
1239 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
1240 else if (Op0I->getOperand(1) == Op1) // (X+Y)-Y == X
1241 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
1242 } else if (Op0I->getOpcode() == Instruction::Sub) {
1243 if (Op0I->getOperand(0) == Op1) // (X-Y)-X == -Y
Dan Gohmancdff2122009-08-12 16:23:25 +00001244 return BinaryOperator::CreateNeg(Op0I->getOperand(1),
Owen Anderson15b39322009-07-13 04:09:18 +00001245 I.getName());
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00001246 }
Dan Gohman7ce405e2009-06-04 22:49:04 +00001247 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001248
1249 ConstantInt *C1;
Dan Gohmanfe91cd62009-08-12 16:04:34 +00001250 if (Value *X = dyn_castFoldableMul(Op0, C1)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001251 if (X == Op1) // X*C - X --> X * (C-1)
Dan Gohmanfe91cd62009-08-12 16:04:34 +00001252 return BinaryOperator::CreateMul(Op1, SubOne(C1));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001253
1254 ConstantInt *C2; // X*C1 - X*C2 -> X * (C1-C2)
Dan Gohmanfe91cd62009-08-12 16:04:34 +00001255 if (X == dyn_castFoldableMul(Op1, C2))
Owen Anderson02b48c32009-07-29 18:55:55 +00001256 return BinaryOperator::CreateMul(X, ConstantExpr::getSub(C1, C2));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001257 }
Chris Lattner93e6ff92009-11-04 08:05:20 +00001258
1259 // Optimize pointer differences into the same array into a size. Consider:
1260 // &A[10] - &A[0]: we should compile this to "10".
1261 if (TD) {
Chris Lattnerc49d68a2010-01-01 22:12:03 +00001262 Value *LHSOp, *RHSOp;
Chris Lattnerc93843f2010-01-01 22:29:12 +00001263 if (match(Op0, m_PtrToInt(m_Value(LHSOp))) &&
1264 match(Op1, m_PtrToInt(m_Value(RHSOp))))
Chris Lattnerc49d68a2010-01-01 22:12:03 +00001265 if (Value *Res = OptimizePointerDifference(LHSOp, RHSOp, I.getType()))
1266 return ReplaceInstUsesWith(I, Res);
Chris Lattner93e6ff92009-11-04 08:05:20 +00001267
1268 // trunc(p)-trunc(q) -> trunc(p-q)
Chris Lattnerc93843f2010-01-01 22:29:12 +00001269 if (match(Op0, m_Trunc(m_PtrToInt(m_Value(LHSOp)))) &&
1270 match(Op1, m_Trunc(m_PtrToInt(m_Value(RHSOp)))))
1271 if (Value *Res = OptimizePointerDifference(LHSOp, RHSOp, I.getType()))
1272 return ReplaceInstUsesWith(I, Res);
Chris Lattner93e6ff92009-11-04 08:05:20 +00001273 }
1274
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001275 return 0;
1276}
1277
Dan Gohman7ce405e2009-06-04 22:49:04 +00001278Instruction *InstCombiner::visitFSub(BinaryOperator &I) {
1279 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1280
1281 // If this is a 'B = x-(-A)', change to B = x+A...
Dan Gohmanfe91cd62009-08-12 16:04:34 +00001282 if (Value *V = dyn_castFNegVal(Op1))
Dan Gohman7ce405e2009-06-04 22:49:04 +00001283 return BinaryOperator::CreateFAdd(Op0, V);
1284
1285 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
1286 if (Op1I->getOpcode() == Instruction::FAdd) {
1287 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
Dan Gohmancdff2122009-08-12 16:23:25 +00001288 return BinaryOperator::CreateFNeg(Op1I->getOperand(1),
Owen Anderson15b39322009-07-13 04:09:18 +00001289 I.getName());
Dan Gohman7ce405e2009-06-04 22:49:04 +00001290 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
Dan Gohmancdff2122009-08-12 16:23:25 +00001291 return BinaryOperator::CreateFNeg(Op1I->getOperand(0),
Owen Anderson15b39322009-07-13 04:09:18 +00001292 I.getName());
Dan Gohman7ce405e2009-06-04 22:49:04 +00001293 }
Dan Gohman7ce405e2009-06-04 22:49:04 +00001294 }
1295
1296 return 0;
1297}
1298
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001299Instruction *InstCombiner::visitMul(BinaryOperator &I) {
1300 bool Changed = SimplifyCommutative(I);
Chris Lattner3508c5c2009-10-11 21:36:10 +00001301 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001302
Chris Lattner3508c5c2009-10-11 21:36:10 +00001303 if (isa<UndefValue>(Op1)) // undef * X -> 0
Owen Andersonaac28372009-07-31 20:28:14 +00001304 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001305
Chris Lattner6438c582009-10-11 07:53:15 +00001306 // Simplify mul instructions with a constant RHS.
Chris Lattner3508c5c2009-10-11 21:36:10 +00001307 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
1308 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1C)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001309
1310 // ((X << C1)*C2) == (X * (C2 << C1))
1311 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op0))
1312 if (SI->getOpcode() == Instruction::Shl)
1313 if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
Gabor Greifa645dd32008-05-16 19:29:10 +00001314 return BinaryOperator::CreateMul(SI->getOperand(0),
Owen Anderson02b48c32009-07-29 18:55:55 +00001315 ConstantExpr::getShl(CI, ShOp));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001316
1317 if (CI->isZero())
Chris Lattner3508c5c2009-10-11 21:36:10 +00001318 return ReplaceInstUsesWith(I, Op1C); // X * 0 == 0
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001319 if (CI->equalsInt(1)) // X * 1 == X
1320 return ReplaceInstUsesWith(I, Op0);
1321 if (CI->isAllOnesValue()) // X * -1 == 0 - X
Dan Gohmancdff2122009-08-12 16:23:25 +00001322 return BinaryOperator::CreateNeg(Op0, I.getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001323
1324 const APInt& Val = cast<ConstantInt>(CI)->getValue();
1325 if (Val.isPowerOf2()) { // Replace X*(2^C) with X << C
Gabor Greifa645dd32008-05-16 19:29:10 +00001326 return BinaryOperator::CreateShl(Op0,
Owen Andersoneacb44d2009-07-24 23:12:02 +00001327 ConstantInt::get(Op0->getType(), Val.logBase2()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001328 }
Chris Lattner3508c5c2009-10-11 21:36:10 +00001329 } else if (isa<VectorType>(Op1C->getType())) {
1330 if (Op1C->isNullValue())
1331 return ReplaceInstUsesWith(I, Op1C);
Nick Lewycky94418732008-11-27 20:21:08 +00001332
Chris Lattner3508c5c2009-10-11 21:36:10 +00001333 if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1C)) {
Nick Lewycky94418732008-11-27 20:21:08 +00001334 if (Op1V->isAllOnesValue()) // X * -1 == 0 - X
Dan Gohmancdff2122009-08-12 16:23:25 +00001335 return BinaryOperator::CreateNeg(Op0, I.getName());
Nick Lewycky94418732008-11-27 20:21:08 +00001336
1337 // As above, vector X*splat(1.0) -> X in all defined cases.
1338 if (Constant *Splat = Op1V->getSplatValue()) {
Nick Lewycky94418732008-11-27 20:21:08 +00001339 if (ConstantInt *CI = dyn_cast<ConstantInt>(Splat))
1340 if (CI->equalsInt(1))
1341 return ReplaceInstUsesWith(I, Op0);
1342 }
1343 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001344 }
1345
1346 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
1347 if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
Chris Lattner3508c5c2009-10-11 21:36:10 +00001348 isa<ConstantInt>(Op0I->getOperand(1)) && isa<ConstantInt>(Op1C)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001349 // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
Chris Lattner3508c5c2009-10-11 21:36:10 +00001350 Value *Add = Builder->CreateMul(Op0I->getOperand(0), Op1C, "tmp");
1351 Value *C1C2 = Builder->CreateMul(Op1C, Op0I->getOperand(1));
Gabor Greifa645dd32008-05-16 19:29:10 +00001352 return BinaryOperator::CreateAdd(Add, C1C2);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001353
1354 }
1355
1356 // Try to fold constant mul into select arguments.
1357 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner54826cd2010-01-04 07:53:58 +00001358 if (Instruction *R = FoldOpIntoSelect(I, SI))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001359 return R;
1360
1361 if (isa<PHINode>(Op0))
1362 if (Instruction *NV = FoldOpIntoPhi(I))
1363 return NV;
1364 }
1365
Dan Gohmanfe91cd62009-08-12 16:04:34 +00001366 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
Chris Lattner3508c5c2009-10-11 21:36:10 +00001367 if (Value *Op1v = dyn_castNegVal(Op1))
Gabor Greifa645dd32008-05-16 19:29:10 +00001368 return BinaryOperator::CreateMul(Op0v, Op1v);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001369
Nick Lewycky1c246402008-11-21 07:33:58 +00001370 // (X / Y) * Y = X - (X % Y)
1371 // (X / Y) * -Y = (X % Y) - X
1372 {
Chris Lattner3508c5c2009-10-11 21:36:10 +00001373 Value *Op1C = Op1;
Nick Lewycky1c246402008-11-21 07:33:58 +00001374 BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0);
1375 if (!BO ||
1376 (BO->getOpcode() != Instruction::UDiv &&
1377 BO->getOpcode() != Instruction::SDiv)) {
Chris Lattner3508c5c2009-10-11 21:36:10 +00001378 Op1C = Op0;
1379 BO = dyn_cast<BinaryOperator>(Op1);
Nick Lewycky1c246402008-11-21 07:33:58 +00001380 }
Chris Lattner3508c5c2009-10-11 21:36:10 +00001381 Value *Neg = dyn_castNegVal(Op1C);
Nick Lewycky1c246402008-11-21 07:33:58 +00001382 if (BO && BO->hasOneUse() &&
Chris Lattner3508c5c2009-10-11 21:36:10 +00001383 (BO->getOperand(1) == Op1C || BO->getOperand(1) == Neg) &&
Nick Lewycky1c246402008-11-21 07:33:58 +00001384 (BO->getOpcode() == Instruction::UDiv ||
1385 BO->getOpcode() == Instruction::SDiv)) {
1386 Value *Op0BO = BO->getOperand(0), *Op1BO = BO->getOperand(1);
1387
Dan Gohman07878902009-08-12 16:33:09 +00001388 // If the division is exact, X % Y is zero.
1389 if (SDivOperator *SDiv = dyn_cast<SDivOperator>(BO))
1390 if (SDiv->isExact()) {
Chris Lattner3508c5c2009-10-11 21:36:10 +00001391 if (Op1BO == Op1C)
Dan Gohman07878902009-08-12 16:33:09 +00001392 return ReplaceInstUsesWith(I, Op0BO);
Chris Lattner3508c5c2009-10-11 21:36:10 +00001393 return BinaryOperator::CreateNeg(Op0BO);
Dan Gohman07878902009-08-12 16:33:09 +00001394 }
1395
Chris Lattnerc7694852009-08-30 07:44:24 +00001396 Value *Rem;
Nick Lewycky1c246402008-11-21 07:33:58 +00001397 if (BO->getOpcode() == Instruction::UDiv)
Chris Lattnerc7694852009-08-30 07:44:24 +00001398 Rem = Builder->CreateURem(Op0BO, Op1BO);
Nick Lewycky1c246402008-11-21 07:33:58 +00001399 else
Chris Lattnerc7694852009-08-30 07:44:24 +00001400 Rem = Builder->CreateSRem(Op0BO, Op1BO);
Nick Lewycky1c246402008-11-21 07:33:58 +00001401 Rem->takeName(BO);
1402
Chris Lattner3508c5c2009-10-11 21:36:10 +00001403 if (Op1BO == Op1C)
Nick Lewycky1c246402008-11-21 07:33:58 +00001404 return BinaryOperator::CreateSub(Op0BO, Rem);
Chris Lattnerc7694852009-08-30 07:44:24 +00001405 return BinaryOperator::CreateSub(Rem, Op0BO);
Nick Lewycky1c246402008-11-21 07:33:58 +00001406 }
1407 }
1408
Chris Lattner6438c582009-10-11 07:53:15 +00001409 /// i1 mul -> i1 and.
Chris Lattner03a27b42010-01-04 07:02:48 +00001410 if (I.getType() == Type::getInt1Ty(I.getContext()))
Chris Lattner3508c5c2009-10-11 21:36:10 +00001411 return BinaryOperator::CreateAnd(Op0, Op1);
Nick Lewyckyd4b63672008-05-31 17:59:52 +00001412
Chris Lattner6438c582009-10-11 07:53:15 +00001413 // X*(1 << Y) --> X << Y
1414 // (1 << Y)*X --> X << Y
1415 {
1416 Value *Y;
1417 if (match(Op0, m_Shl(m_One(), m_Value(Y))))
Chris Lattner3508c5c2009-10-11 21:36:10 +00001418 return BinaryOperator::CreateShl(Op1, Y);
1419 if (match(Op1, m_Shl(m_One(), m_Value(Y))))
Chris Lattner6438c582009-10-11 07:53:15 +00001420 return BinaryOperator::CreateShl(Op0, Y);
1421 }
1422
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001423 // If one of the operands of the multiply is a cast from a boolean value, then
1424 // we know the bool is either zero or one, so this is a 'masking' multiply.
Chris Lattner4ca76f72009-10-11 21:29:45 +00001425 // X * Y (where Y is 0 or 1) -> X & (0-Y)
1426 if (!isa<VectorType>(I.getType())) {
1427 // -2 is "-1 << 1" so it is all bits set except the low one.
Dale Johannesenb5887062009-10-12 18:45:32 +00001428 APInt Negative2(I.getType()->getPrimitiveSizeInBits(), (uint64_t)-2, true);
Chris Lattner291872e2009-10-11 21:22:21 +00001429
Chris Lattner4ca76f72009-10-11 21:29:45 +00001430 Value *BoolCast = 0, *OtherOp = 0;
1431 if (MaskedValueIsZero(Op0, Negative2))
Chris Lattner3508c5c2009-10-11 21:36:10 +00001432 BoolCast = Op0, OtherOp = Op1;
1433 else if (MaskedValueIsZero(Op1, Negative2))
1434 BoolCast = Op1, OtherOp = Op0;
Chris Lattner4ca76f72009-10-11 21:29:45 +00001435
Chris Lattner291872e2009-10-11 21:22:21 +00001436 if (BoolCast) {
Chris Lattner291872e2009-10-11 21:22:21 +00001437 Value *V = Builder->CreateSub(Constant::getNullValue(I.getType()),
1438 BoolCast, "tmp");
1439 return BinaryOperator::CreateAnd(V, OtherOp);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001440 }
1441 }
1442
1443 return Changed ? &I : 0;
1444}
1445
Dan Gohman7ce405e2009-06-04 22:49:04 +00001446Instruction *InstCombiner::visitFMul(BinaryOperator &I) {
1447 bool Changed = SimplifyCommutative(I);
Chris Lattner3508c5c2009-10-11 21:36:10 +00001448 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Dan Gohman7ce405e2009-06-04 22:49:04 +00001449
1450 // Simplify mul instructions with a constant RHS...
Chris Lattner3508c5c2009-10-11 21:36:10 +00001451 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
1452 if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1C)) {
Dan Gohman7ce405e2009-06-04 22:49:04 +00001453 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
1454 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
1455 if (Op1F->isExactlyValue(1.0))
1456 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0'
Chris Lattner3508c5c2009-10-11 21:36:10 +00001457 } else if (isa<VectorType>(Op1C->getType())) {
1458 if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1C)) {
Dan Gohman7ce405e2009-06-04 22:49:04 +00001459 // As above, vector X*splat(1.0) -> X in all defined cases.
1460 if (Constant *Splat = Op1V->getSplatValue()) {
1461 if (ConstantFP *F = dyn_cast<ConstantFP>(Splat))
1462 if (F->isExactlyValue(1.0))
1463 return ReplaceInstUsesWith(I, Op0);
1464 }
1465 }
1466 }
1467
1468 // Try to fold constant mul into select arguments.
1469 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner54826cd2010-01-04 07:53:58 +00001470 if (Instruction *R = FoldOpIntoSelect(I, SI))
Dan Gohman7ce405e2009-06-04 22:49:04 +00001471 return R;
1472
1473 if (isa<PHINode>(Op0))
1474 if (Instruction *NV = FoldOpIntoPhi(I))
1475 return NV;
1476 }
1477
Dan Gohmanfe91cd62009-08-12 16:04:34 +00001478 if (Value *Op0v = dyn_castFNegVal(Op0)) // -X * -Y = X*Y
Chris Lattner3508c5c2009-10-11 21:36:10 +00001479 if (Value *Op1v = dyn_castFNegVal(Op1))
Dan Gohman7ce405e2009-06-04 22:49:04 +00001480 return BinaryOperator::CreateFMul(Op0v, Op1v);
1481
1482 return Changed ? &I : 0;
1483}
1484
Chris Lattner76972db2008-07-14 00:15:52 +00001485/// SimplifyDivRemOfSelect - Try to fold a divide or remainder of a select
1486/// instruction.
1487bool InstCombiner::SimplifyDivRemOfSelect(BinaryOperator &I) {
1488 SelectInst *SI = cast<SelectInst>(I.getOperand(1));
1489
1490 // div/rem X, (Cond ? 0 : Y) -> div/rem X, Y
1491 int NonNullOperand = -1;
1492 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
1493 if (ST->isNullValue())
1494 NonNullOperand = 2;
1495 // div/rem X, (Cond ? Y : 0) -> div/rem X, Y
1496 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
1497 if (ST->isNullValue())
1498 NonNullOperand = 1;
1499
1500 if (NonNullOperand == -1)
1501 return false;
1502
1503 Value *SelectCond = SI->getOperand(0);
1504
1505 // Change the div/rem to use 'Y' instead of the select.
1506 I.setOperand(1, SI->getOperand(NonNullOperand));
1507
1508 // Okay, we know we replace the operand of the div/rem with 'Y' with no
1509 // problem. However, the select, or the condition of the select may have
1510 // multiple uses. Based on our knowledge that the operand must be non-zero,
1511 // propagate the known value for the select into other uses of it, and
1512 // propagate a known value of the condition into its other users.
1513
1514 // If the select and condition only have a single use, don't bother with this,
1515 // early exit.
1516 if (SI->use_empty() && SelectCond->hasOneUse())
1517 return true;
1518
1519 // Scan the current block backward, looking for other uses of SI.
1520 BasicBlock::iterator BBI = &I, BBFront = I.getParent()->begin();
1521
1522 while (BBI != BBFront) {
1523 --BBI;
1524 // If we found a call to a function, we can't assume it will return, so
1525 // information from below it cannot be propagated above it.
1526 if (isa<CallInst>(BBI) && !isa<IntrinsicInst>(BBI))
1527 break;
1528
1529 // Replace uses of the select or its condition with the known values.
1530 for (Instruction::op_iterator I = BBI->op_begin(), E = BBI->op_end();
1531 I != E; ++I) {
1532 if (*I == SI) {
1533 *I = SI->getOperand(NonNullOperand);
Chris Lattner3183fb62009-08-30 06:13:40 +00001534 Worklist.Add(BBI);
Chris Lattner76972db2008-07-14 00:15:52 +00001535 } else if (*I == SelectCond) {
Chris Lattner03a27b42010-01-04 07:02:48 +00001536 *I = NonNullOperand == 1 ? ConstantInt::getTrue(BBI->getContext()) :
1537 ConstantInt::getFalse(BBI->getContext());
Chris Lattner3183fb62009-08-30 06:13:40 +00001538 Worklist.Add(BBI);
Chris Lattner76972db2008-07-14 00:15:52 +00001539 }
1540 }
1541
1542 // If we past the instruction, quit looking for it.
1543 if (&*BBI == SI)
1544 SI = 0;
1545 if (&*BBI == SelectCond)
1546 SelectCond = 0;
1547
1548 // If we ran out of things to eliminate, break out of the loop.
1549 if (SelectCond == 0 && SI == 0)
1550 break;
1551
1552 }
1553 return true;
1554}
1555
1556
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001557/// This function implements the transforms on div instructions that work
1558/// regardless of the kind of div instruction it is (udiv, sdiv, or fdiv). It is
1559/// used by the visitors to those instructions.
1560/// @brief Transforms common to all three div instructions
1561Instruction *InstCombiner::commonDivTransforms(BinaryOperator &I) {
1562 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1563
Chris Lattner653ef3c2008-02-19 06:12:18 +00001564 // undef / X -> 0 for integer.
1565 // undef / X -> undef for FP (the undef could be a snan).
1566 if (isa<UndefValue>(Op0)) {
1567 if (Op0->getType()->isFPOrFPVector())
1568 return ReplaceInstUsesWith(I, Op0);
Owen Andersonaac28372009-07-31 20:28:14 +00001569 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner653ef3c2008-02-19 06:12:18 +00001570 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001571
1572 // X / undef -> undef
1573 if (isa<UndefValue>(Op1))
1574 return ReplaceInstUsesWith(I, Op1);
1575
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001576 return 0;
1577}
1578
1579/// This function implements the transforms common to both integer division
1580/// instructions (udiv and sdiv). It is called by the visitors to those integer
1581/// division instructions.
1582/// @brief Common integer divide transforms
1583Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
1584 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1585
Chris Lattnercefb36c2008-05-16 02:59:42 +00001586 // (sdiv X, X) --> 1 (udiv X, X) --> 1
Nick Lewycky386c0132008-05-23 03:26:47 +00001587 if (Op0 == Op1) {
1588 if (const VectorType *Ty = dyn_cast<VectorType>(I.getType())) {
Owen Andersoneacb44d2009-07-24 23:12:02 +00001589 Constant *CI = ConstantInt::get(Ty->getElementType(), 1);
Nick Lewycky386c0132008-05-23 03:26:47 +00001590 std::vector<Constant*> Elts(Ty->getNumElements(), CI);
Owen Anderson2f422e02009-07-28 21:19:26 +00001591 return ReplaceInstUsesWith(I, ConstantVector::get(Elts));
Nick Lewycky386c0132008-05-23 03:26:47 +00001592 }
1593
Owen Andersoneacb44d2009-07-24 23:12:02 +00001594 Constant *CI = ConstantInt::get(I.getType(), 1);
Nick Lewycky386c0132008-05-23 03:26:47 +00001595 return ReplaceInstUsesWith(I, CI);
1596 }
Chris Lattnercefb36c2008-05-16 02:59:42 +00001597
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001598 if (Instruction *Common = commonDivTransforms(I))
1599 return Common;
Chris Lattner76972db2008-07-14 00:15:52 +00001600
1601 // Handle cases involving: [su]div X, (select Cond, Y, Z)
1602 // This does not apply for fdiv.
1603 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
1604 return &I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001605
1606 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
1607 // div X, 1 == X
1608 if (RHS->equalsInt(1))
1609 return ReplaceInstUsesWith(I, Op0);
1610
1611 // (X / C1) / C2 -> X / (C1*C2)
1612 if (Instruction *LHS = dyn_cast<Instruction>(Op0))
1613 if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
1614 if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
Owen Anderson24be4c12009-07-03 00:17:18 +00001615 if (MultiplyOverflows(RHS, LHSRHS,
Dan Gohmanfe91cd62009-08-12 16:04:34 +00001616 I.getOpcode()==Instruction::SDiv))
Owen Andersonaac28372009-07-31 20:28:14 +00001617 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Nick Lewycky9d798f92008-02-18 22:48:05 +00001618 else
Gabor Greifa645dd32008-05-16 19:29:10 +00001619 return BinaryOperator::Create(I.getOpcode(), LHS->getOperand(0),
Owen Anderson02b48c32009-07-29 18:55:55 +00001620 ConstantExpr::getMul(RHS, LHSRHS));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001621 }
1622
1623 if (!RHS->isZero()) { // avoid X udiv 0
1624 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner54826cd2010-01-04 07:53:58 +00001625 if (Instruction *R = FoldOpIntoSelect(I, SI))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001626 return R;
1627 if (isa<PHINode>(Op0))
1628 if (Instruction *NV = FoldOpIntoPhi(I))
1629 return NV;
1630 }
1631 }
1632
1633 // 0 / X == 0, we don't need to preserve faults!
1634 if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
1635 if (LHS->equalsInt(0))
Owen Andersonaac28372009-07-31 20:28:14 +00001636 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001637
Nick Lewyckyd4b63672008-05-31 17:59:52 +00001638 // It can't be division by zero, hence it must be division by one.
Chris Lattner03a27b42010-01-04 07:02:48 +00001639 if (I.getType() == Type::getInt1Ty(I.getContext()))
Nick Lewyckyd4b63672008-05-31 17:59:52 +00001640 return ReplaceInstUsesWith(I, Op0);
1641
Nick Lewycky94418732008-11-27 20:21:08 +00001642 if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
1643 if (ConstantInt *X = cast_or_null<ConstantInt>(Op1V->getSplatValue()))
1644 // div X, 1 == X
1645 if (X->isOne())
1646 return ReplaceInstUsesWith(I, Op0);
1647 }
1648
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001649 return 0;
1650}
1651
1652Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
1653 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1654
1655 // Handle the integer div common cases
1656 if (Instruction *Common = commonIDivTransforms(I))
1657 return Common;
1658
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001659 if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
Nick Lewycky240182a2008-11-27 22:41:10 +00001660 // X udiv C^2 -> X >> C
1661 // Check to see if this is an unsigned division with an exact power of 2,
1662 // if so, convert to a right shift.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001663 if (C->getValue().isPowerOf2()) // 0 not included in isPowerOf2
Gabor Greifa645dd32008-05-16 19:29:10 +00001664 return BinaryOperator::CreateLShr(Op0,
Owen Andersoneacb44d2009-07-24 23:12:02 +00001665 ConstantInt::get(Op0->getType(), C->getValue().logBase2()));
Nick Lewycky240182a2008-11-27 22:41:10 +00001666
1667 // X udiv C, where C >= signbit
1668 if (C->getValue().isNegative()) {
Chris Lattnerc7694852009-08-30 07:44:24 +00001669 Value *IC = Builder->CreateICmpULT( Op0, C);
Owen Andersonaac28372009-07-31 20:28:14 +00001670 return SelectInst::Create(IC, Constant::getNullValue(I.getType()),
Owen Andersoneacb44d2009-07-24 23:12:02 +00001671 ConstantInt::get(I.getType(), 1));
Nick Lewycky240182a2008-11-27 22:41:10 +00001672 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001673 }
1674
1675 // X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2)
1676 if (BinaryOperator *RHSI = dyn_cast<BinaryOperator>(I.getOperand(1))) {
1677 if (RHSI->getOpcode() == Instruction::Shl &&
1678 isa<ConstantInt>(RHSI->getOperand(0))) {
1679 const APInt& C1 = cast<ConstantInt>(RHSI->getOperand(0))->getValue();
1680 if (C1.isPowerOf2()) {
1681 Value *N = RHSI->getOperand(1);
1682 const Type *NTy = N->getType();
Chris Lattnerc7694852009-08-30 07:44:24 +00001683 if (uint32_t C2 = C1.logBase2())
1684 N = Builder->CreateAdd(N, ConstantInt::get(NTy, C2), "tmp");
Gabor Greifa645dd32008-05-16 19:29:10 +00001685 return BinaryOperator::CreateLShr(Op0, N);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001686 }
1687 }
1688 }
1689
1690 // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
1691 // where C1&C2 are powers of two.
1692 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
1693 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
1694 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
1695 const APInt &TVA = STO->getValue(), &FVA = SFO->getValue();
1696 if (TVA.isPowerOf2() && FVA.isPowerOf2()) {
1697 // Compute the shift amounts
1698 uint32_t TSA = TVA.logBase2(), FSA = FVA.logBase2();
1699 // Construct the "on true" case of the select
Owen Andersoneacb44d2009-07-24 23:12:02 +00001700 Constant *TC = ConstantInt::get(Op0->getType(), TSA);
Chris Lattnerc7694852009-08-30 07:44:24 +00001701 Value *TSI = Builder->CreateLShr(Op0, TC, SI->getName()+".t");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001702
1703 // Construct the "on false" case of the select
Owen Andersoneacb44d2009-07-24 23:12:02 +00001704 Constant *FC = ConstantInt::get(Op0->getType(), FSA);
Chris Lattnerc7694852009-08-30 07:44:24 +00001705 Value *FSI = Builder->CreateLShr(Op0, FC, SI->getName()+".f");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001706
1707 // construct the select instruction and return it.
Gabor Greifd6da1d02008-04-06 20:25:17 +00001708 return SelectInst::Create(SI->getOperand(0), TSI, FSI, SI->getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001709 }
1710 }
1711 return 0;
1712}
1713
1714Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
1715 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1716
1717 // Handle the integer div common cases
1718 if (Instruction *Common = commonIDivTransforms(I))
1719 return Common;
1720
1721 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
1722 // sdiv X, -1 == -X
1723 if (RHS->isAllOnesValue())
Dan Gohmancdff2122009-08-12 16:23:25 +00001724 return BinaryOperator::CreateNeg(Op0);
Dan Gohman31b6b132009-08-11 20:47:47 +00001725
Dan Gohman07878902009-08-12 16:33:09 +00001726 // sdiv X, C --> ashr X, log2(C)
Dan Gohman31b6b132009-08-11 20:47:47 +00001727 if (cast<SDivOperator>(&I)->isExact() &&
1728 RHS->getValue().isNonNegative() &&
1729 RHS->getValue().isPowerOf2()) {
1730 Value *ShAmt = llvm::ConstantInt::get(RHS->getType(),
1731 RHS->getValue().exactLogBase2());
1732 return BinaryOperator::CreateAShr(Op0, ShAmt, I.getName());
1733 }
Dan Gohman5ce93b32009-08-12 16:37:02 +00001734
1735 // -X/C --> X/-C provided the negation doesn't overflow.
1736 if (SubOperator *Sub = dyn_cast<SubOperator>(Op0))
1737 if (isa<Constant>(Sub->getOperand(0)) &&
1738 cast<Constant>(Sub->getOperand(0))->isNullValue() &&
Dan Gohmanb5ed4492009-08-20 17:11:38 +00001739 Sub->hasNoSignedWrap())
Dan Gohman5ce93b32009-08-12 16:37:02 +00001740 return BinaryOperator::CreateSDiv(Sub->getOperand(1),
1741 ConstantExpr::getNeg(RHS));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001742 }
1743
1744 // If the sign bits of both operands are zero (i.e. we can prove they are
1745 // unsigned inputs), turn this into a udiv.
1746 if (I.getType()->isInteger()) {
1747 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
Eli Friedmana17b85f2009-07-18 09:53:21 +00001748 if (MaskedValueIsZero(Op0, Mask)) {
1749 if (MaskedValueIsZero(Op1, Mask)) {
1750 // X sdiv Y -> X udiv Y, iff X and Y don't have sign bit set
1751 return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
1752 }
1753 ConstantInt *ShiftedInt;
Dan Gohmancdff2122009-08-12 16:23:25 +00001754 if (match(Op1, m_Shl(m_ConstantInt(ShiftedInt), m_Value())) &&
Eli Friedmana17b85f2009-07-18 09:53:21 +00001755 ShiftedInt->getValue().isPowerOf2()) {
1756 // X sdiv (1 << Y) -> X udiv (1 << Y) ( -> X u>> Y)
1757 // Safe because the only negative value (1 << Y) can take on is
1758 // INT_MIN, and X sdiv INT_MIN == X udiv INT_MIN == 0 if X doesn't have
1759 // the sign bit set.
1760 return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
1761 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001762 }
Eli Friedmana17b85f2009-07-18 09:53:21 +00001763 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001764
1765 return 0;
1766}
1767
1768Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
1769 return commonDivTransforms(I);
1770}
1771
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001772/// This function implements the transforms on rem instructions that work
1773/// regardless of the kind of rem instruction it is (urem, srem, or frem). It
1774/// is used by the visitors to those instructions.
1775/// @brief Transforms common to all three rem instructions
1776Instruction *InstCombiner::commonRemTransforms(BinaryOperator &I) {
1777 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1778
Chris Lattner653ef3c2008-02-19 06:12:18 +00001779 if (isa<UndefValue>(Op0)) { // undef % X -> 0
1780 if (I.getType()->isFPOrFPVector())
1781 return ReplaceInstUsesWith(I, Op0); // X % undef -> undef (could be SNaN)
Owen Andersonaac28372009-07-31 20:28:14 +00001782 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner653ef3c2008-02-19 06:12:18 +00001783 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001784 if (isa<UndefValue>(Op1))
1785 return ReplaceInstUsesWith(I, Op1); // X % undef -> undef
1786
1787 // Handle cases involving: rem X, (select Cond, Y, Z)
Chris Lattner76972db2008-07-14 00:15:52 +00001788 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
1789 return &I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001790
1791 return 0;
1792}
1793
1794/// This function implements the transforms common to both integer remainder
1795/// instructions (urem and srem). It is called by the visitors to those integer
1796/// remainder instructions.
1797/// @brief Common integer remainder transforms
1798Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
1799 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1800
1801 if (Instruction *common = commonRemTransforms(I))
1802 return common;
1803
Dale Johannesena51f7372009-01-21 00:35:19 +00001804 // 0 % X == 0 for integer, we don't need to preserve faults!
1805 if (Constant *LHS = dyn_cast<Constant>(Op0))
1806 if (LHS->isNullValue())
Owen Andersonaac28372009-07-31 20:28:14 +00001807 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Dale Johannesena51f7372009-01-21 00:35:19 +00001808
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001809 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
1810 // X % 0 == undef, we don't need to preserve faults!
1811 if (RHS->equalsInt(0))
Owen Andersonb99ecca2009-07-30 23:03:37 +00001812 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001813
1814 if (RHS->equalsInt(1)) // X % 1 == 0
Owen Andersonaac28372009-07-31 20:28:14 +00001815 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001816
1817 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
1818 if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
Chris Lattner54826cd2010-01-04 07:53:58 +00001819 if (Instruction *R = FoldOpIntoSelect(I, SI))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001820 return R;
1821 } else if (isa<PHINode>(Op0I)) {
1822 if (Instruction *NV = FoldOpIntoPhi(I))
1823 return NV;
1824 }
Nick Lewyckyc1372c82008-03-06 06:48:30 +00001825
1826 // See if we can fold away this rem instruction.
Chris Lattner676c78e2009-01-31 08:15:18 +00001827 if (SimplifyDemandedInstructionBits(I))
Nick Lewyckyc1372c82008-03-06 06:48:30 +00001828 return &I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001829 }
1830 }
1831
1832 return 0;
1833}
1834
1835Instruction *InstCombiner::visitURem(BinaryOperator &I) {
1836 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1837
1838 if (Instruction *common = commonIRemTransforms(I))
1839 return common;
1840
1841 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
1842 // X urem C^2 -> X and C
1843 // Check to see if this is an unsigned remainder with an exact power of 2,
1844 // if so, convert to a bitwise and.
1845 if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
1846 if (C->getValue().isPowerOf2())
Dan Gohmanfe91cd62009-08-12 16:04:34 +00001847 return BinaryOperator::CreateAnd(Op0, SubOne(C));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001848 }
1849
1850 if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
1851 // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)
1852 if (RHSI->getOpcode() == Instruction::Shl &&
1853 isa<ConstantInt>(RHSI->getOperand(0))) {
1854 if (cast<ConstantInt>(RHSI->getOperand(0))->getValue().isPowerOf2()) {
Owen Andersonaac28372009-07-31 20:28:14 +00001855 Constant *N1 = Constant::getAllOnesValue(I.getType());
Chris Lattnerc7694852009-08-30 07:44:24 +00001856 Value *Add = Builder->CreateAdd(RHSI, N1, "tmp");
Gabor Greifa645dd32008-05-16 19:29:10 +00001857 return BinaryOperator::CreateAnd(Op0, Add);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001858 }
1859 }
1860 }
1861
1862 // urem X, (select Cond, 2^C1, 2^C2) --> select Cond, (and X, C1), (and X, C2)
1863 // where C1&C2 are powers of two.
1864 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
1865 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
1866 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
1867 // STO == 0 and SFO == 0 handled above.
1868 if ((STO->getValue().isPowerOf2()) &&
1869 (SFO->getValue().isPowerOf2())) {
Chris Lattnerc7694852009-08-30 07:44:24 +00001870 Value *TrueAnd = Builder->CreateAnd(Op0, SubOne(STO),
1871 SI->getName()+".t");
1872 Value *FalseAnd = Builder->CreateAnd(Op0, SubOne(SFO),
1873 SI->getName()+".f");
Gabor Greifd6da1d02008-04-06 20:25:17 +00001874 return SelectInst::Create(SI->getOperand(0), TrueAnd, FalseAnd);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001875 }
1876 }
1877 }
1878
1879 return 0;
1880}
1881
1882Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
1883 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1884
Dan Gohmandb3dd962007-11-05 23:16:33 +00001885 // Handle the integer rem common cases
Chris Lattner4796b622009-08-30 06:22:51 +00001886 if (Instruction *Common = commonIRemTransforms(I))
1887 return Common;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001888
Dan Gohmanfe91cd62009-08-12 16:04:34 +00001889 if (Value *RHSNeg = dyn_castNegVal(Op1))
Nick Lewyckycfadfbd2008-09-03 06:24:21 +00001890 if (!isa<Constant>(RHSNeg) ||
1891 (isa<ConstantInt>(RHSNeg) &&
1892 cast<ConstantInt>(RHSNeg)->getValue().isStrictlyPositive())) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001893 // X % -Y -> X % Y
Chris Lattnerc5ad98f2009-08-30 06:27:41 +00001894 Worklist.AddValue(I.getOperand(1));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001895 I.setOperand(1, RHSNeg);
1896 return &I;
1897 }
Nick Lewycky5515c7a2008-09-30 06:08:34 +00001898
Dan Gohmandb3dd962007-11-05 23:16:33 +00001899 // If the sign bits of both operands are zero (i.e. we can prove they are
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001900 // unsigned inputs), turn this into a urem.
Dan Gohmandb3dd962007-11-05 23:16:33 +00001901 if (I.getType()->isInteger()) {
1902 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
1903 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
1904 // X srem Y -> X urem Y, iff X and Y don't have sign bit set
Gabor Greifa645dd32008-05-16 19:29:10 +00001905 return BinaryOperator::CreateURem(Op0, Op1, I.getName());
Dan Gohmandb3dd962007-11-05 23:16:33 +00001906 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001907 }
1908
Nick Lewyckyda9fa432008-12-18 06:31:11 +00001909 // If it's a constant vector, flip any negative values positive.
Nick Lewyckyfd746832008-12-20 16:48:00 +00001910 if (ConstantVector *RHSV = dyn_cast<ConstantVector>(Op1)) {
1911 unsigned VWidth = RHSV->getNumOperands();
Nick Lewyckyda9fa432008-12-18 06:31:11 +00001912
Nick Lewyckyfd746832008-12-20 16:48:00 +00001913 bool hasNegative = false;
1914 for (unsigned i = 0; !hasNegative && i != VWidth; ++i)
1915 if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i)))
1916 if (RHS->getValue().isNegative())
1917 hasNegative = true;
1918
1919 if (hasNegative) {
1920 std::vector<Constant *> Elts(VWidth);
Nick Lewyckyda9fa432008-12-18 06:31:11 +00001921 for (unsigned i = 0; i != VWidth; ++i) {
1922 if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i))) {
1923 if (RHS->getValue().isNegative())
Owen Anderson02b48c32009-07-29 18:55:55 +00001924 Elts[i] = cast<ConstantInt>(ConstantExpr::getNeg(RHS));
Nick Lewyckyda9fa432008-12-18 06:31:11 +00001925 else
1926 Elts[i] = RHS;
1927 }
1928 }
1929
Owen Anderson2f422e02009-07-28 21:19:26 +00001930 Constant *NewRHSV = ConstantVector::get(Elts);
Nick Lewyckyda9fa432008-12-18 06:31:11 +00001931 if (NewRHSV != RHSV) {
Chris Lattnerc5ad98f2009-08-30 06:27:41 +00001932 Worklist.AddValue(I.getOperand(1));
Nick Lewyckyda9fa432008-12-18 06:31:11 +00001933 I.setOperand(1, NewRHSV);
1934 return &I;
1935 }
1936 }
1937 }
1938
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001939 return 0;
1940}
1941
1942Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
1943 return commonRemTransforms(I);
1944}
1945
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001946/// getICmpCode - Encode a icmp predicate into a three bit mask. These bits
1947/// are carefully arranged to allow folding of expressions such as:
1948///
1949/// (A < B) | (A > B) --> (A != B)
1950///
1951/// Note that this is only valid if the first and second predicates have the
1952/// same sign. Is illegal to do: (A u< B) | (A s> B)
1953///
1954/// Three bits are used to represent the condition, as follows:
1955/// 0 A > B
1956/// 1 A == B
1957/// 2 A < B
1958///
1959/// <=> Value Definition
1960/// 000 0 Always false
1961/// 001 1 A > B
1962/// 010 2 A == B
1963/// 011 3 A >= B
1964/// 100 4 A < B
1965/// 101 5 A != B
1966/// 110 6 A <= B
1967/// 111 7 Always true
1968///
1969static unsigned getICmpCode(const ICmpInst *ICI) {
1970 switch (ICI->getPredicate()) {
1971 // False -> 0
1972 case ICmpInst::ICMP_UGT: return 1; // 001
1973 case ICmpInst::ICMP_SGT: return 1; // 001
1974 case ICmpInst::ICMP_EQ: return 2; // 010
1975 case ICmpInst::ICMP_UGE: return 3; // 011
1976 case ICmpInst::ICMP_SGE: return 3; // 011
1977 case ICmpInst::ICMP_ULT: return 4; // 100
1978 case ICmpInst::ICMP_SLT: return 4; // 100
1979 case ICmpInst::ICMP_NE: return 5; // 101
1980 case ICmpInst::ICMP_ULE: return 6; // 110
1981 case ICmpInst::ICMP_SLE: return 6; // 110
1982 // True -> 7
1983 default:
Edwin Törökbd448e32009-07-14 16:55:14 +00001984 llvm_unreachable("Invalid ICmp predicate!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001985 return 0;
1986 }
1987}
1988
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00001989/// getFCmpCode - Similar to getICmpCode but for FCmpInst. This encodes a fcmp
1990/// predicate into a three bit mask. It also returns whether it is an ordered
1991/// predicate by reference.
1992static unsigned getFCmpCode(FCmpInst::Predicate CC, bool &isOrdered) {
1993 isOrdered = false;
1994 switch (CC) {
1995 case FCmpInst::FCMP_ORD: isOrdered = true; return 0; // 000
1996 case FCmpInst::FCMP_UNO: return 0; // 000
Evan Chengf1f2cea2008-10-14 18:13:38 +00001997 case FCmpInst::FCMP_OGT: isOrdered = true; return 1; // 001
1998 case FCmpInst::FCMP_UGT: return 1; // 001
1999 case FCmpInst::FCMP_OEQ: isOrdered = true; return 2; // 010
2000 case FCmpInst::FCMP_UEQ: return 2; // 010
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00002001 case FCmpInst::FCMP_OGE: isOrdered = true; return 3; // 011
2002 case FCmpInst::FCMP_UGE: return 3; // 011
2003 case FCmpInst::FCMP_OLT: isOrdered = true; return 4; // 100
2004 case FCmpInst::FCMP_ULT: return 4; // 100
Evan Chengf1f2cea2008-10-14 18:13:38 +00002005 case FCmpInst::FCMP_ONE: isOrdered = true; return 5; // 101
2006 case FCmpInst::FCMP_UNE: return 5; // 101
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00002007 case FCmpInst::FCMP_OLE: isOrdered = true; return 6; // 110
2008 case FCmpInst::FCMP_ULE: return 6; // 110
Evan Cheng72988052008-10-14 18:44:08 +00002009 // True -> 7
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00002010 default:
2011 // Not expecting FCMP_FALSE and FCMP_TRUE;
Edwin Törökbd448e32009-07-14 16:55:14 +00002012 llvm_unreachable("Unexpected FCmp predicate!");
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00002013 return 0;
2014 }
2015}
2016
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002017/// getICmpValue - This is the complement of getICmpCode, which turns an
2018/// opcode and two operands into either a constant true or false, or a brand
Dan Gohmanda338742007-09-17 17:31:57 +00002019/// new ICmp instruction. The sign is passed in to determine which kind
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00002020/// of predicate to use in the new icmp instruction.
Chris Lattner03a27b42010-01-04 07:02:48 +00002021static Value *getICmpValue(bool sign, unsigned code, Value *LHS, Value *RHS) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002022 switch (code) {
Edwin Törökbd448e32009-07-14 16:55:14 +00002023 default: llvm_unreachable("Illegal ICmp code!");
Chris Lattner03a27b42010-01-04 07:02:48 +00002024 case 0: return ConstantInt::getFalse(LHS->getContext());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002025 case 1:
2026 if (sign)
Dan Gohmane6803b82009-08-25 23:17:54 +00002027 return new ICmpInst(ICmpInst::ICMP_SGT, LHS, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002028 else
Dan Gohmane6803b82009-08-25 23:17:54 +00002029 return new ICmpInst(ICmpInst::ICMP_UGT, LHS, RHS);
2030 case 2: return new ICmpInst(ICmpInst::ICMP_EQ, LHS, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002031 case 3:
2032 if (sign)
Dan Gohmane6803b82009-08-25 23:17:54 +00002033 return new ICmpInst(ICmpInst::ICMP_SGE, LHS, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002034 else
Dan Gohmane6803b82009-08-25 23:17:54 +00002035 return new ICmpInst(ICmpInst::ICMP_UGE, LHS, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002036 case 4:
2037 if (sign)
Dan Gohmane6803b82009-08-25 23:17:54 +00002038 return new ICmpInst(ICmpInst::ICMP_SLT, LHS, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002039 else
Dan Gohmane6803b82009-08-25 23:17:54 +00002040 return new ICmpInst(ICmpInst::ICMP_ULT, LHS, RHS);
2041 case 5: return new ICmpInst(ICmpInst::ICMP_NE, LHS, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002042 case 6:
2043 if (sign)
Dan Gohmane6803b82009-08-25 23:17:54 +00002044 return new ICmpInst(ICmpInst::ICMP_SLE, LHS, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002045 else
Dan Gohmane6803b82009-08-25 23:17:54 +00002046 return new ICmpInst(ICmpInst::ICMP_ULE, LHS, RHS);
Chris Lattner03a27b42010-01-04 07:02:48 +00002047 case 7: return ConstantInt::getTrue(LHS->getContext());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002048 }
2049}
2050
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00002051/// getFCmpValue - This is the complement of getFCmpCode, which turns an
2052/// opcode and two operands into either a FCmp instruction. isordered is passed
2053/// in to determine which kind of predicate to use in the new fcmp instruction.
2054static Value *getFCmpValue(bool isordered, unsigned code,
Chris Lattner03a27b42010-01-04 07:02:48 +00002055 Value *LHS, Value *RHS) {
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00002056 switch (code) {
Edwin Törökbd448e32009-07-14 16:55:14 +00002057 default: llvm_unreachable("Illegal FCmp code!");
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00002058 case 0:
2059 if (isordered)
Dan Gohmane6803b82009-08-25 23:17:54 +00002060 return new FCmpInst(FCmpInst::FCMP_ORD, LHS, RHS);
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00002061 else
Dan Gohmane6803b82009-08-25 23:17:54 +00002062 return new FCmpInst(FCmpInst::FCMP_UNO, LHS, RHS);
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00002063 case 1:
2064 if (isordered)
Dan Gohmane6803b82009-08-25 23:17:54 +00002065 return new FCmpInst(FCmpInst::FCMP_OGT, LHS, RHS);
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00002066 else
Dan Gohmane6803b82009-08-25 23:17:54 +00002067 return new FCmpInst(FCmpInst::FCMP_UGT, LHS, RHS);
Evan Chengf1f2cea2008-10-14 18:13:38 +00002068 case 2:
2069 if (isordered)
Dan Gohmane6803b82009-08-25 23:17:54 +00002070 return new FCmpInst(FCmpInst::FCMP_OEQ, LHS, RHS);
Evan Chengf1f2cea2008-10-14 18:13:38 +00002071 else
Dan Gohmane6803b82009-08-25 23:17:54 +00002072 return new FCmpInst(FCmpInst::FCMP_UEQ, LHS, RHS);
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00002073 case 3:
2074 if (isordered)
Dan Gohmane6803b82009-08-25 23:17:54 +00002075 return new FCmpInst(FCmpInst::FCMP_OGE, LHS, RHS);
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00002076 else
Dan Gohmane6803b82009-08-25 23:17:54 +00002077 return new FCmpInst(FCmpInst::FCMP_UGE, LHS, RHS);
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00002078 case 4:
2079 if (isordered)
Dan Gohmane6803b82009-08-25 23:17:54 +00002080 return new FCmpInst(FCmpInst::FCMP_OLT, LHS, RHS);
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00002081 else
Dan Gohmane6803b82009-08-25 23:17:54 +00002082 return new FCmpInst(FCmpInst::FCMP_ULT, LHS, RHS);
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00002083 case 5:
2084 if (isordered)
Dan Gohmane6803b82009-08-25 23:17:54 +00002085 return new FCmpInst(FCmpInst::FCMP_ONE, LHS, RHS);
Evan Chengf1f2cea2008-10-14 18:13:38 +00002086 else
Dan Gohmane6803b82009-08-25 23:17:54 +00002087 return new FCmpInst(FCmpInst::FCMP_UNE, LHS, RHS);
Evan Chengf1f2cea2008-10-14 18:13:38 +00002088 case 6:
2089 if (isordered)
Dan Gohmane6803b82009-08-25 23:17:54 +00002090 return new FCmpInst(FCmpInst::FCMP_OLE, LHS, RHS);
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00002091 else
Dan Gohmane6803b82009-08-25 23:17:54 +00002092 return new FCmpInst(FCmpInst::FCMP_ULE, LHS, RHS);
Chris Lattner03a27b42010-01-04 07:02:48 +00002093 case 7: return ConstantInt::getTrue(LHS->getContext());
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00002094 }
2095}
2096
Chris Lattner2972b822008-11-16 04:55:20 +00002097/// PredicatesFoldable - Return true if both predicates match sign or if at
2098/// least one of them is an equality comparison (which is signless).
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002099static bool PredicatesFoldable(ICmpInst::Predicate p1, ICmpInst::Predicate p2) {
Nick Lewyckyb0796c62009-10-25 05:20:17 +00002100 return (CmpInst::isSigned(p1) == CmpInst::isSigned(p2)) ||
2101 (CmpInst::isSigned(p1) && ICmpInst::isEquality(p2)) ||
2102 (CmpInst::isSigned(p2) && ICmpInst::isEquality(p1));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002103}
2104
2105namespace {
2106// FoldICmpLogical - Implements (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
2107struct FoldICmpLogical {
2108 InstCombiner &IC;
2109 Value *LHS, *RHS;
2110 ICmpInst::Predicate pred;
2111 FoldICmpLogical(InstCombiner &ic, ICmpInst *ICI)
2112 : IC(ic), LHS(ICI->getOperand(0)), RHS(ICI->getOperand(1)),
2113 pred(ICI->getPredicate()) {}
2114 bool shouldApply(Value *V) const {
2115 if (ICmpInst *ICI = dyn_cast<ICmpInst>(V))
2116 if (PredicatesFoldable(pred, ICI->getPredicate()))
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00002117 return ((ICI->getOperand(0) == LHS && ICI->getOperand(1) == RHS) ||
2118 (ICI->getOperand(0) == RHS && ICI->getOperand(1) == LHS));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002119 return false;
2120 }
2121 Instruction *apply(Instruction &Log) const {
2122 ICmpInst *ICI = cast<ICmpInst>(Log.getOperand(0));
2123 if (ICI->getOperand(0) != LHS) {
2124 assert(ICI->getOperand(1) == LHS);
2125 ICI->swapOperands(); // Swap the LHS and RHS of the ICmp
2126 }
2127
2128 ICmpInst *RHSICI = cast<ICmpInst>(Log.getOperand(1));
2129 unsigned LHSCode = getICmpCode(ICI);
2130 unsigned RHSCode = getICmpCode(RHSICI);
2131 unsigned Code;
2132 switch (Log.getOpcode()) {
2133 case Instruction::And: Code = LHSCode & RHSCode; break;
2134 case Instruction::Or: Code = LHSCode | RHSCode; break;
2135 case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
Edwin Törökbd448e32009-07-14 16:55:14 +00002136 default: llvm_unreachable("Illegal logical opcode!"); return 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002137 }
2138
Nick Lewyckyb0796c62009-10-25 05:20:17 +00002139 bool isSigned = RHSICI->isSigned() || ICI->isSigned();
Chris Lattner03a27b42010-01-04 07:02:48 +00002140 Value *RV = getICmpValue(isSigned, Code, LHS, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002141 if (Instruction *I = dyn_cast<Instruction>(RV))
2142 return I;
2143 // Otherwise, it's a constant boolean value...
2144 return IC.ReplaceInstUsesWith(Log, RV);
2145 }
2146};
2147} // end anonymous namespace
2148
2149// OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
2150// the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
2151// guaranteed to be a binary operator.
2152Instruction *InstCombiner::OptAndOp(Instruction *Op,
2153 ConstantInt *OpRHS,
2154 ConstantInt *AndRHS,
2155 BinaryOperator &TheAnd) {
2156 Value *X = Op->getOperand(0);
2157 Constant *Together = 0;
2158 if (!Op->isShift())
Owen Anderson02b48c32009-07-29 18:55:55 +00002159 Together = ConstantExpr::getAnd(AndRHS, OpRHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002160
2161 switch (Op->getOpcode()) {
2162 case Instruction::Xor:
2163 if (Op->hasOneUse()) {
2164 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
Chris Lattnerc7694852009-08-30 07:44:24 +00002165 Value *And = Builder->CreateAnd(X, AndRHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002166 And->takeName(Op);
Gabor Greifa645dd32008-05-16 19:29:10 +00002167 return BinaryOperator::CreateXor(And, Together);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002168 }
2169 break;
2170 case Instruction::Or:
2171 if (Together == AndRHS) // (X | C) & C --> C
2172 return ReplaceInstUsesWith(TheAnd, AndRHS);
2173
2174 if (Op->hasOneUse() && Together != OpRHS) {
2175 // (X | C1) & C2 --> (X | (C1&C2)) & C2
Chris Lattnerc7694852009-08-30 07:44:24 +00002176 Value *Or = Builder->CreateOr(X, Together);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002177 Or->takeName(Op);
Gabor Greifa645dd32008-05-16 19:29:10 +00002178 return BinaryOperator::CreateAnd(Or, AndRHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002179 }
2180 break;
2181 case Instruction::Add:
2182 if (Op->hasOneUse()) {
2183 // Adding a one to a single bit bit-field should be turned into an XOR
2184 // of the bit. First thing to check is to see if this AND is with a
2185 // single bit constant.
Chris Lattner77fe28f2010-01-05 06:03:12 +00002186 const APInt &AndRHSV = cast<ConstantInt>(AndRHS)->getValue();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002187
Chris Lattner77fe28f2010-01-05 06:03:12 +00002188 // If there is only one bit set.
2189 if (AndRHSV.isPowerOf2()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002190 // Ok, at this point, we know that we are masking the result of the
2191 // ADD down to exactly one bit. If the constant we are adding has
2192 // no bits set below this bit, then we can eliminate the ADD.
2193 const APInt& AddRHS = cast<ConstantInt>(OpRHS)->getValue();
2194
2195 // Check to see if any bits below the one bit set in AndRHSV are set.
2196 if ((AddRHS & (AndRHSV-1)) == 0) {
2197 // If not, the only thing that can effect the output of the AND is
2198 // the bit specified by AndRHSV. If that bit is set, the effect of
2199 // the XOR is to toggle the bit. If it is clear, then the ADD has
2200 // no effect.
2201 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
2202 TheAnd.setOperand(0, X);
2203 return &TheAnd;
2204 } else {
2205 // Pull the XOR out of the AND.
Chris Lattnerc7694852009-08-30 07:44:24 +00002206 Value *NewAnd = Builder->CreateAnd(X, AndRHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002207 NewAnd->takeName(Op);
Gabor Greifa645dd32008-05-16 19:29:10 +00002208 return BinaryOperator::CreateXor(NewAnd, AndRHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002209 }
2210 }
2211 }
2212 }
2213 break;
2214
2215 case Instruction::Shl: {
2216 // We know that the AND will not produce any of the bits shifted in, so if
2217 // the anded constant includes them, clear them now!
2218 //
2219 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
2220 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
2221 APInt ShlMask(APInt::getHighBitsSet(BitWidth, BitWidth-OpRHSVal));
Chris Lattner03a27b42010-01-04 07:02:48 +00002222 ConstantInt *CI = ConstantInt::get(AndRHS->getContext(),
2223 AndRHS->getValue() & ShlMask);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002224
2225 if (CI->getValue() == ShlMask) {
2226 // Masking out bits that the shift already masks
2227 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
2228 } else if (CI != AndRHS) { // Reducing bits set in and.
2229 TheAnd.setOperand(1, CI);
2230 return &TheAnd;
2231 }
2232 break;
2233 }
Chris Lattner03a27b42010-01-04 07:02:48 +00002234 case Instruction::LShr: {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002235 // We know that the AND will not produce any of the bits shifted in, so if
2236 // the anded constant includes them, clear them now! This only applies to
2237 // unsigned shifts, because a signed shr may bring in set bits!
2238 //
2239 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
2240 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
2241 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
Chris Lattner03a27b42010-01-04 07:02:48 +00002242 ConstantInt *CI = ConstantInt::get(Op->getContext(),
2243 AndRHS->getValue() & ShrMask);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002244
2245 if (CI->getValue() == ShrMask) {
2246 // Masking out bits that the shift already masks.
2247 return ReplaceInstUsesWith(TheAnd, Op);
2248 } else if (CI != AndRHS) {
2249 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
2250 return &TheAnd;
2251 }
2252 break;
2253 }
2254 case Instruction::AShr:
2255 // Signed shr.
2256 // See if this is shifting in some sign extension, then masking it out
2257 // with an and.
2258 if (Op->hasOneUse()) {
2259 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
2260 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
2261 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
Chris Lattner03a27b42010-01-04 07:02:48 +00002262 Constant *C = ConstantInt::get(Op->getContext(),
2263 AndRHS->getValue() & ShrMask);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002264 if (C == AndRHS) { // Masking out bits shifted in.
2265 // (Val ashr C1) & C2 -> (Val lshr C1) & C2
2266 // Make the argument unsigned.
2267 Value *ShVal = Op->getOperand(0);
Chris Lattnerc7694852009-08-30 07:44:24 +00002268 ShVal = Builder->CreateLShr(ShVal, OpRHS, Op->getName());
Gabor Greifa645dd32008-05-16 19:29:10 +00002269 return BinaryOperator::CreateAnd(ShVal, AndRHS, TheAnd.getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002270 }
2271 }
2272 break;
2273 }
2274 return 0;
2275}
2276
2277
2278/// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
2279/// true, otherwise (V < Lo || V >= Hi). In pratice, we emit the more efficient
2280/// (V-Lo) <u Hi-Lo. This method expects that Lo <= Hi. isSigned indicates
2281/// whether to treat the V, Lo and HI as signed or not. IB is the location to
2282/// insert new instructions.
2283Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
2284 bool isSigned, bool Inside,
2285 Instruction &IB) {
Owen Anderson02b48c32009-07-29 18:55:55 +00002286 assert(cast<ConstantInt>(ConstantExpr::getICmp((isSigned ?
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002287 ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
2288 "Lo is not <= Hi in range emission code!");
2289
2290 if (Inside) {
2291 if (Lo == Hi) // Trivially false.
Dan Gohmane6803b82009-08-25 23:17:54 +00002292 return new ICmpInst(ICmpInst::ICMP_NE, V, V);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002293
2294 // V >= Min && V < Hi --> V < Hi
2295 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
2296 ICmpInst::Predicate pred = (isSigned ?
2297 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
Dan Gohmane6803b82009-08-25 23:17:54 +00002298 return new ICmpInst(pred, V, Hi);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002299 }
2300
2301 // Emit V-Lo <u Hi-Lo
Owen Anderson02b48c32009-07-29 18:55:55 +00002302 Constant *NegLo = ConstantExpr::getNeg(Lo);
Chris Lattnerc7694852009-08-30 07:44:24 +00002303 Value *Add = Builder->CreateAdd(V, NegLo, V->getName()+".off");
Owen Anderson02b48c32009-07-29 18:55:55 +00002304 Constant *UpperBound = ConstantExpr::getAdd(NegLo, Hi);
Dan Gohmane6803b82009-08-25 23:17:54 +00002305 return new ICmpInst(ICmpInst::ICMP_ULT, Add, UpperBound);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002306 }
2307
2308 if (Lo == Hi) // Trivially true.
Dan Gohmane6803b82009-08-25 23:17:54 +00002309 return new ICmpInst(ICmpInst::ICMP_EQ, V, V);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002310
2311 // V < Min || V >= Hi -> V > Hi-1
Dan Gohmanfe91cd62009-08-12 16:04:34 +00002312 Hi = SubOne(cast<ConstantInt>(Hi));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002313 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
2314 ICmpInst::Predicate pred = (isSigned ?
2315 ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
Dan Gohmane6803b82009-08-25 23:17:54 +00002316 return new ICmpInst(pred, V, Hi);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002317 }
2318
2319 // Emit V-Lo >u Hi-1-Lo
2320 // Note that Hi has already had one subtracted from it, above.
Owen Anderson02b48c32009-07-29 18:55:55 +00002321 ConstantInt *NegLo = cast<ConstantInt>(ConstantExpr::getNeg(Lo));
Chris Lattnerc7694852009-08-30 07:44:24 +00002322 Value *Add = Builder->CreateAdd(V, NegLo, V->getName()+".off");
Owen Anderson02b48c32009-07-29 18:55:55 +00002323 Constant *LowerBound = ConstantExpr::getAdd(NegLo, Hi);
Dan Gohmane6803b82009-08-25 23:17:54 +00002324 return new ICmpInst(ICmpInst::ICMP_UGT, Add, LowerBound);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002325}
2326
2327// isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
2328// any number of 0s on either side. The 1s are allowed to wrap from LSB to
2329// MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs. 0x0F0F0000 is
2330// not, since all 1s are not contiguous.
2331static bool isRunOfOnes(ConstantInt *Val, uint32_t &MB, uint32_t &ME) {
2332 const APInt& V = Val->getValue();
2333 uint32_t BitWidth = Val->getType()->getBitWidth();
2334 if (!APIntOps::isShiftedMask(BitWidth, V)) return false;
2335
2336 // look for the first zero bit after the run of ones
2337 MB = BitWidth - ((V - 1) ^ V).countLeadingZeros();
2338 // look for the first non-zero bit
2339 ME = V.getActiveBits();
2340 return true;
2341}
2342
2343/// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
2344/// where isSub determines whether the operator is a sub. If we can fold one of
2345/// the following xforms:
2346///
2347/// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
2348/// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
2349/// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
2350///
2351/// return (A +/- B).
2352///
2353Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
2354 ConstantInt *Mask, bool isSub,
2355 Instruction &I) {
2356 Instruction *LHSI = dyn_cast<Instruction>(LHS);
2357 if (!LHSI || LHSI->getNumOperands() != 2 ||
2358 !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
2359
2360 ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
2361
2362 switch (LHSI->getOpcode()) {
2363 default: return 0;
2364 case Instruction::And:
Owen Anderson02b48c32009-07-29 18:55:55 +00002365 if (ConstantExpr::getAnd(N, Mask) == Mask) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002366 // If the AndRHS is a power of two minus one (0+1+), this is simple.
2367 if ((Mask->getValue().countLeadingZeros() +
2368 Mask->getValue().countPopulation()) ==
2369 Mask->getValue().getBitWidth())
2370 break;
2371
2372 // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
2373 // part, we don't need any explicit masks to take them out of A. If that
2374 // is all N is, ignore it.
2375 uint32_t MB = 0, ME = 0;
2376 if (isRunOfOnes(Mask, MB, ME)) { // begin/end bit of run, inclusive
2377 uint32_t BitWidth = cast<IntegerType>(RHS->getType())->getBitWidth();
2378 APInt Mask(APInt::getLowBitsSet(BitWidth, MB-1));
2379 if (MaskedValueIsZero(RHS, Mask))
2380 break;
2381 }
2382 }
2383 return 0;
2384 case Instruction::Or:
2385 case Instruction::Xor:
2386 // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
2387 if ((Mask->getValue().countLeadingZeros() +
2388 Mask->getValue().countPopulation()) == Mask->getValue().getBitWidth()
Owen Anderson02b48c32009-07-29 18:55:55 +00002389 && ConstantExpr::getAnd(N, Mask)->isNullValue())
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002390 break;
2391 return 0;
2392 }
2393
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002394 if (isSub)
Chris Lattnerc7694852009-08-30 07:44:24 +00002395 return Builder->CreateSub(LHSI->getOperand(0), RHS, "fold");
2396 return Builder->CreateAdd(LHSI->getOperand(0), RHS, "fold");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002397}
2398
Chris Lattner0631ea72008-11-16 05:06:21 +00002399/// FoldAndOfICmps - Fold (icmp)&(icmp) if possible.
2400Instruction *InstCombiner::FoldAndOfICmps(Instruction &I,
2401 ICmpInst *LHS, ICmpInst *RHS) {
Chris Lattnerf3803482008-11-16 05:10:52 +00002402 Value *Val, *Val2;
Chris Lattner0631ea72008-11-16 05:06:21 +00002403 ConstantInt *LHSCst, *RHSCst;
2404 ICmpInst::Predicate LHSCC, RHSCC;
2405
Chris Lattnerf3803482008-11-16 05:10:52 +00002406 // This only handles icmp of constants: (icmp1 A, C1) & (icmp2 B, C2).
Owen Andersona21eb582009-07-10 17:35:01 +00002407 if (!match(LHS, m_ICmp(LHSCC, m_Value(Val),
Dan Gohmancdff2122009-08-12 16:23:25 +00002408 m_ConstantInt(LHSCst))) ||
Owen Andersona21eb582009-07-10 17:35:01 +00002409 !match(RHS, m_ICmp(RHSCC, m_Value(Val2),
Dan Gohmancdff2122009-08-12 16:23:25 +00002410 m_ConstantInt(RHSCst))))
Chris Lattner0631ea72008-11-16 05:06:21 +00002411 return 0;
Chris Lattnerf3803482008-11-16 05:10:52 +00002412
Chris Lattner163e6ab2009-11-29 00:51:17 +00002413 if (LHSCst == RHSCst && LHSCC == RHSCC) {
2414 // (icmp ult A, C) & (icmp ult B, C) --> (icmp ult (A|B), C)
2415 // where C is a power of 2
2416 if (LHSCC == ICmpInst::ICMP_ULT &&
2417 LHSCst->getValue().isPowerOf2()) {
2418 Value *NewOr = Builder->CreateOr(Val, Val2);
2419 return new ICmpInst(LHSCC, NewOr, LHSCst);
2420 }
2421
2422 // (icmp eq A, 0) & (icmp eq B, 0) --> (icmp eq (A|B), 0)
2423 if (LHSCC == ICmpInst::ICMP_EQ && LHSCst->isZero()) {
2424 Value *NewOr = Builder->CreateOr(Val, Val2);
2425 return new ICmpInst(LHSCC, NewOr, LHSCst);
2426 }
Chris Lattnerf3803482008-11-16 05:10:52 +00002427 }
2428
2429 // From here on, we only handle:
2430 // (icmp1 A, C1) & (icmp2 A, C2) --> something simpler.
2431 if (Val != Val2) return 0;
2432
Chris Lattner0631ea72008-11-16 05:06:21 +00002433 // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
2434 if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
2435 RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
2436 LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
2437 RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
2438 return 0;
2439
2440 // We can't fold (ugt x, C) & (sgt x, C2).
2441 if (!PredicatesFoldable(LHSCC, RHSCC))
2442 return 0;
2443
2444 // Ensure that the larger constant is on the RHS.
Chris Lattner665298f2008-11-16 05:14:43 +00002445 bool ShouldSwap;
Nick Lewyckyb0796c62009-10-25 05:20:17 +00002446 if (CmpInst::isSigned(LHSCC) ||
Chris Lattner0631ea72008-11-16 05:06:21 +00002447 (ICmpInst::isEquality(LHSCC) &&
Nick Lewyckyb0796c62009-10-25 05:20:17 +00002448 CmpInst::isSigned(RHSCC)))
Chris Lattner665298f2008-11-16 05:14:43 +00002449 ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
Chris Lattner0631ea72008-11-16 05:06:21 +00002450 else
Chris Lattner665298f2008-11-16 05:14:43 +00002451 ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
2452
2453 if (ShouldSwap) {
Chris Lattner0631ea72008-11-16 05:06:21 +00002454 std::swap(LHS, RHS);
2455 std::swap(LHSCst, RHSCst);
2456 std::swap(LHSCC, RHSCC);
2457 }
2458
2459 // At this point, we know we have have two icmp instructions
2460 // comparing a value against two constants and and'ing the result
2461 // together. Because of the above check, we know that we only have
2462 // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know
2463 // (from the FoldICmpLogical check above), that the two constants
2464 // are not equal and that the larger constant is on the RHS
2465 assert(LHSCst != RHSCst && "Compares not folded above?");
2466
2467 switch (LHSCC) {
Edwin Törökbd448e32009-07-14 16:55:14 +00002468 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner0631ea72008-11-16 05:06:21 +00002469 case ICmpInst::ICMP_EQ:
2470 switch (RHSCC) {
Edwin Törökbd448e32009-07-14 16:55:14 +00002471 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner0631ea72008-11-16 05:06:21 +00002472 case ICmpInst::ICMP_EQ: // (X == 13 & X == 15) -> false
2473 case ICmpInst::ICMP_UGT: // (X == 13 & X > 15) -> false
2474 case ICmpInst::ICMP_SGT: // (X == 13 & X > 15) -> false
Chris Lattner03a27b42010-01-04 07:02:48 +00002475 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getContext()));
Chris Lattner0631ea72008-11-16 05:06:21 +00002476 case ICmpInst::ICMP_NE: // (X == 13 & X != 15) -> X == 13
2477 case ICmpInst::ICMP_ULT: // (X == 13 & X < 15) -> X == 13
2478 case ICmpInst::ICMP_SLT: // (X == 13 & X < 15) -> X == 13
2479 return ReplaceInstUsesWith(I, LHS);
2480 }
2481 case ICmpInst::ICMP_NE:
2482 switch (RHSCC) {
Edwin Törökbd448e32009-07-14 16:55:14 +00002483 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner0631ea72008-11-16 05:06:21 +00002484 case ICmpInst::ICMP_ULT:
Dan Gohmanfe91cd62009-08-12 16:04:34 +00002485 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X u< 14) -> X < 13
Dan Gohmane6803b82009-08-25 23:17:54 +00002486 return new ICmpInst(ICmpInst::ICMP_ULT, Val, LHSCst);
Chris Lattner0631ea72008-11-16 05:06:21 +00002487 break; // (X != 13 & X u< 15) -> no change
2488 case ICmpInst::ICMP_SLT:
Dan Gohmanfe91cd62009-08-12 16:04:34 +00002489 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X s< 14) -> X < 13
Dan Gohmane6803b82009-08-25 23:17:54 +00002490 return new ICmpInst(ICmpInst::ICMP_SLT, Val, LHSCst);
Chris Lattner0631ea72008-11-16 05:06:21 +00002491 break; // (X != 13 & X s< 15) -> no change
2492 case ICmpInst::ICMP_EQ: // (X != 13 & X == 15) -> X == 15
2493 case ICmpInst::ICMP_UGT: // (X != 13 & X u> 15) -> X u> 15
2494 case ICmpInst::ICMP_SGT: // (X != 13 & X s> 15) -> X s> 15
2495 return ReplaceInstUsesWith(I, RHS);
2496 case ICmpInst::ICMP_NE:
Dan Gohmanfe91cd62009-08-12 16:04:34 +00002497 if (LHSCst == SubOne(RHSCst)){// (X != 13 & X != 14) -> X-13 >u 1
Owen Anderson02b48c32009-07-29 18:55:55 +00002498 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
Chris Lattnerc7694852009-08-30 07:44:24 +00002499 Value *Add = Builder->CreateAdd(Val, AddCST, Val->getName()+".off");
Dan Gohmane6803b82009-08-25 23:17:54 +00002500 return new ICmpInst(ICmpInst::ICMP_UGT, Add,
Owen Andersoneacb44d2009-07-24 23:12:02 +00002501 ConstantInt::get(Add->getType(), 1));
Chris Lattner0631ea72008-11-16 05:06:21 +00002502 }
2503 break; // (X != 13 & X != 15) -> no change
2504 }
2505 break;
2506 case ICmpInst::ICMP_ULT:
2507 switch (RHSCC) {
Edwin Törökbd448e32009-07-14 16:55:14 +00002508 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner0631ea72008-11-16 05:06:21 +00002509 case ICmpInst::ICMP_EQ: // (X u< 13 & X == 15) -> false
2510 case ICmpInst::ICMP_UGT: // (X u< 13 & X u> 15) -> false
Chris Lattner03a27b42010-01-04 07:02:48 +00002511 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getContext()));
Chris Lattner0631ea72008-11-16 05:06:21 +00002512 case ICmpInst::ICMP_SGT: // (X u< 13 & X s> 15) -> no change
2513 break;
2514 case ICmpInst::ICMP_NE: // (X u< 13 & X != 15) -> X u< 13
2515 case ICmpInst::ICMP_ULT: // (X u< 13 & X u< 15) -> X u< 13
2516 return ReplaceInstUsesWith(I, LHS);
2517 case ICmpInst::ICMP_SLT: // (X u< 13 & X s< 15) -> no change
2518 break;
2519 }
2520 break;
2521 case ICmpInst::ICMP_SLT:
2522 switch (RHSCC) {
Edwin Törökbd448e32009-07-14 16:55:14 +00002523 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner0631ea72008-11-16 05:06:21 +00002524 case ICmpInst::ICMP_EQ: // (X s< 13 & X == 15) -> false
2525 case ICmpInst::ICMP_SGT: // (X s< 13 & X s> 15) -> false
Chris Lattner03a27b42010-01-04 07:02:48 +00002526 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getContext()));
Chris Lattner0631ea72008-11-16 05:06:21 +00002527 case ICmpInst::ICMP_UGT: // (X s< 13 & X u> 15) -> no change
2528 break;
2529 case ICmpInst::ICMP_NE: // (X s< 13 & X != 15) -> X < 13
2530 case ICmpInst::ICMP_SLT: // (X s< 13 & X s< 15) -> X < 13
2531 return ReplaceInstUsesWith(I, LHS);
2532 case ICmpInst::ICMP_ULT: // (X s< 13 & X u< 15) -> no change
2533 break;
2534 }
2535 break;
2536 case ICmpInst::ICMP_UGT:
2537 switch (RHSCC) {
Edwin Törökbd448e32009-07-14 16:55:14 +00002538 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner0631ea72008-11-16 05:06:21 +00002539 case ICmpInst::ICMP_EQ: // (X u> 13 & X == 15) -> X == 15
2540 case ICmpInst::ICMP_UGT: // (X u> 13 & X u> 15) -> X u> 15
2541 return ReplaceInstUsesWith(I, RHS);
2542 case ICmpInst::ICMP_SGT: // (X u> 13 & X s> 15) -> no change
2543 break;
2544 case ICmpInst::ICMP_NE:
Dan Gohmanfe91cd62009-08-12 16:04:34 +00002545 if (RHSCst == AddOne(LHSCst)) // (X u> 13 & X != 14) -> X u> 14
Dan Gohmane6803b82009-08-25 23:17:54 +00002546 return new ICmpInst(LHSCC, Val, RHSCst);
Chris Lattner0631ea72008-11-16 05:06:21 +00002547 break; // (X u> 13 & X != 15) -> no change
Chris Lattner0c678e52008-11-16 05:20:07 +00002548 case ICmpInst::ICMP_ULT: // (X u> 13 & X u< 15) -> (X-14) <u 1
Dan Gohmanfe91cd62009-08-12 16:04:34 +00002549 return InsertRangeTest(Val, AddOne(LHSCst),
Owen Anderson24be4c12009-07-03 00:17:18 +00002550 RHSCst, false, true, I);
Chris Lattner0631ea72008-11-16 05:06:21 +00002551 case ICmpInst::ICMP_SLT: // (X u> 13 & X s< 15) -> no change
2552 break;
2553 }
2554 break;
2555 case ICmpInst::ICMP_SGT:
2556 switch (RHSCC) {
Edwin Törökbd448e32009-07-14 16:55:14 +00002557 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner0631ea72008-11-16 05:06:21 +00002558 case ICmpInst::ICMP_EQ: // (X s> 13 & X == 15) -> X == 15
2559 case ICmpInst::ICMP_SGT: // (X s> 13 & X s> 15) -> X s> 15
2560 return ReplaceInstUsesWith(I, RHS);
2561 case ICmpInst::ICMP_UGT: // (X s> 13 & X u> 15) -> no change
2562 break;
2563 case ICmpInst::ICMP_NE:
Dan Gohmanfe91cd62009-08-12 16:04:34 +00002564 if (RHSCst == AddOne(LHSCst)) // (X s> 13 & X != 14) -> X s> 14
Dan Gohmane6803b82009-08-25 23:17:54 +00002565 return new ICmpInst(LHSCC, Val, RHSCst);
Chris Lattner0631ea72008-11-16 05:06:21 +00002566 break; // (X s> 13 & X != 15) -> no change
Chris Lattner0c678e52008-11-16 05:20:07 +00002567 case ICmpInst::ICMP_SLT: // (X s> 13 & X s< 15) -> (X-14) s< 1
Dan Gohmanfe91cd62009-08-12 16:04:34 +00002568 return InsertRangeTest(Val, AddOne(LHSCst),
Owen Anderson24be4c12009-07-03 00:17:18 +00002569 RHSCst, true, true, I);
Chris Lattner0631ea72008-11-16 05:06:21 +00002570 case ICmpInst::ICMP_ULT: // (X s> 13 & X u< 15) -> no change
2571 break;
2572 }
2573 break;
2574 }
Chris Lattner0631ea72008-11-16 05:06:21 +00002575
2576 return 0;
2577}
2578
Chris Lattner93a359a2009-07-23 05:14:02 +00002579Instruction *InstCombiner::FoldAndOfFCmps(Instruction &I, FCmpInst *LHS,
2580 FCmpInst *RHS) {
2581
2582 if (LHS->getPredicate() == FCmpInst::FCMP_ORD &&
2583 RHS->getPredicate() == FCmpInst::FCMP_ORD) {
2584 // (fcmp ord x, c) & (fcmp ord y, c) -> (fcmp ord x, y)
2585 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
2586 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
2587 // If either of the constants are nans, then the whole thing returns
2588 // false.
2589 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Chris Lattner03a27b42010-01-04 07:02:48 +00002590 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getContext()));
Dan Gohmane6803b82009-08-25 23:17:54 +00002591 return new FCmpInst(FCmpInst::FCMP_ORD,
Chris Lattner93a359a2009-07-23 05:14:02 +00002592 LHS->getOperand(0), RHS->getOperand(0));
2593 }
Chris Lattnercf373552009-07-23 05:32:17 +00002594
2595 // Handle vector zeros. This occurs because the canonical form of
2596 // "fcmp ord x,x" is "fcmp ord x, 0".
2597 if (isa<ConstantAggregateZero>(LHS->getOperand(1)) &&
2598 isa<ConstantAggregateZero>(RHS->getOperand(1)))
Dan Gohmane6803b82009-08-25 23:17:54 +00002599 return new FCmpInst(FCmpInst::FCMP_ORD,
Chris Lattnercf373552009-07-23 05:32:17 +00002600 LHS->getOperand(0), RHS->getOperand(0));
Chris Lattner93a359a2009-07-23 05:14:02 +00002601 return 0;
2602 }
2603
2604 Value *Op0LHS = LHS->getOperand(0), *Op0RHS = LHS->getOperand(1);
2605 Value *Op1LHS = RHS->getOperand(0), *Op1RHS = RHS->getOperand(1);
2606 FCmpInst::Predicate Op0CC = LHS->getPredicate(), Op1CC = RHS->getPredicate();
2607
2608
2609 if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
2610 // Swap RHS operands to match LHS.
2611 Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
2612 std::swap(Op1LHS, Op1RHS);
2613 }
2614
2615 if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
2616 // Simplify (fcmp cc0 x, y) & (fcmp cc1 x, y).
2617 if (Op0CC == Op1CC)
Dan Gohmane6803b82009-08-25 23:17:54 +00002618 return new FCmpInst((FCmpInst::Predicate)Op0CC, Op0LHS, Op0RHS);
Chris Lattner93a359a2009-07-23 05:14:02 +00002619
2620 if (Op0CC == FCmpInst::FCMP_FALSE || Op1CC == FCmpInst::FCMP_FALSE)
Chris Lattner03a27b42010-01-04 07:02:48 +00002621 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getContext()));
Chris Lattner93a359a2009-07-23 05:14:02 +00002622 if (Op0CC == FCmpInst::FCMP_TRUE)
2623 return ReplaceInstUsesWith(I, RHS);
2624 if (Op1CC == FCmpInst::FCMP_TRUE)
2625 return ReplaceInstUsesWith(I, LHS);
2626
2627 bool Op0Ordered;
2628 bool Op1Ordered;
2629 unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
2630 unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
2631 if (Op1Pred == 0) {
2632 std::swap(LHS, RHS);
2633 std::swap(Op0Pred, Op1Pred);
2634 std::swap(Op0Ordered, Op1Ordered);
2635 }
2636 if (Op0Pred == 0) {
2637 // uno && ueq -> uno && (uno || eq) -> ueq
2638 // ord && olt -> ord && (ord && lt) -> olt
2639 if (Op0Ordered == Op1Ordered)
2640 return ReplaceInstUsesWith(I, RHS);
2641
2642 // uno && oeq -> uno && (ord && eq) -> false
2643 // uno && ord -> false
2644 if (!Op0Ordered)
Chris Lattner03a27b42010-01-04 07:02:48 +00002645 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getContext()));
Chris Lattner93a359a2009-07-23 05:14:02 +00002646 // ord && ueq -> ord && (uno || eq) -> oeq
Chris Lattner03a27b42010-01-04 07:02:48 +00002647 return cast<Instruction>(getFCmpValue(true, Op1Pred, Op0LHS, Op0RHS));
Chris Lattner93a359a2009-07-23 05:14:02 +00002648 }
2649 }
2650
2651 return 0;
2652}
2653
Chris Lattner0631ea72008-11-16 05:06:21 +00002654
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002655Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
2656 bool Changed = SimplifyCommutative(I);
2657 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2658
Chris Lattnera3e46f62009-11-10 00:55:12 +00002659 if (Value *V = SimplifyAndInst(Op0, Op1, TD))
2660 return ReplaceInstUsesWith(I, V);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002661
2662 // See if we can simplify any instructions used by the instruction whose sole
2663 // purpose is to compute bits we don't care about.
Dan Gohman8fd520a2009-06-15 22:12:54 +00002664 if (SimplifyDemandedInstructionBits(I))
Nick Lewycky72c812c2010-01-02 15:25:44 +00002665 return &I;
Dan Gohman8fd520a2009-06-15 22:12:54 +00002666
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002667 if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner4580d452009-10-11 22:00:32 +00002668 const APInt &AndRHSMask = AndRHS->getValue();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002669 APInt NotAndRHS(~AndRHSMask);
2670
2671 // Optimize a variety of ((val OP C1) & C2) combinations...
Chris Lattner4580d452009-10-11 22:00:32 +00002672 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002673 Value *Op0LHS = Op0I->getOperand(0);
2674 Value *Op0RHS = Op0I->getOperand(1);
2675 switch (Op0I->getOpcode()) {
Chris Lattner4580d452009-10-11 22:00:32 +00002676 default: break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002677 case Instruction::Xor:
2678 case Instruction::Or:
2679 // If the mask is only needed on one incoming arm, push it up.
Chris Lattner4580d452009-10-11 22:00:32 +00002680 if (!Op0I->hasOneUse()) break;
2681
2682 if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
2683 // Not masking anything out for the LHS, move to RHS.
2684 Value *NewRHS = Builder->CreateAnd(Op0RHS, AndRHS,
2685 Op0RHS->getName()+".masked");
2686 return BinaryOperator::Create(Op0I->getOpcode(), Op0LHS, NewRHS);
2687 }
2688 if (!isa<Constant>(Op0RHS) &&
2689 MaskedValueIsZero(Op0RHS, NotAndRHS)) {
2690 // Not masking anything out for the RHS, move to LHS.
2691 Value *NewLHS = Builder->CreateAnd(Op0LHS, AndRHS,
2692 Op0LHS->getName()+".masked");
2693 return BinaryOperator::Create(Op0I->getOpcode(), NewLHS, Op0RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002694 }
2695
2696 break;
2697 case Instruction::Add:
2698 // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
2699 // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
2700 // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
2701 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
Gabor Greifa645dd32008-05-16 19:29:10 +00002702 return BinaryOperator::CreateAnd(V, AndRHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002703 if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
Gabor Greifa645dd32008-05-16 19:29:10 +00002704 return BinaryOperator::CreateAnd(V, AndRHS); // Add commutes
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002705 break;
2706
2707 case Instruction::Sub:
2708 // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
2709 // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
2710 // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
2711 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
Gabor Greifa645dd32008-05-16 19:29:10 +00002712 return BinaryOperator::CreateAnd(V, AndRHS);
Nick Lewyckyffed71b2008-07-09 04:32:37 +00002713
Nick Lewyckya349ba42008-07-10 05:51:40 +00002714 // (A - N) & AndRHS -> -N & AndRHS iff A&AndRHS==0 and AndRHS
2715 // has 1's for all bits that the subtraction with A might affect.
2716 if (Op0I->hasOneUse()) {
2717 uint32_t BitWidth = AndRHSMask.getBitWidth();
2718 uint32_t Zeros = AndRHSMask.countLeadingZeros();
2719 APInt Mask = APInt::getLowBitsSet(BitWidth, BitWidth - Zeros);
2720
Nick Lewyckyffed71b2008-07-09 04:32:37 +00002721 ConstantInt *A = dyn_cast<ConstantInt>(Op0LHS);
Nick Lewyckya349ba42008-07-10 05:51:40 +00002722 if (!(A && A->isZero()) && // avoid infinite recursion.
2723 MaskedValueIsZero(Op0LHS, Mask)) {
Chris Lattnerc7694852009-08-30 07:44:24 +00002724 Value *NewNeg = Builder->CreateNeg(Op0RHS);
Nick Lewyckyffed71b2008-07-09 04:32:37 +00002725 return BinaryOperator::CreateAnd(NewNeg, AndRHS);
2726 }
2727 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002728 break;
Nick Lewycky659ed4d2008-07-09 05:20:13 +00002729
2730 case Instruction::Shl:
2731 case Instruction::LShr:
2732 // (1 << x) & 1 --> zext(x == 0)
2733 // (1 >> x) & 1 --> zext(x == 0)
Nick Lewyckyf1b12222008-07-09 07:35:26 +00002734 if (AndRHSMask == 1 && Op0LHS == AndRHS) {
Chris Lattnerc7694852009-08-30 07:44:24 +00002735 Value *NewICmp =
2736 Builder->CreateICmpEQ(Op0RHS, Constant::getNullValue(I.getType()));
Nick Lewycky659ed4d2008-07-09 05:20:13 +00002737 return new ZExtInst(NewICmp, I.getType());
2738 }
2739 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002740 }
2741
2742 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
2743 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
2744 return Res;
2745 } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
2746 // If this is an integer truncation or change from signed-to-unsigned, and
2747 // if the source is an and/or with immediate, transform it. This
2748 // frequently occurs for bitfield accesses.
2749 if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
2750 if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
2751 CastOp->getNumOperands() == 2)
Chris Lattner6e060db2009-10-26 15:40:07 +00002752 if (ConstantInt *AndCI =dyn_cast<ConstantInt>(CastOp->getOperand(1))){
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002753 if (CastOp->getOpcode() == Instruction::And) {
2754 // Change: and (cast (and X, C1) to T), C2
2755 // into : and (cast X to T), trunc_or_bitcast(C1)&C2
2756 // This will fold the two constants together, which may allow
2757 // other simplifications.
Chris Lattnerc7694852009-08-30 07:44:24 +00002758 Value *NewCast = Builder->CreateTruncOrBitCast(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002759 CastOp->getOperand(0), I.getType(),
2760 CastOp->getName()+".shrunk");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002761 // trunc_or_bitcast(C1)&C2
Chris Lattnerc7694852009-08-30 07:44:24 +00002762 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
Owen Anderson02b48c32009-07-29 18:55:55 +00002763 C3 = ConstantExpr::getAnd(C3, AndRHS);
Gabor Greifa645dd32008-05-16 19:29:10 +00002764 return BinaryOperator::CreateAnd(NewCast, C3);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002765 } else if (CastOp->getOpcode() == Instruction::Or) {
2766 // Change: and (cast (or X, C1) to T), C2
2767 // into : trunc(C1)&C2 iff trunc(C1)&C2 == C2
Chris Lattnerc7694852009-08-30 07:44:24 +00002768 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
Owen Anderson02b48c32009-07-29 18:55:55 +00002769 if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS)
Owen Anderson24be4c12009-07-03 00:17:18 +00002770 // trunc(C1)&C2
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002771 return ReplaceInstUsesWith(I, AndRHS);
2772 }
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00002773 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002774 }
2775 }
2776
2777 // Try to fold constant and into select arguments.
2778 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner54826cd2010-01-04 07:53:58 +00002779 if (Instruction *R = FoldOpIntoSelect(I, SI))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002780 return R;
2781 if (isa<PHINode>(Op0))
2782 if (Instruction *NV = FoldOpIntoPhi(I))
2783 return NV;
2784 }
2785
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002786
2787 // (~A & ~B) == (~(A | B)) - De Morgan's Law
Chris Lattnera3e46f62009-11-10 00:55:12 +00002788 if (Value *Op0NotVal = dyn_castNotVal(Op0))
2789 if (Value *Op1NotVal = dyn_castNotVal(Op1))
2790 if (Op0->hasOneUse() && Op1->hasOneUse()) {
2791 Value *Or = Builder->CreateOr(Op0NotVal, Op1NotVal,
2792 I.getName()+".demorgan");
2793 return BinaryOperator::CreateNot(Or);
2794 }
2795
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002796 {
2797 Value *A = 0, *B = 0, *C = 0, *D = 0;
Chris Lattnera3e46f62009-11-10 00:55:12 +00002798 // (A|B) & ~(A&B) -> A^B
2799 if (match(Op0, m_Or(m_Value(A), m_Value(B))) &&
2800 match(Op1, m_Not(m_And(m_Value(C), m_Value(D)))) &&
2801 ((A == C && B == D) || (A == D && B == C)))
2802 return BinaryOperator::CreateXor(A, B);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002803
Chris Lattnera3e46f62009-11-10 00:55:12 +00002804 // ~(A&B) & (A|B) -> A^B
2805 if (match(Op1, m_Or(m_Value(A), m_Value(B))) &&
2806 match(Op0, m_Not(m_And(m_Value(C), m_Value(D)))) &&
2807 ((A == C && B == D) || (A == D && B == C)))
2808 return BinaryOperator::CreateXor(A, B);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002809
2810 if (Op0->hasOneUse() &&
Dan Gohmancdff2122009-08-12 16:23:25 +00002811 match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002812 if (A == Op1) { // (A^B)&A -> A&(A^B)
2813 I.swapOperands(); // Simplify below
2814 std::swap(Op0, Op1);
2815 } else if (B == Op1) { // (A^B)&B -> B&(B^A)
2816 cast<BinaryOperator>(Op0)->swapOperands();
2817 I.swapOperands(); // Simplify below
2818 std::swap(Op0, Op1);
2819 }
2820 }
Bill Wendlingce5e0af2008-11-30 13:08:13 +00002821
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002822 if (Op1->hasOneUse() &&
Dan Gohmancdff2122009-08-12 16:23:25 +00002823 match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002824 if (B == Op0) { // B&(A^B) -> B&(B^A)
2825 cast<BinaryOperator>(Op1)->swapOperands();
2826 std::swap(A, B);
2827 }
Chris Lattnerc7694852009-08-30 07:44:24 +00002828 if (A == Op0) // A&(A^B) -> A & ~B
2829 return BinaryOperator::CreateAnd(A, Builder->CreateNot(B, "tmp"));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002830 }
Bill Wendlingce5e0af2008-11-30 13:08:13 +00002831
2832 // (A&((~A)|B)) -> A&B
Dan Gohmancdff2122009-08-12 16:23:25 +00002833 if (match(Op0, m_Or(m_Not(m_Specific(Op1)), m_Value(A))) ||
2834 match(Op0, m_Or(m_Value(A), m_Not(m_Specific(Op1)))))
Chris Lattner9db479f2008-12-01 05:16:26 +00002835 return BinaryOperator::CreateAnd(A, Op1);
Dan Gohmancdff2122009-08-12 16:23:25 +00002836 if (match(Op1, m_Or(m_Not(m_Specific(Op0)), m_Value(A))) ||
2837 match(Op1, m_Or(m_Value(A), m_Not(m_Specific(Op0)))))
Chris Lattner9db479f2008-12-01 05:16:26 +00002838 return BinaryOperator::CreateAnd(A, Op0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002839 }
2840
2841 if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1)) {
2842 // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
Dan Gohmanfe91cd62009-08-12 16:04:34 +00002843 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002844 return R;
2845
Chris Lattner0631ea72008-11-16 05:06:21 +00002846 if (ICmpInst *LHS = dyn_cast<ICmpInst>(Op0))
2847 if (Instruction *Res = FoldAndOfICmps(I, LHS, RHS))
2848 return Res;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002849 }
2850
2851 // fold (and (cast A), (cast B)) -> (cast (and A, B))
2852 if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
2853 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
2854 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind ?
2855 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattnercf373552009-07-23 05:32:17 +00002856 if (SrcTy == Op1C->getOperand(0)->getType() &&
2857 SrcTy->isIntOrIntVector() &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002858 // Only do this if the casts both really cause code to be generated.
Chris Lattner54826cd2010-01-04 07:53:58 +00002859 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
2860 I.getType()) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002861 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
Chris Lattner54826cd2010-01-04 07:53:58 +00002862 I.getType())) {
Chris Lattnerc7694852009-08-30 07:44:24 +00002863 Value *NewOp = Builder->CreateAnd(Op0C->getOperand(0),
2864 Op1C->getOperand(0), I.getName());
Gabor Greifa645dd32008-05-16 19:29:10 +00002865 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002866 }
2867 }
2868
2869 // (X >> Z) & (Y >> Z) -> (X&Y) >> Z for all shifts.
2870 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
2871 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
2872 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
2873 SI0->getOperand(1) == SI1->getOperand(1) &&
2874 (SI0->hasOneUse() || SI1->hasOneUse())) {
Chris Lattnerc7694852009-08-30 07:44:24 +00002875 Value *NewOp =
2876 Builder->CreateAnd(SI0->getOperand(0), SI1->getOperand(0),
2877 SI0->getName());
Gabor Greifa645dd32008-05-16 19:29:10 +00002878 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002879 SI1->getOperand(1));
2880 }
2881 }
2882
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00002883 // If and'ing two fcmp, try combine them into one.
Chris Lattner91882432007-10-24 05:38:08 +00002884 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
Chris Lattner93a359a2009-07-23 05:14:02 +00002885 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
2886 if (Instruction *Res = FoldAndOfFCmps(I, LHS, RHS))
2887 return Res;
Chris Lattner91882432007-10-24 05:38:08 +00002888 }
Nick Lewyckyffed71b2008-07-09 04:32:37 +00002889
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002890 return Changed ? &I : 0;
2891}
2892
Chris Lattner567f5112008-10-05 02:13:19 +00002893/// CollectBSwapParts - Analyze the specified subexpression and see if it is
2894/// capable of providing pieces of a bswap. The subexpression provides pieces
2895/// of a bswap if it is proven that each of the non-zero bytes in the output of
2896/// the expression came from the corresponding "byte swapped" byte in some other
2897/// value. For example, if the current subexpression is "(shl i32 %X, 24)" then
2898/// we know that the expression deposits the low byte of %X into the high byte
2899/// of the bswap result and that all other bytes are zero. This expression is
2900/// accepted, the high byte of ByteValues is set to X to indicate a correct
2901/// match.
2902///
2903/// This function returns true if the match was unsuccessful and false if so.
2904/// On entry to the function the "OverallLeftShift" is a signed integer value
2905/// indicating the number of bytes that the subexpression is later shifted. For
2906/// example, if the expression is later right shifted by 16 bits, the
2907/// OverallLeftShift value would be -2 on entry. This is used to specify which
2908/// byte of ByteValues is actually being set.
2909///
2910/// Similarly, ByteMask is a bitmask where a bit is clear if its corresponding
2911/// byte is masked to zero by a user. For example, in (X & 255), X will be
2912/// processed with a bytemask of 1. Because bytemask is 32-bits, this limits
2913/// this function to working on up to 32-byte (256 bit) values. ByteMask is
2914/// always in the local (OverallLeftShift) coordinate space.
2915///
2916static bool CollectBSwapParts(Value *V, int OverallLeftShift, uint32_t ByteMask,
2917 SmallVector<Value*, 8> &ByteValues) {
2918 if (Instruction *I = dyn_cast<Instruction>(V)) {
2919 // If this is an or instruction, it may be an inner node of the bswap.
2920 if (I->getOpcode() == Instruction::Or) {
2921 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
2922 ByteValues) ||
2923 CollectBSwapParts(I->getOperand(1), OverallLeftShift, ByteMask,
2924 ByteValues);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002925 }
Chris Lattner567f5112008-10-05 02:13:19 +00002926
2927 // If this is a logical shift by a constant multiple of 8, recurse with
2928 // OverallLeftShift and ByteMask adjusted.
2929 if (I->isLogicalShift() && isa<ConstantInt>(I->getOperand(1))) {
2930 unsigned ShAmt =
2931 cast<ConstantInt>(I->getOperand(1))->getLimitedValue(~0U);
2932 // Ensure the shift amount is defined and of a byte value.
2933 if ((ShAmt & 7) || (ShAmt > 8*ByteValues.size()))
2934 return true;
2935
2936 unsigned ByteShift = ShAmt >> 3;
2937 if (I->getOpcode() == Instruction::Shl) {
2938 // X << 2 -> collect(X, +2)
2939 OverallLeftShift += ByteShift;
2940 ByteMask >>= ByteShift;
2941 } else {
2942 // X >>u 2 -> collect(X, -2)
2943 OverallLeftShift -= ByteShift;
2944 ByteMask <<= ByteShift;
Chris Lattner44448592008-10-08 06:42:28 +00002945 ByteMask &= (~0U >> (32-ByteValues.size()));
Chris Lattner567f5112008-10-05 02:13:19 +00002946 }
2947
2948 if (OverallLeftShift >= (int)ByteValues.size()) return true;
2949 if (OverallLeftShift <= -(int)ByteValues.size()) return true;
2950
2951 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
2952 ByteValues);
2953 }
2954
2955 // If this is a logical 'and' with a mask that clears bytes, clear the
2956 // corresponding bytes in ByteMask.
2957 if (I->getOpcode() == Instruction::And &&
2958 isa<ConstantInt>(I->getOperand(1))) {
2959 // Scan every byte of the and mask, seeing if the byte is either 0 or 255.
2960 unsigned NumBytes = ByteValues.size();
2961 APInt Byte(I->getType()->getPrimitiveSizeInBits(), 255);
2962 const APInt &AndMask = cast<ConstantInt>(I->getOperand(1))->getValue();
2963
2964 for (unsigned i = 0; i != NumBytes; ++i, Byte <<= 8) {
2965 // If this byte is masked out by a later operation, we don't care what
2966 // the and mask is.
2967 if ((ByteMask & (1 << i)) == 0)
2968 continue;
2969
2970 // If the AndMask is all zeros for this byte, clear the bit.
2971 APInt MaskB = AndMask & Byte;
2972 if (MaskB == 0) {
2973 ByteMask &= ~(1U << i);
2974 continue;
2975 }
2976
2977 // If the AndMask is not all ones for this byte, it's not a bytezap.
2978 if (MaskB != Byte)
2979 return true;
2980
2981 // Otherwise, this byte is kept.
2982 }
2983
2984 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
2985 ByteValues);
2986 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002987 }
2988
Chris Lattner567f5112008-10-05 02:13:19 +00002989 // Okay, we got to something that isn't a shift, 'or' or 'and'. This must be
2990 // the input value to the bswap. Some observations: 1) if more than one byte
2991 // is demanded from this input, then it could not be successfully assembled
2992 // into a byteswap. At least one of the two bytes would not be aligned with
2993 // their ultimate destination.
2994 if (!isPowerOf2_32(ByteMask)) return true;
2995 unsigned InputByteNo = CountTrailingZeros_32(ByteMask);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002996
Chris Lattner567f5112008-10-05 02:13:19 +00002997 // 2) The input and ultimate destinations must line up: if byte 3 of an i32
2998 // is demanded, it needs to go into byte 0 of the result. This means that the
2999 // byte needs to be shifted until it lands in the right byte bucket. The
3000 // shift amount depends on the position: if the byte is coming from the high
3001 // part of the value (e.g. byte 3) then it must be shifted right. If from the
3002 // low part, it must be shifted left.
3003 unsigned DestByteNo = InputByteNo + OverallLeftShift;
3004 if (InputByteNo < ByteValues.size()/2) {
3005 if (ByteValues.size()-1-DestByteNo != InputByteNo)
3006 return true;
3007 } else {
3008 if (ByteValues.size()-1-DestByteNo != InputByteNo)
3009 return true;
3010 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003011
3012 // If the destination byte value is already defined, the values are or'd
3013 // together, which isn't a bswap (unless it's an or of the same bits).
Chris Lattner567f5112008-10-05 02:13:19 +00003014 if (ByteValues[DestByteNo] && ByteValues[DestByteNo] != V)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003015 return true;
Chris Lattner567f5112008-10-05 02:13:19 +00003016 ByteValues[DestByteNo] = V;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003017 return false;
3018}
3019
3020/// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
3021/// If so, insert the new bswap intrinsic and return it.
3022Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
3023 const IntegerType *ITy = dyn_cast<IntegerType>(I.getType());
Chris Lattner567f5112008-10-05 02:13:19 +00003024 if (!ITy || ITy->getBitWidth() % 16 ||
3025 // ByteMask only allows up to 32-byte values.
3026 ITy->getBitWidth() > 32*8)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003027 return 0; // Can only bswap pairs of bytes. Can't do vectors.
3028
3029 /// ByteValues - For each byte of the result, we keep track of which value
3030 /// defines each byte.
3031 SmallVector<Value*, 8> ByteValues;
3032 ByteValues.resize(ITy->getBitWidth()/8);
3033
3034 // Try to find all the pieces corresponding to the bswap.
Chris Lattner567f5112008-10-05 02:13:19 +00003035 uint32_t ByteMask = ~0U >> (32-ByteValues.size());
3036 if (CollectBSwapParts(&I, 0, ByteMask, ByteValues))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003037 return 0;
3038
3039 // Check to see if all of the bytes come from the same value.
3040 Value *V = ByteValues[0];
3041 if (V == 0) return 0; // Didn't find a byte? Must be zero.
3042
3043 // Check to make sure that all of the bytes come from the same value.
3044 for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
3045 if (ByteValues[i] != V)
3046 return 0;
Chandler Carrutha228e392007-08-04 01:51:18 +00003047 const Type *Tys[] = { ITy };
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003048 Module *M = I.getParent()->getParent()->getParent();
Chandler Carrutha228e392007-08-04 01:51:18 +00003049 Function *F = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 1);
Gabor Greifd6da1d02008-04-06 20:25:17 +00003050 return CallInst::Create(F, V);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003051}
3052
Chris Lattnerdd7772b2008-11-16 04:24:12 +00003053/// MatchSelectFromAndOr - We have an expression of the form (A&C)|(B&D). Check
3054/// If A is (cond?-1:0) and either B or D is ~(cond?-1,0) or (cond?0,-1), then
3055/// we can simplify this expression to "cond ? C : D or B".
3056static Instruction *MatchSelectFromAndOr(Value *A, Value *B,
Chris Lattner03a27b42010-01-04 07:02:48 +00003057 Value *C, Value *D) {
Chris Lattnerd09b5ba2008-11-16 04:26:55 +00003058 // If A is not a select of -1/0, this cannot match.
Chris Lattner641ea462008-11-16 04:46:19 +00003059 Value *Cond = 0;
Dan Gohmancdff2122009-08-12 16:23:25 +00003060 if (!match(A, m_SelectCst<-1, 0>(m_Value(Cond))))
Chris Lattnerdd7772b2008-11-16 04:24:12 +00003061 return 0;
3062
Chris Lattnerd09b5ba2008-11-16 04:26:55 +00003063 // ((cond?-1:0)&C) | (B&(cond?0:-1)) -> cond ? C : B.
Dan Gohmancdff2122009-08-12 16:23:25 +00003064 if (match(D, m_SelectCst<0, -1>(m_Specific(Cond))))
Chris Lattnerd09b5ba2008-11-16 04:26:55 +00003065 return SelectInst::Create(Cond, C, B);
Dan Gohmancdff2122009-08-12 16:23:25 +00003066 if (match(D, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond)))))
Chris Lattnerd09b5ba2008-11-16 04:26:55 +00003067 return SelectInst::Create(Cond, C, B);
3068 // ((cond?-1:0)&C) | ((cond?0:-1)&D) -> cond ? C : D.
Dan Gohmancdff2122009-08-12 16:23:25 +00003069 if (match(B, m_SelectCst<0, -1>(m_Specific(Cond))))
Chris Lattnerd09b5ba2008-11-16 04:26:55 +00003070 return SelectInst::Create(Cond, C, D);
Dan Gohmancdff2122009-08-12 16:23:25 +00003071 if (match(B, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond)))))
Chris Lattnerd09b5ba2008-11-16 04:26:55 +00003072 return SelectInst::Create(Cond, C, D);
Chris Lattnerdd7772b2008-11-16 04:24:12 +00003073 return 0;
3074}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003075
Chris Lattner0c678e52008-11-16 05:20:07 +00003076/// FoldOrOfICmps - Fold (icmp)|(icmp) if possible.
3077Instruction *InstCombiner::FoldOrOfICmps(Instruction &I,
3078 ICmpInst *LHS, ICmpInst *RHS) {
3079 Value *Val, *Val2;
3080 ConstantInt *LHSCst, *RHSCst;
3081 ICmpInst::Predicate LHSCC, RHSCC;
3082
3083 // This only handles icmp of constants: (icmp1 A, C1) | (icmp2 B, C2).
Chris Lattner163e6ab2009-11-29 00:51:17 +00003084 if (!match(LHS, m_ICmp(LHSCC, m_Value(Val), m_ConstantInt(LHSCst))) ||
3085 !match(RHS, m_ICmp(RHSCC, m_Value(Val2), m_ConstantInt(RHSCst))))
Chris Lattner0c678e52008-11-16 05:20:07 +00003086 return 0;
Chris Lattner163e6ab2009-11-29 00:51:17 +00003087
3088
3089 // (icmp ne A, 0) | (icmp ne B, 0) --> (icmp ne (A|B), 0)
3090 if (LHSCst == RHSCst && LHSCC == RHSCC &&
3091 LHSCC == ICmpInst::ICMP_NE && LHSCst->isZero()) {
3092 Value *NewOr = Builder->CreateOr(Val, Val2);
3093 return new ICmpInst(LHSCC, NewOr, LHSCst);
3094 }
Chris Lattner0c678e52008-11-16 05:20:07 +00003095
3096 // From here on, we only handle:
3097 // (icmp1 A, C1) | (icmp2 A, C2) --> something simpler.
3098 if (Val != Val2) return 0;
3099
3100 // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
3101 if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
3102 RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
3103 LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
3104 RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
3105 return 0;
3106
3107 // We can't fold (ugt x, C) | (sgt x, C2).
3108 if (!PredicatesFoldable(LHSCC, RHSCC))
3109 return 0;
3110
3111 // Ensure that the larger constant is on the RHS.
3112 bool ShouldSwap;
Nick Lewyckyb0796c62009-10-25 05:20:17 +00003113 if (CmpInst::isSigned(LHSCC) ||
Chris Lattner0c678e52008-11-16 05:20:07 +00003114 (ICmpInst::isEquality(LHSCC) &&
Nick Lewyckyb0796c62009-10-25 05:20:17 +00003115 CmpInst::isSigned(RHSCC)))
Chris Lattner0c678e52008-11-16 05:20:07 +00003116 ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
3117 else
3118 ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
3119
3120 if (ShouldSwap) {
3121 std::swap(LHS, RHS);
3122 std::swap(LHSCst, RHSCst);
3123 std::swap(LHSCC, RHSCC);
3124 }
3125
3126 // At this point, we know we have have two icmp instructions
3127 // comparing a value against two constants and or'ing the result
3128 // together. Because of the above check, we know that we only have
3129 // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
3130 // FoldICmpLogical check above), that the two constants are not
3131 // equal.
3132 assert(LHSCst != RHSCst && "Compares not folded above?");
3133
3134 switch (LHSCC) {
Edwin Törökbd448e32009-07-14 16:55:14 +00003135 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner0c678e52008-11-16 05:20:07 +00003136 case ICmpInst::ICMP_EQ:
3137 switch (RHSCC) {
Edwin Törökbd448e32009-07-14 16:55:14 +00003138 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner0c678e52008-11-16 05:20:07 +00003139 case ICmpInst::ICMP_EQ:
Dan Gohmanfe91cd62009-08-12 16:04:34 +00003140 if (LHSCst == SubOne(RHSCst)) {
Owen Anderson24be4c12009-07-03 00:17:18 +00003141 // (X == 13 | X == 14) -> X-13 <u 2
Owen Anderson02b48c32009-07-29 18:55:55 +00003142 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
Chris Lattnerc7694852009-08-30 07:44:24 +00003143 Value *Add = Builder->CreateAdd(Val, AddCST, Val->getName()+".off");
Dan Gohmanfe91cd62009-08-12 16:04:34 +00003144 AddCST = ConstantExpr::getSub(AddOne(RHSCst), LHSCst);
Dan Gohmane6803b82009-08-25 23:17:54 +00003145 return new ICmpInst(ICmpInst::ICMP_ULT, Add, AddCST);
Chris Lattner0c678e52008-11-16 05:20:07 +00003146 }
3147 break; // (X == 13 | X == 15) -> no change
3148 case ICmpInst::ICMP_UGT: // (X == 13 | X u> 14) -> no change
3149 case ICmpInst::ICMP_SGT: // (X == 13 | X s> 14) -> no change
3150 break;
3151 case ICmpInst::ICMP_NE: // (X == 13 | X != 15) -> X != 15
3152 case ICmpInst::ICMP_ULT: // (X == 13 | X u< 15) -> X u< 15
3153 case ICmpInst::ICMP_SLT: // (X == 13 | X s< 15) -> X s< 15
3154 return ReplaceInstUsesWith(I, RHS);
3155 }
3156 break;
3157 case ICmpInst::ICMP_NE:
3158 switch (RHSCC) {
Edwin Törökbd448e32009-07-14 16:55:14 +00003159 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner0c678e52008-11-16 05:20:07 +00003160 case ICmpInst::ICMP_EQ: // (X != 13 | X == 15) -> X != 13
3161 case ICmpInst::ICMP_UGT: // (X != 13 | X u> 15) -> X != 13
3162 case ICmpInst::ICMP_SGT: // (X != 13 | X s> 15) -> X != 13
3163 return ReplaceInstUsesWith(I, LHS);
3164 case ICmpInst::ICMP_NE: // (X != 13 | X != 15) -> true
3165 case ICmpInst::ICMP_ULT: // (X != 13 | X u< 15) -> true
3166 case ICmpInst::ICMP_SLT: // (X != 13 | X s< 15) -> true
Chris Lattner03a27b42010-01-04 07:02:48 +00003167 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getContext()));
Chris Lattner0c678e52008-11-16 05:20:07 +00003168 }
3169 break;
3170 case ICmpInst::ICMP_ULT:
3171 switch (RHSCC) {
Edwin Törökbd448e32009-07-14 16:55:14 +00003172 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner0c678e52008-11-16 05:20:07 +00003173 case ICmpInst::ICMP_EQ: // (X u< 13 | X == 14) -> no change
3174 break;
3175 case ICmpInst::ICMP_UGT: // (X u< 13 | X u> 15) -> (X-13) u> 2
3176 // If RHSCst is [us]MAXINT, it is always false. Not handling
3177 // this can cause overflow.
3178 if (RHSCst->isMaxValue(false))
3179 return ReplaceInstUsesWith(I, LHS);
Dan Gohmanfe91cd62009-08-12 16:04:34 +00003180 return InsertRangeTest(Val, LHSCst, AddOne(RHSCst),
Owen Anderson24be4c12009-07-03 00:17:18 +00003181 false, false, I);
Chris Lattner0c678e52008-11-16 05:20:07 +00003182 case ICmpInst::ICMP_SGT: // (X u< 13 | X s> 15) -> no change
3183 break;
3184 case ICmpInst::ICMP_NE: // (X u< 13 | X != 15) -> X != 15
3185 case ICmpInst::ICMP_ULT: // (X u< 13 | X u< 15) -> X u< 15
3186 return ReplaceInstUsesWith(I, RHS);
3187 case ICmpInst::ICMP_SLT: // (X u< 13 | X s< 15) -> no change
3188 break;
3189 }
3190 break;
3191 case ICmpInst::ICMP_SLT:
3192 switch (RHSCC) {
Edwin Törökbd448e32009-07-14 16:55:14 +00003193 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner0c678e52008-11-16 05:20:07 +00003194 case ICmpInst::ICMP_EQ: // (X s< 13 | X == 14) -> no change
3195 break;
3196 case ICmpInst::ICMP_SGT: // (X s< 13 | X s> 15) -> (X-13) s> 2
3197 // If RHSCst is [us]MAXINT, it is always false. Not handling
3198 // this can cause overflow.
3199 if (RHSCst->isMaxValue(true))
3200 return ReplaceInstUsesWith(I, LHS);
Dan Gohmanfe91cd62009-08-12 16:04:34 +00003201 return InsertRangeTest(Val, LHSCst, AddOne(RHSCst),
Owen Anderson24be4c12009-07-03 00:17:18 +00003202 true, false, I);
Chris Lattner0c678e52008-11-16 05:20:07 +00003203 case ICmpInst::ICMP_UGT: // (X s< 13 | X u> 15) -> no change
3204 break;
3205 case ICmpInst::ICMP_NE: // (X s< 13 | X != 15) -> X != 15
3206 case ICmpInst::ICMP_SLT: // (X s< 13 | X s< 15) -> X s< 15
3207 return ReplaceInstUsesWith(I, RHS);
3208 case ICmpInst::ICMP_ULT: // (X s< 13 | X u< 15) -> no change
3209 break;
3210 }
3211 break;
3212 case ICmpInst::ICMP_UGT:
3213 switch (RHSCC) {
Edwin Törökbd448e32009-07-14 16:55:14 +00003214 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner0c678e52008-11-16 05:20:07 +00003215 case ICmpInst::ICMP_EQ: // (X u> 13 | X == 15) -> X u> 13
3216 case ICmpInst::ICMP_UGT: // (X u> 13 | X u> 15) -> X u> 13
3217 return ReplaceInstUsesWith(I, LHS);
3218 case ICmpInst::ICMP_SGT: // (X u> 13 | X s> 15) -> no change
3219 break;
3220 case ICmpInst::ICMP_NE: // (X u> 13 | X != 15) -> true
3221 case ICmpInst::ICMP_ULT: // (X u> 13 | X u< 15) -> true
Chris Lattner03a27b42010-01-04 07:02:48 +00003222 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getContext()));
Chris Lattner0c678e52008-11-16 05:20:07 +00003223 case ICmpInst::ICMP_SLT: // (X u> 13 | X s< 15) -> no change
3224 break;
3225 }
3226 break;
3227 case ICmpInst::ICMP_SGT:
3228 switch (RHSCC) {
Edwin Törökbd448e32009-07-14 16:55:14 +00003229 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner0c678e52008-11-16 05:20:07 +00003230 case ICmpInst::ICMP_EQ: // (X s> 13 | X == 15) -> X > 13
3231 case ICmpInst::ICMP_SGT: // (X s> 13 | X s> 15) -> X > 13
3232 return ReplaceInstUsesWith(I, LHS);
3233 case ICmpInst::ICMP_UGT: // (X s> 13 | X u> 15) -> no change
3234 break;
3235 case ICmpInst::ICMP_NE: // (X s> 13 | X != 15) -> true
3236 case ICmpInst::ICMP_SLT: // (X s> 13 | X s< 15) -> true
Chris Lattner03a27b42010-01-04 07:02:48 +00003237 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getContext()));
Chris Lattner0c678e52008-11-16 05:20:07 +00003238 case ICmpInst::ICMP_ULT: // (X s> 13 | X u< 15) -> no change
3239 break;
3240 }
3241 break;
3242 }
3243 return 0;
3244}
3245
Chris Lattner57e66fa2009-07-23 05:46:22 +00003246Instruction *InstCombiner::FoldOrOfFCmps(Instruction &I, FCmpInst *LHS,
3247 FCmpInst *RHS) {
3248 if (LHS->getPredicate() == FCmpInst::FCMP_UNO &&
3249 RHS->getPredicate() == FCmpInst::FCMP_UNO &&
3250 LHS->getOperand(0)->getType() == RHS->getOperand(0)->getType()) {
3251 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
3252 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
3253 // If either of the constants are nans, then the whole thing returns
3254 // true.
3255 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Chris Lattner03a27b42010-01-04 07:02:48 +00003256 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getContext()));
Chris Lattner57e66fa2009-07-23 05:46:22 +00003257
3258 // Otherwise, no need to compare the two constants, compare the
3259 // rest.
Dan Gohmane6803b82009-08-25 23:17:54 +00003260 return new FCmpInst(FCmpInst::FCMP_UNO,
Chris Lattner57e66fa2009-07-23 05:46:22 +00003261 LHS->getOperand(0), RHS->getOperand(0));
3262 }
3263
3264 // Handle vector zeros. This occurs because the canonical form of
3265 // "fcmp uno x,x" is "fcmp uno x, 0".
3266 if (isa<ConstantAggregateZero>(LHS->getOperand(1)) &&
3267 isa<ConstantAggregateZero>(RHS->getOperand(1)))
Dan Gohmane6803b82009-08-25 23:17:54 +00003268 return new FCmpInst(FCmpInst::FCMP_UNO,
Chris Lattner57e66fa2009-07-23 05:46:22 +00003269 LHS->getOperand(0), RHS->getOperand(0));
3270
3271 return 0;
3272 }
3273
3274 Value *Op0LHS = LHS->getOperand(0), *Op0RHS = LHS->getOperand(1);
3275 Value *Op1LHS = RHS->getOperand(0), *Op1RHS = RHS->getOperand(1);
3276 FCmpInst::Predicate Op0CC = LHS->getPredicate(), Op1CC = RHS->getPredicate();
3277
3278 if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
3279 // Swap RHS operands to match LHS.
3280 Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
3281 std::swap(Op1LHS, Op1RHS);
3282 }
3283 if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
3284 // Simplify (fcmp cc0 x, y) | (fcmp cc1 x, y).
3285 if (Op0CC == Op1CC)
Dan Gohmane6803b82009-08-25 23:17:54 +00003286 return new FCmpInst((FCmpInst::Predicate)Op0CC,
Chris Lattner57e66fa2009-07-23 05:46:22 +00003287 Op0LHS, Op0RHS);
3288 if (Op0CC == FCmpInst::FCMP_TRUE || Op1CC == FCmpInst::FCMP_TRUE)
Chris Lattner03a27b42010-01-04 07:02:48 +00003289 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getContext()));
Chris Lattner57e66fa2009-07-23 05:46:22 +00003290 if (Op0CC == FCmpInst::FCMP_FALSE)
3291 return ReplaceInstUsesWith(I, RHS);
3292 if (Op1CC == FCmpInst::FCMP_FALSE)
3293 return ReplaceInstUsesWith(I, LHS);
3294 bool Op0Ordered;
3295 bool Op1Ordered;
3296 unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
3297 unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
3298 if (Op0Ordered == Op1Ordered) {
3299 // If both are ordered or unordered, return a new fcmp with
3300 // or'ed predicates.
Chris Lattner03a27b42010-01-04 07:02:48 +00003301 Value *RV = getFCmpValue(Op0Ordered, Op0Pred|Op1Pred, Op0LHS, Op0RHS);
Chris Lattner57e66fa2009-07-23 05:46:22 +00003302 if (Instruction *I = dyn_cast<Instruction>(RV))
3303 return I;
3304 // Otherwise, it's a constant boolean value...
3305 return ReplaceInstUsesWith(I, RV);
3306 }
3307 }
3308 return 0;
3309}
3310
Bill Wendlingdae376a2008-12-01 08:23:25 +00003311/// FoldOrWithConstants - This helper function folds:
3312///
Bill Wendling236a1192008-12-02 05:09:00 +00003313/// ((A | B) & C1) | (B & C2)
Bill Wendlingdae376a2008-12-01 08:23:25 +00003314///
3315/// into:
3316///
Bill Wendling236a1192008-12-02 05:09:00 +00003317/// (A & C1) | B
Bill Wendling9912f712008-12-01 08:32:40 +00003318///
Bill Wendling236a1192008-12-02 05:09:00 +00003319/// when the XOR of the two constants is "all ones" (-1).
Bill Wendling9912f712008-12-01 08:32:40 +00003320Instruction *InstCombiner::FoldOrWithConstants(BinaryOperator &I, Value *Op,
Bill Wendlingdae376a2008-12-01 08:23:25 +00003321 Value *A, Value *B, Value *C) {
Bill Wendlingfc5b8e62008-12-02 05:06:43 +00003322 ConstantInt *CI1 = dyn_cast<ConstantInt>(C);
3323 if (!CI1) return 0;
Bill Wendlingdae376a2008-12-01 08:23:25 +00003324
Bill Wendling0a0dcaf2008-12-02 06:24:20 +00003325 Value *V1 = 0;
3326 ConstantInt *CI2 = 0;
Dan Gohmancdff2122009-08-12 16:23:25 +00003327 if (!match(Op, m_And(m_Value(V1), m_ConstantInt(CI2)))) return 0;
Bill Wendlingdae376a2008-12-01 08:23:25 +00003328
Bill Wendling86ee3162008-12-02 06:18:11 +00003329 APInt Xor = CI1->getValue() ^ CI2->getValue();
3330 if (!Xor.isAllOnesValue()) return 0;
3331
Bill Wendling0a0dcaf2008-12-02 06:24:20 +00003332 if (V1 == A || V1 == B) {
Chris Lattnerc7694852009-08-30 07:44:24 +00003333 Value *NewOp = Builder->CreateAnd((V1 == A) ? B : A, CI1);
Bill Wendling6c8ecbb2008-12-02 06:22:04 +00003334 return BinaryOperator::CreateOr(NewOp, V1);
Bill Wendlingdae376a2008-12-01 08:23:25 +00003335 }
3336
3337 return 0;
3338}
3339
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003340Instruction *InstCombiner::visitOr(BinaryOperator &I) {
3341 bool Changed = SimplifyCommutative(I);
3342 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3343
Chris Lattnera3e46f62009-11-10 00:55:12 +00003344 if (Value *V = SimplifyOrInst(Op0, Op1, TD))
3345 return ReplaceInstUsesWith(I, V);
3346
3347
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003348 // See if we can simplify any instructions used by the instruction whose sole
3349 // purpose is to compute bits we don't care about.
Dan Gohman8fd520a2009-06-15 22:12:54 +00003350 if (SimplifyDemandedInstructionBits(I))
3351 return &I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003352
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003353 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3354 ConstantInt *C1 = 0; Value *X = 0;
3355 // (X & C1) | C2 --> (X | C2) & (C1|C2)
Dan Gohmancdff2122009-08-12 16:23:25 +00003356 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) &&
Owen Andersona21eb582009-07-10 17:35:01 +00003357 isOnlyUse(Op0)) {
Chris Lattnerc7694852009-08-30 07:44:24 +00003358 Value *Or = Builder->CreateOr(X, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003359 Or->takeName(Op0);
Gabor Greifa645dd32008-05-16 19:29:10 +00003360 return BinaryOperator::CreateAnd(Or,
Chris Lattner03a27b42010-01-04 07:02:48 +00003361 ConstantInt::get(I.getContext(),
3362 RHS->getValue() | C1->getValue()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003363 }
3364
3365 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
Dan Gohmancdff2122009-08-12 16:23:25 +00003366 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) &&
Owen Andersona21eb582009-07-10 17:35:01 +00003367 isOnlyUse(Op0)) {
Chris Lattnerc7694852009-08-30 07:44:24 +00003368 Value *Or = Builder->CreateOr(X, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003369 Or->takeName(Op0);
Gabor Greifa645dd32008-05-16 19:29:10 +00003370 return BinaryOperator::CreateXor(Or,
Chris Lattner03a27b42010-01-04 07:02:48 +00003371 ConstantInt::get(I.getContext(),
3372 C1->getValue() & ~RHS->getValue()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003373 }
3374
3375 // Try to fold constant and into select arguments.
3376 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner54826cd2010-01-04 07:53:58 +00003377 if (Instruction *R = FoldOpIntoSelect(I, SI))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003378 return R;
3379 if (isa<PHINode>(Op0))
3380 if (Instruction *NV = FoldOpIntoPhi(I))
3381 return NV;
3382 }
3383
3384 Value *A = 0, *B = 0;
3385 ConstantInt *C1 = 0, *C2 = 0;
3386
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003387 // (A | B) | C and A | (B | C) -> bswap if possible.
3388 // (A >> B) | (C << D) and (A << B) | (B >> C) -> bswap if possible.
Dan Gohmancdff2122009-08-12 16:23:25 +00003389 if (match(Op0, m_Or(m_Value(), m_Value())) ||
3390 match(Op1, m_Or(m_Value(), m_Value())) ||
3391 (match(Op0, m_Shift(m_Value(), m_Value())) &&
3392 match(Op1, m_Shift(m_Value(), m_Value())))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003393 if (Instruction *BSwap = MatchBSwap(I))
3394 return BSwap;
3395 }
3396
3397 // (X^C)|Y -> (X|Y)^C iff Y&C == 0
Owen Andersona21eb582009-07-10 17:35:01 +00003398 if (Op0->hasOneUse() &&
Dan Gohmancdff2122009-08-12 16:23:25 +00003399 match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003400 MaskedValueIsZero(Op1, C1->getValue())) {
Chris Lattnerc7694852009-08-30 07:44:24 +00003401 Value *NOr = Builder->CreateOr(A, Op1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003402 NOr->takeName(Op0);
Gabor Greifa645dd32008-05-16 19:29:10 +00003403 return BinaryOperator::CreateXor(NOr, C1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003404 }
3405
3406 // Y|(X^C) -> (X|Y)^C iff Y&C == 0
Owen Andersona21eb582009-07-10 17:35:01 +00003407 if (Op1->hasOneUse() &&
Dan Gohmancdff2122009-08-12 16:23:25 +00003408 match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003409 MaskedValueIsZero(Op0, C1->getValue())) {
Chris Lattnerc7694852009-08-30 07:44:24 +00003410 Value *NOr = Builder->CreateOr(A, Op0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003411 NOr->takeName(Op0);
Gabor Greifa645dd32008-05-16 19:29:10 +00003412 return BinaryOperator::CreateXor(NOr, C1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003413 }
3414
3415 // (A & C)|(B & D)
3416 Value *C = 0, *D = 0;
Dan Gohmancdff2122009-08-12 16:23:25 +00003417 if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
3418 match(Op1, m_And(m_Value(B), m_Value(D)))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003419 Value *V1 = 0, *V2 = 0, *V3 = 0;
3420 C1 = dyn_cast<ConstantInt>(C);
3421 C2 = dyn_cast<ConstantInt>(D);
3422 if (C1 && C2) { // (A & C1)|(B & C2)
3423 // If we have: ((V + N) & C1) | (V & C2)
3424 // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
3425 // replace with V+N.
3426 if (C1->getValue() == ~C2->getValue()) {
3427 if ((C2->getValue() & (C2->getValue()+1)) == 0 && // C2 == 0+1+
Dan Gohmancdff2122009-08-12 16:23:25 +00003428 match(A, m_Add(m_Value(V1), m_Value(V2)))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003429 // Add commutes, try both ways.
3430 if (V1 == B && MaskedValueIsZero(V2, C2->getValue()))
3431 return ReplaceInstUsesWith(I, A);
3432 if (V2 == B && MaskedValueIsZero(V1, C2->getValue()))
3433 return ReplaceInstUsesWith(I, A);
3434 }
3435 // Or commutes, try both ways.
3436 if ((C1->getValue() & (C1->getValue()+1)) == 0 &&
Dan Gohmancdff2122009-08-12 16:23:25 +00003437 match(B, m_Add(m_Value(V1), m_Value(V2)))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003438 // Add commutes, try both ways.
3439 if (V1 == A && MaskedValueIsZero(V2, C1->getValue()))
3440 return ReplaceInstUsesWith(I, B);
3441 if (V2 == A && MaskedValueIsZero(V1, C1->getValue()))
3442 return ReplaceInstUsesWith(I, B);
3443 }
3444 }
Chris Lattner4fcef8a2010-01-04 06:03:59 +00003445
3446 // ((V | N) & C1) | (V & C2) --> (V|N) & (C1|C2)
3447 // iff (C1&C2) == 0 and (N&~C1) == 0
3448 if ((C1->getValue() & C2->getValue()) == 0) {
3449 if (match(A, m_Or(m_Value(V1), m_Value(V2))) &&
3450 ((V1 == B && MaskedValueIsZero(V2, ~C1->getValue())) || // (V|N)
3451 (V2 == B && MaskedValueIsZero(V1, ~C1->getValue())))) // (N|V)
3452 return BinaryOperator::CreateAnd(A,
3453 ConstantInt::get(A->getContext(),
3454 C1->getValue()|C2->getValue()));
3455 // Or commutes, try both ways.
3456 if (match(B, m_Or(m_Value(V1), m_Value(V2))) &&
3457 ((V1 == A && MaskedValueIsZero(V2, ~C2->getValue())) || // (V|N)
3458 (V2 == A && MaskedValueIsZero(V1, ~C2->getValue())))) // (N|V)
3459 return BinaryOperator::CreateAnd(B,
3460 ConstantInt::get(B->getContext(),
3461 C1->getValue()|C2->getValue()));
3462 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003463 }
3464
3465 // Check to see if we have any common things being and'ed. If so, find the
3466 // terms for V1 & (V2|V3).
3467 if (isOnlyUse(Op0) || isOnlyUse(Op1)) {
Chris Lattner4fcef8a2010-01-04 06:03:59 +00003468 V1 = 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003469 if (A == B) // (A & C)|(A & D) == A & (C|D)
3470 V1 = A, V2 = C, V3 = D;
3471 else if (A == D) // (A & C)|(B & A) == A & (B|C)
3472 V1 = A, V2 = B, V3 = C;
3473 else if (C == B) // (A & C)|(C & D) == C & (A|D)
3474 V1 = C, V2 = A, V3 = D;
3475 else if (C == D) // (A & C)|(B & C) == C & (A|B)
3476 V1 = C, V2 = A, V3 = B;
3477
3478 if (V1) {
Chris Lattnerc7694852009-08-30 07:44:24 +00003479 Value *Or = Builder->CreateOr(V2, V3, "tmp");
Gabor Greifa645dd32008-05-16 19:29:10 +00003480 return BinaryOperator::CreateAnd(V1, Or);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003481 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003482 }
Dan Gohman279952c2008-10-28 22:38:57 +00003483
Dan Gohman35b76162008-10-30 20:40:10 +00003484 // (A & (C0?-1:0)) | (B & ~(C0?-1:0)) -> C0 ? A : B, and commuted variants
Chris Lattner03a27b42010-01-04 07:02:48 +00003485 if (Instruction *Match = MatchSelectFromAndOr(A, B, C, D))
Chris Lattnerdd7772b2008-11-16 04:24:12 +00003486 return Match;
Chris Lattner03a27b42010-01-04 07:02:48 +00003487 if (Instruction *Match = MatchSelectFromAndOr(B, A, D, C))
Chris Lattnerdd7772b2008-11-16 04:24:12 +00003488 return Match;
Chris Lattner03a27b42010-01-04 07:02:48 +00003489 if (Instruction *Match = MatchSelectFromAndOr(C, B, A, D))
Chris Lattnerdd7772b2008-11-16 04:24:12 +00003490 return Match;
Chris Lattner03a27b42010-01-04 07:02:48 +00003491 if (Instruction *Match = MatchSelectFromAndOr(D, A, B, C))
Chris Lattnerdd7772b2008-11-16 04:24:12 +00003492 return Match;
Bill Wendling22ca8352008-11-30 13:52:49 +00003493
Bill Wendling22ca8352008-11-30 13:52:49 +00003494 // ((A&~B)|(~A&B)) -> A^B
Dan Gohmancdff2122009-08-12 16:23:25 +00003495 if ((match(C, m_Not(m_Specific(D))) &&
3496 match(B, m_Not(m_Specific(A)))))
Bill Wendlingc1f31132008-12-01 08:09:47 +00003497 return BinaryOperator::CreateXor(A, D);
Bill Wendling22ca8352008-11-30 13:52:49 +00003498 // ((~B&A)|(~A&B)) -> A^B
Dan Gohmancdff2122009-08-12 16:23:25 +00003499 if ((match(A, m_Not(m_Specific(D))) &&
3500 match(B, m_Not(m_Specific(C)))))
Bill Wendlingc1f31132008-12-01 08:09:47 +00003501 return BinaryOperator::CreateXor(C, D);
Bill Wendling22ca8352008-11-30 13:52:49 +00003502 // ((A&~B)|(B&~A)) -> A^B
Dan Gohmancdff2122009-08-12 16:23:25 +00003503 if ((match(C, m_Not(m_Specific(B))) &&
3504 match(D, m_Not(m_Specific(A)))))
Bill Wendlingc1f31132008-12-01 08:09:47 +00003505 return BinaryOperator::CreateXor(A, B);
Bill Wendling22ca8352008-11-30 13:52:49 +00003506 // ((~B&A)|(B&~A)) -> A^B
Dan Gohmancdff2122009-08-12 16:23:25 +00003507 if ((match(A, m_Not(m_Specific(B))) &&
3508 match(D, m_Not(m_Specific(C)))))
Bill Wendlingc1f31132008-12-01 08:09:47 +00003509 return BinaryOperator::CreateXor(C, B);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003510 }
3511
3512 // (X >> Z) | (Y >> Z) -> (X|Y) >> Z for all shifts.
3513 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
3514 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
3515 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
3516 SI0->getOperand(1) == SI1->getOperand(1) &&
3517 (SI0->hasOneUse() || SI1->hasOneUse())) {
Chris Lattnerc7694852009-08-30 07:44:24 +00003518 Value *NewOp = Builder->CreateOr(SI0->getOperand(0), SI1->getOperand(0),
3519 SI0->getName());
Gabor Greifa645dd32008-05-16 19:29:10 +00003520 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003521 SI1->getOperand(1));
3522 }
3523 }
3524
Bill Wendlingd8ce2372008-12-01 01:07:11 +00003525 // ((A|B)&1)|(B&-2) -> (A&1) | B
Dan Gohmancdff2122009-08-12 16:23:25 +00003526 if (match(Op0, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C))) ||
3527 match(Op0, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))))) {
Bill Wendling9912f712008-12-01 08:32:40 +00003528 Instruction *Ret = FoldOrWithConstants(I, Op1, A, B, C);
Bill Wendlingdae376a2008-12-01 08:23:25 +00003529 if (Ret) return Ret;
Bill Wendlingd8ce2372008-12-01 01:07:11 +00003530 }
3531 // (B&-2)|((A|B)&1) -> (A&1) | B
Dan Gohmancdff2122009-08-12 16:23:25 +00003532 if (match(Op1, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C))) ||
3533 match(Op1, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))))) {
Bill Wendling9912f712008-12-01 08:32:40 +00003534 Instruction *Ret = FoldOrWithConstants(I, Op0, A, B, C);
Bill Wendlingdae376a2008-12-01 08:23:25 +00003535 if (Ret) return Ret;
Bill Wendlingd8ce2372008-12-01 01:07:11 +00003536 }
3537
Chris Lattnera3e46f62009-11-10 00:55:12 +00003538 // (~A | ~B) == (~(A & B)) - De Morgan's Law
3539 if (Value *Op0NotVal = dyn_castNotVal(Op0))
3540 if (Value *Op1NotVal = dyn_castNotVal(Op1))
3541 if (Op0->hasOneUse() && Op1->hasOneUse()) {
3542 Value *And = Builder->CreateAnd(Op0NotVal, Op1NotVal,
3543 I.getName()+".demorgan");
3544 return BinaryOperator::CreateNot(And);
3545 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003546
3547 // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
3548 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1))) {
Dan Gohmanfe91cd62009-08-12 16:04:34 +00003549 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003550 return R;
3551
Chris Lattner0c678e52008-11-16 05:20:07 +00003552 if (ICmpInst *LHS = dyn_cast<ICmpInst>(I.getOperand(0)))
3553 if (Instruction *Res = FoldOrOfICmps(I, LHS, RHS))
3554 return Res;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003555 }
3556
3557 // fold (or (cast A), (cast B)) -> (cast (or A, B))
Chris Lattner91882432007-10-24 05:38:08 +00003558 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003559 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
3560 if (Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
Evan Chenge3779cf2008-03-24 00:21:34 +00003561 if (!isa<ICmpInst>(Op0C->getOperand(0)) ||
3562 !isa<ICmpInst>(Op1C->getOperand(0))) {
3563 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattnercf373552009-07-23 05:32:17 +00003564 if (SrcTy == Op1C->getOperand(0)->getType() &&
3565 SrcTy->isIntOrIntVector() &&
Evan Chenge3779cf2008-03-24 00:21:34 +00003566 // Only do this if the casts both really cause code to be
3567 // generated.
3568 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
Chris Lattner54826cd2010-01-04 07:53:58 +00003569 I.getType()) &&
Evan Chenge3779cf2008-03-24 00:21:34 +00003570 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
Chris Lattner54826cd2010-01-04 07:53:58 +00003571 I.getType())) {
Chris Lattnerc7694852009-08-30 07:44:24 +00003572 Value *NewOp = Builder->CreateOr(Op0C->getOperand(0),
3573 Op1C->getOperand(0), I.getName());
Gabor Greifa645dd32008-05-16 19:29:10 +00003574 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Evan Chenge3779cf2008-03-24 00:21:34 +00003575 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003576 }
3577 }
Chris Lattner91882432007-10-24 05:38:08 +00003578 }
3579
3580
3581 // (fcmp uno x, c) | (fcmp uno y, c) -> (fcmp uno x, y)
3582 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
Chris Lattner57e66fa2009-07-23 05:46:22 +00003583 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
3584 if (Instruction *Res = FoldOrOfFCmps(I, LHS, RHS))
3585 return Res;
Chris Lattner91882432007-10-24 05:38:08 +00003586 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003587
3588 return Changed ? &I : 0;
3589}
3590
Dan Gohman089efff2008-05-13 00:00:25 +00003591namespace {
3592
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003593// XorSelf - Implements: X ^ X --> 0
3594struct XorSelf {
3595 Value *RHS;
3596 XorSelf(Value *rhs) : RHS(rhs) {}
3597 bool shouldApply(Value *LHS) const { return LHS == RHS; }
3598 Instruction *apply(BinaryOperator &Xor) const {
3599 return &Xor;
3600 }
3601};
3602
Dan Gohman089efff2008-05-13 00:00:25 +00003603}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003604
3605Instruction *InstCombiner::visitXor(BinaryOperator &I) {
3606 bool Changed = SimplifyCommutative(I);
3607 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3608
Evan Chenge5cd8032008-03-25 20:07:13 +00003609 if (isa<UndefValue>(Op1)) {
3610 if (isa<UndefValue>(Op0))
3611 // Handle undef ^ undef -> 0 special case. This is a common
3612 // idiom (misuse).
Owen Andersonaac28372009-07-31 20:28:14 +00003613 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003614 return ReplaceInstUsesWith(I, Op1); // X ^ undef -> undef
Evan Chenge5cd8032008-03-25 20:07:13 +00003615 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003616
3617 // xor X, X = 0, even if X is nested in a sequence of Xor's.
Dan Gohmanfe91cd62009-08-12 16:04:34 +00003618 if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
Chris Lattnerb933ea62007-08-05 08:47:58 +00003619 assert(Result == &I && "AssociativeOpt didn't work?"); Result=Result;
Owen Andersonaac28372009-07-31 20:28:14 +00003620 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003621 }
3622
3623 // See if we can simplify any instructions used by the instruction whose sole
3624 // purpose is to compute bits we don't care about.
Dan Gohman8fd520a2009-06-15 22:12:54 +00003625 if (SimplifyDemandedInstructionBits(I))
3626 return &I;
3627 if (isa<VectorType>(I.getType()))
3628 if (isa<ConstantAggregateZero>(Op1))
3629 return ReplaceInstUsesWith(I, Op0); // X ^ <0,0> -> X
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003630
3631 // Is this a ~ operation?
Dan Gohmanfe91cd62009-08-12 16:04:34 +00003632 if (Value *NotOp = dyn_castNotVal(&I)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003633 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(NotOp)) {
3634 if (Op0I->getOpcode() == Instruction::And ||
3635 Op0I->getOpcode() == Instruction::Or) {
Chris Lattner6e060db2009-10-26 15:40:07 +00003636 // ~(~X & Y) --> (X | ~Y) - De Morgan's Law
3637 // ~(~X | Y) === (X & ~Y) - De Morgan's Law
3638 if (dyn_castNotVal(Op0I->getOperand(1)))
3639 Op0I->swapOperands();
Dan Gohmanfe91cd62009-08-12 16:04:34 +00003640 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
Chris Lattnerc7694852009-08-30 07:44:24 +00003641 Value *NotY =
3642 Builder->CreateNot(Op0I->getOperand(1),
3643 Op0I->getOperand(1)->getName()+".not");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003644 if (Op0I->getOpcode() == Instruction::And)
Gabor Greifa645dd32008-05-16 19:29:10 +00003645 return BinaryOperator::CreateOr(Op0NotVal, NotY);
Chris Lattnerc7694852009-08-30 07:44:24 +00003646 return BinaryOperator::CreateAnd(Op0NotVal, NotY);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003647 }
Chris Lattner6e060db2009-10-26 15:40:07 +00003648
3649 // ~(X & Y) --> (~X | ~Y) - De Morgan's Law
3650 // ~(X | Y) === (~X & ~Y) - De Morgan's Law
3651 if (isFreeToInvert(Op0I->getOperand(0)) &&
3652 isFreeToInvert(Op0I->getOperand(1))) {
3653 Value *NotX =
3654 Builder->CreateNot(Op0I->getOperand(0), "notlhs");
3655 Value *NotY =
3656 Builder->CreateNot(Op0I->getOperand(1), "notrhs");
3657 if (Op0I->getOpcode() == Instruction::And)
3658 return BinaryOperator::CreateOr(NotX, NotY);
3659 return BinaryOperator::CreateAnd(NotX, NotY);
3660 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003661 }
3662 }
3663 }
3664
3665
3666 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner4580d452009-10-11 22:00:32 +00003667 if (RHS->isOne() && Op0->hasOneUse()) {
Bill Wendling61741952009-01-01 01:18:23 +00003668 // xor (cmp A, B), true = not (cmp A, B) = !cmp A, B
Nick Lewycky1405e922007-08-06 20:04:16 +00003669 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Op0))
Dan Gohmane6803b82009-08-25 23:17:54 +00003670 return new ICmpInst(ICI->getInversePredicate(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003671 ICI->getOperand(0), ICI->getOperand(1));
3672
Nick Lewycky1405e922007-08-06 20:04:16 +00003673 if (FCmpInst *FCI = dyn_cast<FCmpInst>(Op0))
Dan Gohmane6803b82009-08-25 23:17:54 +00003674 return new FCmpInst(FCI->getInversePredicate(),
Nick Lewycky1405e922007-08-06 20:04:16 +00003675 FCI->getOperand(0), FCI->getOperand(1));
3676 }
3677
Nick Lewycky0aa63aa2008-05-31 19:01:33 +00003678 // fold (xor(zext(cmp)), 1) and (xor(sext(cmp)), -1) to ext(!cmp).
3679 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
3680 if (CmpInst *CI = dyn_cast<CmpInst>(Op0C->getOperand(0))) {
3681 if (CI->hasOneUse() && Op0C->hasOneUse()) {
3682 Instruction::CastOps Opcode = Op0C->getOpcode();
Chris Lattnerc7694852009-08-30 07:44:24 +00003683 if ((Opcode == Instruction::ZExt || Opcode == Instruction::SExt) &&
3684 (RHS == ConstantExpr::getCast(Opcode,
Chris Lattner03a27b42010-01-04 07:02:48 +00003685 ConstantInt::getTrue(I.getContext()),
Chris Lattnerc7694852009-08-30 07:44:24 +00003686 Op0C->getDestTy()))) {
3687 CI->setPredicate(CI->getInversePredicate());
3688 return CastInst::Create(Opcode, CI, Op0C->getType());
Nick Lewycky0aa63aa2008-05-31 19:01:33 +00003689 }
3690 }
3691 }
3692 }
3693
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003694 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
3695 // ~(c-X) == X-c-1 == X+(-c-1)
3696 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
3697 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
Owen Anderson02b48c32009-07-29 18:55:55 +00003698 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
3699 Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
Owen Andersoneacb44d2009-07-24 23:12:02 +00003700 ConstantInt::get(I.getType(), 1));
Gabor Greifa645dd32008-05-16 19:29:10 +00003701 return BinaryOperator::CreateAdd(Op0I->getOperand(1), ConstantRHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003702 }
3703
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00003704 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003705 if (Op0I->getOpcode() == Instruction::Add) {
3706 // ~(X-c) --> (-c-1)-X
3707 if (RHS->isAllOnesValue()) {
Owen Anderson02b48c32009-07-29 18:55:55 +00003708 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
Gabor Greifa645dd32008-05-16 19:29:10 +00003709 return BinaryOperator::CreateSub(
Owen Anderson02b48c32009-07-29 18:55:55 +00003710 ConstantExpr::getSub(NegOp0CI,
Owen Andersoneacb44d2009-07-24 23:12:02 +00003711 ConstantInt::get(I.getType(), 1)),
Owen Anderson24be4c12009-07-03 00:17:18 +00003712 Op0I->getOperand(0));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003713 } else if (RHS->getValue().isSignBit()) {
3714 // (X + C) ^ signbit -> (X + C + signbit)
Chris Lattner03a27b42010-01-04 07:02:48 +00003715 Constant *C = ConstantInt::get(I.getContext(),
Owen Andersoneacb44d2009-07-24 23:12:02 +00003716 RHS->getValue() + Op0CI->getValue());
Gabor Greifa645dd32008-05-16 19:29:10 +00003717 return BinaryOperator::CreateAdd(Op0I->getOperand(0), C);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003718
3719 }
3720 } else if (Op0I->getOpcode() == Instruction::Or) {
3721 // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
3722 if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue())) {
Owen Anderson02b48c32009-07-29 18:55:55 +00003723 Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003724 // Anything in both C1 and C2 is known to be zero, remove it from
3725 // NewRHS.
Owen Anderson02b48c32009-07-29 18:55:55 +00003726 Constant *CommonBits = ConstantExpr::getAnd(Op0CI, RHS);
3727 NewRHS = ConstantExpr::getAnd(NewRHS,
3728 ConstantExpr::getNot(CommonBits));
Chris Lattner3183fb62009-08-30 06:13:40 +00003729 Worklist.Add(Op0I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003730 I.setOperand(0, Op0I->getOperand(0));
3731 I.setOperand(1, NewRHS);
3732 return &I;
3733 }
3734 }
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00003735 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003736 }
3737
3738 // Try to fold constant and into select arguments.
3739 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner54826cd2010-01-04 07:53:58 +00003740 if (Instruction *R = FoldOpIntoSelect(I, SI))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003741 return R;
3742 if (isa<PHINode>(Op0))
3743 if (Instruction *NV = FoldOpIntoPhi(I))
3744 return NV;
3745 }
3746
Dan Gohmanfe91cd62009-08-12 16:04:34 +00003747 if (Value *X = dyn_castNotVal(Op0)) // ~A ^ A == -1
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003748 if (X == Op1)
Owen Andersonaac28372009-07-31 20:28:14 +00003749 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003750
Dan Gohmanfe91cd62009-08-12 16:04:34 +00003751 if (Value *X = dyn_castNotVal(Op1)) // A ^ ~A == -1
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003752 if (X == Op0)
Owen Andersonaac28372009-07-31 20:28:14 +00003753 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003754
3755
3756 BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1);
3757 if (Op1I) {
3758 Value *A, *B;
Dan Gohmancdff2122009-08-12 16:23:25 +00003759 if (match(Op1I, m_Or(m_Value(A), m_Value(B)))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003760 if (A == Op0) { // B^(B|A) == (A|B)^B
3761 Op1I->swapOperands();
3762 I.swapOperands();
3763 std::swap(Op0, Op1);
3764 } else if (B == Op0) { // B^(A|B) == (A|B)^B
3765 I.swapOperands(); // Simplified below.
3766 std::swap(Op0, Op1);
3767 }
Dan Gohmancdff2122009-08-12 16:23:25 +00003768 } else if (match(Op1I, m_Xor(m_Specific(Op0), m_Value(B)))) {
Chris Lattner3b874082008-11-16 05:38:51 +00003769 return ReplaceInstUsesWith(I, B); // A^(A^B) == B
Dan Gohmancdff2122009-08-12 16:23:25 +00003770 } else if (match(Op1I, m_Xor(m_Value(A), m_Specific(Op0)))) {
Chris Lattner3b874082008-11-16 05:38:51 +00003771 return ReplaceInstUsesWith(I, A); // A^(B^A) == B
Dan Gohmancdff2122009-08-12 16:23:25 +00003772 } else if (match(Op1I, m_And(m_Value(A), m_Value(B))) &&
Owen Andersona21eb582009-07-10 17:35:01 +00003773 Op1I->hasOneUse()){
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003774 if (A == Op0) { // A^(A&B) -> A^(B&A)
3775 Op1I->swapOperands();
3776 std::swap(A, B);
3777 }
3778 if (B == Op0) { // A^(B&A) -> (B&A)^A
3779 I.swapOperands(); // Simplified below.
3780 std::swap(Op0, Op1);
3781 }
3782 }
3783 }
3784
3785 BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0);
3786 if (Op0I) {
3787 Value *A, *B;
Dan Gohmancdff2122009-08-12 16:23:25 +00003788 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
Owen Andersona21eb582009-07-10 17:35:01 +00003789 Op0I->hasOneUse()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003790 if (A == Op1) // (B|A)^B == (A|B)^B
3791 std::swap(A, B);
Chris Lattnerc7694852009-08-30 07:44:24 +00003792 if (B == Op1) // (A|B)^B == A & ~B
3793 return BinaryOperator::CreateAnd(A, Builder->CreateNot(Op1, "tmp"));
Dan Gohmancdff2122009-08-12 16:23:25 +00003794 } else if (match(Op0I, m_Xor(m_Specific(Op1), m_Value(B)))) {
Chris Lattner3b874082008-11-16 05:38:51 +00003795 return ReplaceInstUsesWith(I, B); // (A^B)^A == B
Dan Gohmancdff2122009-08-12 16:23:25 +00003796 } else if (match(Op0I, m_Xor(m_Value(A), m_Specific(Op1)))) {
Chris Lattner3b874082008-11-16 05:38:51 +00003797 return ReplaceInstUsesWith(I, A); // (B^A)^A == B
Dan Gohmancdff2122009-08-12 16:23:25 +00003798 } else if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
Owen Andersona21eb582009-07-10 17:35:01 +00003799 Op0I->hasOneUse()){
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003800 if (A == Op1) // (A&B)^A -> (B&A)^A
3801 std::swap(A, B);
3802 if (B == Op1 && // (B&A)^A == ~B & A
3803 !isa<ConstantInt>(Op1)) { // Canonical form is (B&C)^C
Chris Lattnerc7694852009-08-30 07:44:24 +00003804 return BinaryOperator::CreateAnd(Builder->CreateNot(A, "tmp"), Op1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003805 }
3806 }
3807 }
3808
3809 // (X >> Z) ^ (Y >> Z) -> (X^Y) >> Z for all shifts.
3810 if (Op0I && Op1I && Op0I->isShift() &&
3811 Op0I->getOpcode() == Op1I->getOpcode() &&
3812 Op0I->getOperand(1) == Op1I->getOperand(1) &&
3813 (Op1I->hasOneUse() || Op1I->hasOneUse())) {
Chris Lattnerc7694852009-08-30 07:44:24 +00003814 Value *NewOp =
3815 Builder->CreateXor(Op0I->getOperand(0), Op1I->getOperand(0),
3816 Op0I->getName());
Gabor Greifa645dd32008-05-16 19:29:10 +00003817 return BinaryOperator::Create(Op1I->getOpcode(), NewOp,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003818 Op1I->getOperand(1));
3819 }
3820
3821 if (Op0I && Op1I) {
3822 Value *A, *B, *C, *D;
3823 // (A & B)^(A | B) -> A ^ B
Dan Gohmancdff2122009-08-12 16:23:25 +00003824 if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
3825 match(Op1I, m_Or(m_Value(C), m_Value(D)))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003826 if ((A == C && B == D) || (A == D && B == C))
Gabor Greifa645dd32008-05-16 19:29:10 +00003827 return BinaryOperator::CreateXor(A, B);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003828 }
3829 // (A | B)^(A & B) -> A ^ B
Dan Gohmancdff2122009-08-12 16:23:25 +00003830 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
3831 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003832 if ((A == C && B == D) || (A == D && B == C))
Gabor Greifa645dd32008-05-16 19:29:10 +00003833 return BinaryOperator::CreateXor(A, B);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003834 }
3835
3836 // (A & B)^(C & D)
3837 if ((Op0I->hasOneUse() || Op1I->hasOneUse()) &&
Dan Gohmancdff2122009-08-12 16:23:25 +00003838 match(Op0I, m_And(m_Value(A), m_Value(B))) &&
3839 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003840 // (X & Y)^(X & Y) -> (Y^Z) & X
3841 Value *X = 0, *Y = 0, *Z = 0;
3842 if (A == C)
3843 X = A, Y = B, Z = D;
3844 else if (A == D)
3845 X = A, Y = B, Z = C;
3846 else if (B == C)
3847 X = B, Y = A, Z = D;
3848 else if (B == D)
3849 X = B, Y = A, Z = C;
3850
3851 if (X) {
Chris Lattnerc7694852009-08-30 07:44:24 +00003852 Value *NewOp = Builder->CreateXor(Y, Z, Op0->getName());
Gabor Greifa645dd32008-05-16 19:29:10 +00003853 return BinaryOperator::CreateAnd(NewOp, X);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003854 }
3855 }
3856 }
3857
3858 // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
3859 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
Dan Gohmanfe91cd62009-08-12 16:04:34 +00003860 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003861 return R;
3862
3863 // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
Chris Lattner91882432007-10-24 05:38:08 +00003864 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003865 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
3866 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
3867 const Type *SrcTy = Op0C->getOperand(0)->getType();
3868 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
3869 // Only do this if the casts both really cause code to be generated.
3870 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
Chris Lattner54826cd2010-01-04 07:53:58 +00003871 I.getType()) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003872 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
Chris Lattner54826cd2010-01-04 07:53:58 +00003873 I.getType())) {
Chris Lattnerc7694852009-08-30 07:44:24 +00003874 Value *NewOp = Builder->CreateXor(Op0C->getOperand(0),
3875 Op1C->getOperand(0), I.getName());
Gabor Greifa645dd32008-05-16 19:29:10 +00003876 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003877 }
3878 }
Chris Lattner91882432007-10-24 05:38:08 +00003879 }
Nick Lewycky0aa63aa2008-05-31 19:01:33 +00003880
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003881 return Changed ? &I : 0;
3882}
3883
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003884
3885Instruction *InstCombiner::visitShl(BinaryOperator &I) {
3886 return commonShiftTransforms(I);
3887}
3888
3889Instruction *InstCombiner::visitLShr(BinaryOperator &I) {
3890 return commonShiftTransforms(I);
3891}
3892
3893Instruction *InstCombiner::visitAShr(BinaryOperator &I) {
Chris Lattnere3c504f2007-12-06 01:59:46 +00003894 if (Instruction *R = commonShiftTransforms(I))
3895 return R;
3896
3897 Value *Op0 = I.getOperand(0);
3898
3899 // ashr int -1, X = -1 (for any arithmetic shift rights of ~0)
3900 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
3901 if (CSI->isAllOnesValue())
3902 return ReplaceInstUsesWith(I, CSI);
Dan Gohman843649e2009-02-24 02:00:40 +00003903
Dan Gohman2526aea2009-06-16 19:55:29 +00003904 // See if we can turn a signed shr into an unsigned shr.
3905 if (MaskedValueIsZero(Op0,
3906 APInt::getSignBit(I.getType()->getScalarSizeInBits())))
3907 return BinaryOperator::CreateLShr(Op0, I.getOperand(1));
3908
3909 // Arithmetic shifting an all-sign-bit value is a no-op.
3910 unsigned NumSignBits = ComputeNumSignBits(Op0);
3911 if (NumSignBits == Op0->getType()->getScalarSizeInBits())
3912 return ReplaceInstUsesWith(I, Op0);
Dan Gohman843649e2009-02-24 02:00:40 +00003913
Chris Lattnere3c504f2007-12-06 01:59:46 +00003914 return 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003915}
3916
3917Instruction *InstCombiner::commonShiftTransforms(BinaryOperator &I) {
3918 assert(I.getOperand(1)->getType() == I.getOperand(0)->getType());
3919 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3920
3921 // shl X, 0 == X and shr X, 0 == X
3922 // shl 0, X == 0 and shr 0, X == 0
Owen Andersonaac28372009-07-31 20:28:14 +00003923 if (Op1 == Constant::getNullValue(Op1->getType()) ||
3924 Op0 == Constant::getNullValue(Op0->getType()))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003925 return ReplaceInstUsesWith(I, Op0);
3926
3927 if (isa<UndefValue>(Op0)) {
3928 if (I.getOpcode() == Instruction::AShr) // undef >>s X -> undef
3929 return ReplaceInstUsesWith(I, Op0);
3930 else // undef << X -> 0, undef >>u X -> 0
Owen Andersonaac28372009-07-31 20:28:14 +00003931 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003932 }
3933 if (isa<UndefValue>(Op1)) {
3934 if (I.getOpcode() == Instruction::AShr) // X >>s undef -> X
3935 return ReplaceInstUsesWith(I, Op0);
3936 else // X << undef, X >>u undef -> 0
Owen Andersonaac28372009-07-31 20:28:14 +00003937 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003938 }
3939
Dan Gohman2bc21562009-05-21 02:28:33 +00003940 // See if we can fold away this shift.
Dan Gohman8fd520a2009-06-15 22:12:54 +00003941 if (SimplifyDemandedInstructionBits(I))
Dan Gohman2bc21562009-05-21 02:28:33 +00003942 return &I;
3943
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003944 // Try to fold constant and into select arguments.
3945 if (isa<Constant>(Op0))
3946 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner54826cd2010-01-04 07:53:58 +00003947 if (Instruction *R = FoldOpIntoSelect(I, SI))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003948 return R;
3949
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003950 if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
3951 if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
3952 return Res;
3953 return 0;
3954}
3955
3956Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
3957 BinaryOperator &I) {
Chris Lattner08817332009-01-31 08:24:16 +00003958 bool isLeftShift = I.getOpcode() == Instruction::Shl;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003959
3960 // See if we can simplify any instructions used by the instruction whose sole
3961 // purpose is to compute bits we don't care about.
Dan Gohman2526aea2009-06-16 19:55:29 +00003962 uint32_t TypeBits = Op0->getType()->getScalarSizeInBits();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003963
Dan Gohman9e1657f2009-06-14 23:30:43 +00003964 // shl i32 X, 32 = 0 and srl i8 Y, 9 = 0, ... just don't eliminate
3965 // a signed shift.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003966 //
3967 if (Op1->uge(TypeBits)) {
3968 if (I.getOpcode() != Instruction::AShr)
Owen Andersonaac28372009-07-31 20:28:14 +00003969 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003970 else {
Owen Andersoneacb44d2009-07-24 23:12:02 +00003971 I.setOperand(1, ConstantInt::get(I.getType(), TypeBits-1));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003972 return &I;
3973 }
3974 }
3975
3976 // ((X*C1) << C2) == (X * (C1 << C2))
3977 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
3978 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
3979 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
Gabor Greifa645dd32008-05-16 19:29:10 +00003980 return BinaryOperator::CreateMul(BO->getOperand(0),
Owen Anderson02b48c32009-07-29 18:55:55 +00003981 ConstantExpr::getShl(BOOp, Op1));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003982
3983 // Try to fold constant and into select arguments.
3984 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner54826cd2010-01-04 07:53:58 +00003985 if (Instruction *R = FoldOpIntoSelect(I, SI))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003986 return R;
3987 if (isa<PHINode>(Op0))
3988 if (Instruction *NV = FoldOpIntoPhi(I))
3989 return NV;
3990
Chris Lattnerc6d1f642007-12-22 09:07:47 +00003991 // Fold shift2(trunc(shift1(x,c1)), c2) -> trunc(shift2(shift1(x,c1),c2))
3992 if (TruncInst *TI = dyn_cast<TruncInst>(Op0)) {
3993 Instruction *TrOp = dyn_cast<Instruction>(TI->getOperand(0));
3994 // If 'shift2' is an ashr, we would have to get the sign bit into a funny
3995 // place. Don't try to do this transformation in this case. Also, we
3996 // require that the input operand is a shift-by-constant so that we have
3997 // confidence that the shifts will get folded together. We could do this
3998 // xform in more cases, but it is unlikely to be profitable.
3999 if (TrOp && I.isLogicalShift() && TrOp->isShift() &&
4000 isa<ConstantInt>(TrOp->getOperand(1))) {
4001 // Okay, we'll do this xform. Make the shift of shift.
Owen Anderson02b48c32009-07-29 18:55:55 +00004002 Constant *ShAmt = ConstantExpr::getZExt(Op1, TrOp->getType());
Chris Lattnerc7694852009-08-30 07:44:24 +00004003 // (shift2 (shift1 & 0x00FF), c2)
4004 Value *NSh = Builder->CreateBinOp(I.getOpcode(), TrOp, ShAmt,I.getName());
Chris Lattnerc6d1f642007-12-22 09:07:47 +00004005
4006 // For logical shifts, the truncation has the effect of making the high
4007 // part of the register be zeros. Emulate this by inserting an AND to
4008 // clear the top bits as needed. This 'and' will usually be zapped by
4009 // other xforms later if dead.
Dan Gohman2526aea2009-06-16 19:55:29 +00004010 unsigned SrcSize = TrOp->getType()->getScalarSizeInBits();
4011 unsigned DstSize = TI->getType()->getScalarSizeInBits();
Chris Lattnerc6d1f642007-12-22 09:07:47 +00004012 APInt MaskV(APInt::getLowBitsSet(SrcSize, DstSize));
4013
4014 // The mask we constructed says what the trunc would do if occurring
4015 // between the shifts. We want to know the effect *after* the second
4016 // shift. We know that it is a logical shift by a constant, so adjust the
4017 // mask as appropriate.
4018 if (I.getOpcode() == Instruction::Shl)
4019 MaskV <<= Op1->getZExtValue();
4020 else {
4021 assert(I.getOpcode() == Instruction::LShr && "Unknown logical shift");
4022 MaskV = MaskV.lshr(Op1->getZExtValue());
4023 }
4024
Chris Lattnerc7694852009-08-30 07:44:24 +00004025 // shift1 & 0x00FF
Chris Lattner03a27b42010-01-04 07:02:48 +00004026 Value *And = Builder->CreateAnd(NSh,
4027 ConstantInt::get(I.getContext(), MaskV),
Chris Lattnerc7694852009-08-30 07:44:24 +00004028 TI->getName());
Chris Lattnerc6d1f642007-12-22 09:07:47 +00004029
4030 // Return the value truncated to the interesting size.
4031 return new TruncInst(And, I.getType());
4032 }
4033 }
4034
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004035 if (Op0->hasOneUse()) {
4036 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
4037 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
4038 Value *V1, *V2;
4039 ConstantInt *CC;
4040 switch (Op0BO->getOpcode()) {
4041 default: break;
4042 case Instruction::Add:
4043 case Instruction::And:
4044 case Instruction::Or:
4045 case Instruction::Xor: {
4046 // These operators commute.
4047 // Turn (Y + (X >> C)) << C -> (X + (Y << C)) & (~0 << C)
4048 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
Owen Andersona21eb582009-07-10 17:35:01 +00004049 match(Op0BO->getOperand(1), m_Shr(m_Value(V1),
Chris Lattnerad7516a2009-08-30 18:50:58 +00004050 m_Specific(Op1)))) {
4051 Value *YS = // (Y << C)
4052 Builder->CreateShl(Op0BO->getOperand(0), Op1, Op0BO->getName());
4053 // (X + (Y << C))
4054 Value *X = Builder->CreateBinOp(Op0BO->getOpcode(), YS, V1,
4055 Op0BO->getOperand(1)->getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004056 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
Chris Lattner03a27b42010-01-04 07:02:48 +00004057 return BinaryOperator::CreateAnd(X, ConstantInt::get(I.getContext(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004058 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
4059 }
4060
4061 // Turn (Y + ((X >> C) & CC)) << C -> ((X & (CC << C)) + (Y << C))
4062 Value *Op0BOOp1 = Op0BO->getOperand(1);
4063 if (isLeftShift && Op0BOOp1->hasOneUse() &&
4064 match(Op0BOOp1,
Chris Lattner3b874082008-11-16 05:38:51 +00004065 m_And(m_Shr(m_Value(V1), m_Specific(Op1)),
Dan Gohmancdff2122009-08-12 16:23:25 +00004066 m_ConstantInt(CC))) &&
Chris Lattner3b874082008-11-16 05:38:51 +00004067 cast<BinaryOperator>(Op0BOOp1)->getOperand(0)->hasOneUse()) {
Chris Lattnerad7516a2009-08-30 18:50:58 +00004068 Value *YS = // (Y << C)
4069 Builder->CreateShl(Op0BO->getOperand(0), Op1,
4070 Op0BO->getName());
4071 // X & (CC << C)
4072 Value *XM = Builder->CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
4073 V1->getName()+".mask");
Gabor Greifa645dd32008-05-16 19:29:10 +00004074 return BinaryOperator::Create(Op0BO->getOpcode(), YS, XM);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004075 }
4076 }
4077
4078 // FALL THROUGH.
4079 case Instruction::Sub: {
4080 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
4081 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
Owen Andersona21eb582009-07-10 17:35:01 +00004082 match(Op0BO->getOperand(0), m_Shr(m_Value(V1),
Dan Gohmancdff2122009-08-12 16:23:25 +00004083 m_Specific(Op1)))) {
Chris Lattnerad7516a2009-08-30 18:50:58 +00004084 Value *YS = // (Y << C)
4085 Builder->CreateShl(Op0BO->getOperand(1), Op1, Op0BO->getName());
4086 // (X + (Y << C))
4087 Value *X = Builder->CreateBinOp(Op0BO->getOpcode(), V1, YS,
4088 Op0BO->getOperand(0)->getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004089 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
Chris Lattner03a27b42010-01-04 07:02:48 +00004090 return BinaryOperator::CreateAnd(X, ConstantInt::get(I.getContext(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004091 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
4092 }
4093
4094 // Turn (((X >> C)&CC) + Y) << C -> (X + (Y << C)) & (CC << C)
4095 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
4096 match(Op0BO->getOperand(0),
4097 m_And(m_Shr(m_Value(V1), m_Value(V2)),
Dan Gohmancdff2122009-08-12 16:23:25 +00004098 m_ConstantInt(CC))) && V2 == Op1 &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004099 cast<BinaryOperator>(Op0BO->getOperand(0))
4100 ->getOperand(0)->hasOneUse()) {
Chris Lattnerad7516a2009-08-30 18:50:58 +00004101 Value *YS = // (Y << C)
4102 Builder->CreateShl(Op0BO->getOperand(1), Op1, Op0BO->getName());
4103 // X & (CC << C)
4104 Value *XM = Builder->CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
4105 V1->getName()+".mask");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004106
Gabor Greifa645dd32008-05-16 19:29:10 +00004107 return BinaryOperator::Create(Op0BO->getOpcode(), XM, YS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004108 }
4109
4110 break;
4111 }
4112 }
4113
4114
4115 // If the operand is an bitwise operator with a constant RHS, and the
4116 // shift is the only use, we can pull it out of the shift.
4117 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
4118 bool isValid = true; // Valid only for And, Or, Xor
4119 bool highBitSet = false; // Transform if high bit of constant set?
4120
4121 switch (Op0BO->getOpcode()) {
4122 default: isValid = false; break; // Do not perform transform!
4123 case Instruction::Add:
4124 isValid = isLeftShift;
4125 break;
4126 case Instruction::Or:
4127 case Instruction::Xor:
4128 highBitSet = false;
4129 break;
4130 case Instruction::And:
4131 highBitSet = true;
4132 break;
4133 }
4134
4135 // If this is a signed shift right, and the high bit is modified
4136 // by the logical operation, do not perform the transformation.
4137 // The highBitSet boolean indicates the value of the high bit of
4138 // the constant which would cause it to be modified for this
4139 // operation.
4140 //
Chris Lattner15b76e32007-12-06 06:25:04 +00004141 if (isValid && I.getOpcode() == Instruction::AShr)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004142 isValid = Op0C->getValue()[TypeBits-1] == highBitSet;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004143
4144 if (isValid) {
Owen Anderson02b48c32009-07-29 18:55:55 +00004145 Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004146
Chris Lattnerad7516a2009-08-30 18:50:58 +00004147 Value *NewShift =
4148 Builder->CreateBinOp(I.getOpcode(), Op0BO->getOperand(0), Op1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004149 NewShift->takeName(Op0BO);
4150
Gabor Greifa645dd32008-05-16 19:29:10 +00004151 return BinaryOperator::Create(Op0BO->getOpcode(), NewShift,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004152 NewRHS);
4153 }
4154 }
4155 }
4156 }
4157
4158 // Find out if this is a shift of a shift by a constant.
4159 BinaryOperator *ShiftOp = dyn_cast<BinaryOperator>(Op0);
4160 if (ShiftOp && !ShiftOp->isShift())
4161 ShiftOp = 0;
4162
4163 if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
4164 ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
4165 uint32_t ShiftAmt1 = ShiftAmt1C->getLimitedValue(TypeBits);
4166 uint32_t ShiftAmt2 = Op1->getLimitedValue(TypeBits);
4167 assert(ShiftAmt2 != 0 && "Should have been simplified earlier");
4168 if (ShiftAmt1 == 0) return 0; // Will be simplified in the future.
4169 Value *X = ShiftOp->getOperand(0);
4170
4171 uint32_t AmtSum = ShiftAmt1+ShiftAmt2; // Fold into one big shift.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004172
4173 const IntegerType *Ty = cast<IntegerType>(I.getType());
4174
4175 // Check for (X << c1) << c2 and (X >> c1) >> c2
4176 if (I.getOpcode() == ShiftOp->getOpcode()) {
Chris Lattnerb36c7012009-03-20 22:41:15 +00004177 // If this is oversized composite shift, then unsigned shifts get 0, ashr
4178 // saturates.
4179 if (AmtSum >= TypeBits) {
4180 if (I.getOpcode() != Instruction::AShr)
Owen Andersonaac28372009-07-31 20:28:14 +00004181 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerb36c7012009-03-20 22:41:15 +00004182 AmtSum = TypeBits-1; // Saturate to 31 for i32 ashr.
4183 }
4184
Gabor Greifa645dd32008-05-16 19:29:10 +00004185 return BinaryOperator::Create(I.getOpcode(), X,
Owen Andersoneacb44d2009-07-24 23:12:02 +00004186 ConstantInt::get(Ty, AmtSum));
Chris Lattnerad7516a2009-08-30 18:50:58 +00004187 }
4188
4189 if (ShiftOp->getOpcode() == Instruction::LShr &&
4190 I.getOpcode() == Instruction::AShr) {
Chris Lattnerb36c7012009-03-20 22:41:15 +00004191 if (AmtSum >= TypeBits)
Owen Andersonaac28372009-07-31 20:28:14 +00004192 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerb36c7012009-03-20 22:41:15 +00004193
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004194 // ((X >>u C1) >>s C2) -> (X >>u (C1+C2)) since C1 != 0.
Owen Andersoneacb44d2009-07-24 23:12:02 +00004195 return BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, AmtSum));
Chris Lattnerad7516a2009-08-30 18:50:58 +00004196 }
4197
4198 if (ShiftOp->getOpcode() == Instruction::AShr &&
4199 I.getOpcode() == Instruction::LShr) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004200 // ((X >>s C1) >>u C2) -> ((X >>s (C1+C2)) & mask) since C1 != 0.
Chris Lattnerb36c7012009-03-20 22:41:15 +00004201 if (AmtSum >= TypeBits)
4202 AmtSum = TypeBits-1;
4203
Chris Lattnerad7516a2009-08-30 18:50:58 +00004204 Value *Shift = Builder->CreateAShr(X, ConstantInt::get(Ty, AmtSum));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004205
4206 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Chris Lattner03a27b42010-01-04 07:02:48 +00004207 return BinaryOperator::CreateAnd(Shift,
4208 ConstantInt::get(I.getContext(), Mask));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004209 }
4210
4211 // Okay, if we get here, one shift must be left, and the other shift must be
4212 // right. See if the amounts are equal.
4213 if (ShiftAmt1 == ShiftAmt2) {
4214 // If we have ((X >>? C) << C), turn this into X & (-1 << C).
4215 if (I.getOpcode() == Instruction::Shl) {
4216 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt1));
Chris Lattner03a27b42010-01-04 07:02:48 +00004217 return BinaryOperator::CreateAnd(X,
4218 ConstantInt::get(I.getContext(),Mask));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004219 }
4220 // If we have ((X << C) >>u C), turn this into X & (-1 >>u C).
4221 if (I.getOpcode() == Instruction::LShr) {
4222 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt1));
Chris Lattner03a27b42010-01-04 07:02:48 +00004223 return BinaryOperator::CreateAnd(X,
4224 ConstantInt::get(I.getContext(), Mask));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004225 }
4226 // We can simplify ((X << C) >>s C) into a trunc + sext.
4227 // NOTE: we could do this for any C, but that would make 'unusual' integer
4228 // types. For now, just stick to ones well-supported by the code
4229 // generators.
4230 const Type *SExtType = 0;
4231 switch (Ty->getBitWidth() - ShiftAmt1) {
4232 case 1 :
4233 case 8 :
4234 case 16 :
4235 case 32 :
4236 case 64 :
4237 case 128:
Chris Lattner03a27b42010-01-04 07:02:48 +00004238 SExtType = IntegerType::get(I.getContext(),
4239 Ty->getBitWidth() - ShiftAmt1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004240 break;
4241 default: break;
4242 }
Chris Lattnerad7516a2009-08-30 18:50:58 +00004243 if (SExtType)
4244 return new SExtInst(Builder->CreateTrunc(X, SExtType, "sext"), Ty);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004245 // Otherwise, we can't handle it yet.
4246 } else if (ShiftAmt1 < ShiftAmt2) {
4247 uint32_t ShiftDiff = ShiftAmt2-ShiftAmt1;
4248
4249 // (X >>? C1) << C2 --> X << (C2-C1) & (-1 << C2)
4250 if (I.getOpcode() == Instruction::Shl) {
4251 assert(ShiftOp->getOpcode() == Instruction::LShr ||
4252 ShiftOp->getOpcode() == Instruction::AShr);
Chris Lattnerad7516a2009-08-30 18:50:58 +00004253 Value *Shift = Builder->CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004254
4255 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersoneacb44d2009-07-24 23:12:02 +00004256 return BinaryOperator::CreateAnd(Shift,
Chris Lattner03a27b42010-01-04 07:02:48 +00004257 ConstantInt::get(I.getContext(),Mask));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004258 }
4259
4260 // (X << C1) >>u C2 --> X >>u (C2-C1) & (-1 >> C2)
4261 if (I.getOpcode() == Instruction::LShr) {
4262 assert(ShiftOp->getOpcode() == Instruction::Shl);
Chris Lattnerad7516a2009-08-30 18:50:58 +00004263 Value *Shift = Builder->CreateLShr(X, ConstantInt::get(Ty, ShiftDiff));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004264
4265 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersoneacb44d2009-07-24 23:12:02 +00004266 return BinaryOperator::CreateAnd(Shift,
Chris Lattner03a27b42010-01-04 07:02:48 +00004267 ConstantInt::get(I.getContext(),Mask));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004268 }
4269
4270 // We can't handle (X << C1) >>s C2, it shifts arbitrary bits in.
4271 } else {
4272 assert(ShiftAmt2 < ShiftAmt1);
4273 uint32_t ShiftDiff = ShiftAmt1-ShiftAmt2;
4274
4275 // (X >>? C1) << C2 --> X >>? (C1-C2) & (-1 << C2)
4276 if (I.getOpcode() == Instruction::Shl) {
4277 assert(ShiftOp->getOpcode() == Instruction::LShr ||
4278 ShiftOp->getOpcode() == Instruction::AShr);
Chris Lattnerad7516a2009-08-30 18:50:58 +00004279 Value *Shift = Builder->CreateBinOp(ShiftOp->getOpcode(), X,
4280 ConstantInt::get(Ty, ShiftDiff));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004281
4282 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersoneacb44d2009-07-24 23:12:02 +00004283 return BinaryOperator::CreateAnd(Shift,
Chris Lattner03a27b42010-01-04 07:02:48 +00004284 ConstantInt::get(I.getContext(),Mask));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004285 }
4286
4287 // (X << C1) >>u C2 --> X << (C1-C2) & (-1 >> C2)
4288 if (I.getOpcode() == Instruction::LShr) {
4289 assert(ShiftOp->getOpcode() == Instruction::Shl);
Chris Lattnerad7516a2009-08-30 18:50:58 +00004290 Value *Shift = Builder->CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004291
4292 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersoneacb44d2009-07-24 23:12:02 +00004293 return BinaryOperator::CreateAnd(Shift,
Chris Lattner03a27b42010-01-04 07:02:48 +00004294 ConstantInt::get(I.getContext(),Mask));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004295 }
4296
4297 // We can't handle (X << C1) >>a C2, it shifts arbitrary bits in.
4298 }
4299 }
4300 return 0;
4301}
4302
4303
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004304
Chris Lattner94ccd5f2009-01-09 05:44:56 +00004305/// FindElementAtOffset - Given a type and a constant offset, determine whether
4306/// or not there is a sequence of GEP indices into the type that will land us at
Chris Lattner54dddc72009-01-24 01:00:13 +00004307/// the specified offset. If so, fill them into NewIndices and return the
4308/// resultant element type, otherwise return null.
Chris Lattner54826cd2010-01-04 07:53:58 +00004309const Type *InstCombiner::FindElementAtOffset(const Type *Ty, int64_t Offset,
4310 SmallVectorImpl<Value*> &NewIndices) {
Dan Gohmana80e2712009-07-21 23:21:54 +00004311 if (!TD) return 0;
Chris Lattner54dddc72009-01-24 01:00:13 +00004312 if (!Ty->isSized()) return 0;
Chris Lattner94ccd5f2009-01-09 05:44:56 +00004313
4314 // Start with the index over the outer type. Note that the type size
4315 // might be zero (even if the offset isn't zero) if the indexed type
4316 // is something like [0 x {int, int}]
Chris Lattner03a27b42010-01-04 07:02:48 +00004317 const Type *IntPtrTy = TD->getIntPtrType(Ty->getContext());
Chris Lattner94ccd5f2009-01-09 05:44:56 +00004318 int64_t FirstIdx = 0;
Duncan Sandsec4f97d2009-05-09 07:06:46 +00004319 if (int64_t TySize = TD->getTypeAllocSize(Ty)) {
Chris Lattner94ccd5f2009-01-09 05:44:56 +00004320 FirstIdx = Offset/TySize;
Chris Lattner0bd6f2b2009-01-11 20:41:36 +00004321 Offset -= FirstIdx*TySize;
Chris Lattner94ccd5f2009-01-09 05:44:56 +00004322
Chris Lattnerce48c462009-01-11 20:15:20 +00004323 // Handle hosts where % returns negative instead of values [0..TySize).
Chris Lattner94ccd5f2009-01-09 05:44:56 +00004324 if (Offset < 0) {
4325 --FirstIdx;
4326 Offset += TySize;
4327 assert(Offset >= 0);
4328 }
4329 assert((uint64_t)Offset < (uint64_t)TySize && "Out of range offset");
4330 }
4331
Owen Andersoneacb44d2009-07-24 23:12:02 +00004332 NewIndices.push_back(ConstantInt::get(IntPtrTy, FirstIdx));
Chris Lattner94ccd5f2009-01-09 05:44:56 +00004333
4334 // Index into the types. If we fail, set OrigBase to null.
4335 while (Offset) {
Chris Lattnerce48c462009-01-11 20:15:20 +00004336 // Indexing into tail padding between struct/array elements.
4337 if (uint64_t(Offset*8) >= TD->getTypeSizeInBits(Ty))
Chris Lattner54dddc72009-01-24 01:00:13 +00004338 return 0;
Chris Lattnerce48c462009-01-11 20:15:20 +00004339
Chris Lattner94ccd5f2009-01-09 05:44:56 +00004340 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
4341 const StructLayout *SL = TD->getStructLayout(STy);
Chris Lattnerce48c462009-01-11 20:15:20 +00004342 assert(Offset < (int64_t)SL->getSizeInBytes() &&
4343 "Offset must stay within the indexed type");
4344
Chris Lattner94ccd5f2009-01-09 05:44:56 +00004345 unsigned Elt = SL->getElementContainingOffset(Offset);
Chris Lattner03a27b42010-01-04 07:02:48 +00004346 NewIndices.push_back(ConstantInt::get(Type::getInt32Ty(Ty->getContext()),
4347 Elt));
Chris Lattner94ccd5f2009-01-09 05:44:56 +00004348
4349 Offset -= SL->getElementOffset(Elt);
4350 Ty = STy->getElementType(Elt);
Chris Lattnerd35ce6a2009-01-11 20:23:52 +00004351 } else if (const ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
Duncan Sandsec4f97d2009-05-09 07:06:46 +00004352 uint64_t EltSize = TD->getTypeAllocSize(AT->getElementType());
Chris Lattnerce48c462009-01-11 20:15:20 +00004353 assert(EltSize && "Cannot index into a zero-sized array");
Owen Andersoneacb44d2009-07-24 23:12:02 +00004354 NewIndices.push_back(ConstantInt::get(IntPtrTy,Offset/EltSize));
Chris Lattnerce48c462009-01-11 20:15:20 +00004355 Offset %= EltSize;
Chris Lattnerd35ce6a2009-01-11 20:23:52 +00004356 Ty = AT->getElementType();
Chris Lattner94ccd5f2009-01-09 05:44:56 +00004357 } else {
Chris Lattnerce48c462009-01-11 20:15:20 +00004358 // Otherwise, we can't index into the middle of this atomic type, bail.
Chris Lattner54dddc72009-01-24 01:00:13 +00004359 return 0;
Chris Lattner94ccd5f2009-01-09 05:44:56 +00004360 }
4361 }
4362
Chris Lattner54dddc72009-01-24 01:00:13 +00004363 return Ty;
Chris Lattner94ccd5f2009-01-09 05:44:56 +00004364}
4365
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004366
Dan Gohman2d648bb2008-04-10 18:43:06 +00004367/// EnforceKnownAlignment - If the specified pointer points to an object that
4368/// we control, modify the object's alignment to PrefAlign. This isn't
4369/// often possible though. If alignment is important, a more reliable approach
4370/// is to simply align all global variables and allocation instructions to
4371/// their preferred alignment from the beginning.
4372///
4373static unsigned EnforceKnownAlignment(Value *V,
4374 unsigned Align, unsigned PrefAlign) {
Chris Lattner47cf3452007-08-09 19:05:49 +00004375
Dan Gohman2d648bb2008-04-10 18:43:06 +00004376 User *U = dyn_cast<User>(V);
4377 if (!U) return Align;
4378
Dan Gohman9545fb02009-07-17 20:47:02 +00004379 switch (Operator::getOpcode(U)) {
Dan Gohman2d648bb2008-04-10 18:43:06 +00004380 default: break;
4381 case Instruction::BitCast:
4382 return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
4383 case Instruction::GetElementPtr: {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004384 // If all indexes are zero, it is just the alignment of the base pointer.
4385 bool AllZeroOperands = true;
Gabor Greife92fbe22008-06-12 21:51:29 +00004386 for (User::op_iterator i = U->op_begin() + 1, e = U->op_end(); i != e; ++i)
Gabor Greif17396002008-06-12 21:37:33 +00004387 if (!isa<Constant>(*i) ||
4388 !cast<Constant>(*i)->isNullValue()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004389 AllZeroOperands = false;
4390 break;
4391 }
Chris Lattner47cf3452007-08-09 19:05:49 +00004392
4393 if (AllZeroOperands) {
4394 // Treat this like a bitcast.
Dan Gohman2d648bb2008-04-10 18:43:06 +00004395 return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
Chris Lattner47cf3452007-08-09 19:05:49 +00004396 }
Dan Gohman2d648bb2008-04-10 18:43:06 +00004397 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004398 }
Dan Gohman2d648bb2008-04-10 18:43:06 +00004399 }
4400
4401 if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
4402 // If there is a large requested alignment and we can, bump up the alignment
4403 // of the global.
4404 if (!GV->isDeclaration()) {
Dan Gohmanf6fe71e2009-02-16 23:02:21 +00004405 if (GV->getAlignment() >= PrefAlign)
4406 Align = GV->getAlignment();
4407 else {
4408 GV->setAlignment(PrefAlign);
4409 Align = PrefAlign;
4410 }
Dan Gohman2d648bb2008-04-10 18:43:06 +00004411 }
Chris Lattnere8ad9ae2009-09-27 21:42:46 +00004412 } else if (AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
4413 // If there is a requested alignment and if this is an alloca, round up.
4414 if (AI->getAlignment() >= PrefAlign)
4415 Align = AI->getAlignment();
4416 else {
4417 AI->setAlignment(PrefAlign);
4418 Align = PrefAlign;
Dan Gohman2d648bb2008-04-10 18:43:06 +00004419 }
4420 }
4421
4422 return Align;
4423}
4424
4425/// GetOrEnforceKnownAlignment - If the specified pointer has an alignment that
4426/// we can determine, return it, otherwise return 0. If PrefAlign is specified,
4427/// and it is more than the alignment of the ultimate object, see if we can
4428/// increase the alignment of the ultimate object, making this check succeed.
4429unsigned InstCombiner::GetOrEnforceKnownAlignment(Value *V,
4430 unsigned PrefAlign) {
4431 unsigned BitWidth = TD ? TD->getTypeSizeInBits(V->getType()) :
4432 sizeof(PrefAlign) * CHAR_BIT;
4433 APInt Mask = APInt::getAllOnesValue(BitWidth);
4434 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
4435 ComputeMaskedBits(V, Mask, KnownZero, KnownOne);
4436 unsigned TrailZ = KnownZero.countTrailingOnes();
4437 unsigned Align = 1u << std::min(BitWidth - 1, TrailZ);
4438
4439 if (PrefAlign > Align)
4440 Align = EnforceKnownAlignment(V, Align, PrefAlign);
4441
4442 // We don't need to make any adjustment.
4443 return Align;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004444}
4445
Chris Lattner00ae5132008-01-13 23:50:23 +00004446Instruction *InstCombiner::SimplifyMemTransfer(MemIntrinsic *MI) {
Dan Gohman2d648bb2008-04-10 18:43:06 +00004447 unsigned DstAlign = GetOrEnforceKnownAlignment(MI->getOperand(1));
Dan Gohmaneb254912009-02-22 18:06:32 +00004448 unsigned SrcAlign = GetOrEnforceKnownAlignment(MI->getOperand(2));
Chris Lattner00ae5132008-01-13 23:50:23 +00004449 unsigned MinAlign = std::min(DstAlign, SrcAlign);
Chris Lattner3947da72009-03-08 03:59:00 +00004450 unsigned CopyAlign = MI->getAlignment();
Chris Lattner00ae5132008-01-13 23:50:23 +00004451
4452 if (CopyAlign < MinAlign) {
Owen Andersoneacb44d2009-07-24 23:12:02 +00004453 MI->setAlignment(ConstantInt::get(MI->getAlignmentType(),
Owen Andersonf9f99362009-07-09 18:36:20 +00004454 MinAlign, false));
Chris Lattner00ae5132008-01-13 23:50:23 +00004455 return MI;
4456 }
4457
4458 // If MemCpyInst length is 1/2/4/8 bytes then replace memcpy with
4459 // load/store.
4460 ConstantInt *MemOpLength = dyn_cast<ConstantInt>(MI->getOperand(3));
4461 if (MemOpLength == 0) return 0;
4462
Chris Lattnerc669fb62008-01-14 00:28:35 +00004463 // Source and destination pointer types are always "i8*" for intrinsic. See
4464 // if the size is something we can handle with a single primitive load/store.
4465 // A single load+store correctly handles overlapping memory in the memmove
4466 // case.
Chris Lattner00ae5132008-01-13 23:50:23 +00004467 unsigned Size = MemOpLength->getZExtValue();
Chris Lattner5af8a912008-04-30 06:39:11 +00004468 if (Size == 0) return MI; // Delete this mem transfer.
4469
4470 if (Size > 8 || (Size&(Size-1)))
Chris Lattnerc669fb62008-01-14 00:28:35 +00004471 return 0; // If not 1/2/4/8 bytes, exit.
Chris Lattner00ae5132008-01-13 23:50:23 +00004472
Chris Lattnerc669fb62008-01-14 00:28:35 +00004473 // Use an integer load+store unless we can find something better.
Owen Anderson24be4c12009-07-03 00:17:18 +00004474 Type *NewPtrTy =
Chris Lattner03a27b42010-01-04 07:02:48 +00004475 PointerType::getUnqual(IntegerType::get(MI->getContext(), Size<<3));
Chris Lattnerc669fb62008-01-14 00:28:35 +00004476
4477 // Memcpy forces the use of i8* for the source and destination. That means
4478 // that if you're using memcpy to move one double around, you'll get a cast
4479 // from double* to i8*. We'd much rather use a double load+store rather than
4480 // an i64 load+store, here because this improves the odds that the source or
4481 // dest address will be promotable. See if we can find a better type than the
4482 // integer datatype.
4483 if (Value *Op = getBitCastOperand(MI->getOperand(1))) {
4484 const Type *SrcETy = cast<PointerType>(Op->getType())->getElementType();
Dan Gohmana80e2712009-07-21 23:21:54 +00004485 if (TD && SrcETy->isSized() && TD->getTypeStoreSize(SrcETy) == Size) {
Chris Lattnerc669fb62008-01-14 00:28:35 +00004486 // The SrcETy might be something like {{{double}}} or [1 x double]. Rip
4487 // down through these levels if so.
Dan Gohmanb8e94f62008-05-23 01:52:21 +00004488 while (!SrcETy->isSingleValueType()) {
Chris Lattnerc669fb62008-01-14 00:28:35 +00004489 if (const StructType *STy = dyn_cast<StructType>(SrcETy)) {
4490 if (STy->getNumElements() == 1)
4491 SrcETy = STy->getElementType(0);
4492 else
4493 break;
4494 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcETy)) {
4495 if (ATy->getNumElements() == 1)
4496 SrcETy = ATy->getElementType();
4497 else
4498 break;
4499 } else
4500 break;
4501 }
4502
Dan Gohmanb8e94f62008-05-23 01:52:21 +00004503 if (SrcETy->isSingleValueType())
Owen Anderson6b6e2d92009-07-29 22:17:13 +00004504 NewPtrTy = PointerType::getUnqual(SrcETy);
Chris Lattnerc669fb62008-01-14 00:28:35 +00004505 }
4506 }
4507
4508
Chris Lattner00ae5132008-01-13 23:50:23 +00004509 // If the memcpy/memmove provides better alignment info than we can
4510 // infer, use it.
4511 SrcAlign = std::max(SrcAlign, CopyAlign);
4512 DstAlign = std::max(DstAlign, CopyAlign);
4513
Chris Lattner78628292009-08-30 19:47:22 +00004514 Value *Src = Builder->CreateBitCast(MI->getOperand(2), NewPtrTy);
4515 Value *Dest = Builder->CreateBitCast(MI->getOperand(1), NewPtrTy);
Chris Lattnerc669fb62008-01-14 00:28:35 +00004516 Instruction *L = new LoadInst(Src, "tmp", false, SrcAlign);
4517 InsertNewInstBefore(L, *MI);
4518 InsertNewInstBefore(new StoreInst(L, Dest, false, DstAlign), *MI);
4519
4520 // Set the size of the copy to 0, it will be deleted on the next iteration.
Owen Andersonaac28372009-07-31 20:28:14 +00004521 MI->setOperand(3, Constant::getNullValue(MemOpLength->getType()));
Chris Lattnerc669fb62008-01-14 00:28:35 +00004522 return MI;
Chris Lattner00ae5132008-01-13 23:50:23 +00004523}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004524
Chris Lattner5af8a912008-04-30 06:39:11 +00004525Instruction *InstCombiner::SimplifyMemSet(MemSetInst *MI) {
4526 unsigned Alignment = GetOrEnforceKnownAlignment(MI->getDest());
Chris Lattner3947da72009-03-08 03:59:00 +00004527 if (MI->getAlignment() < Alignment) {
Owen Andersoneacb44d2009-07-24 23:12:02 +00004528 MI->setAlignment(ConstantInt::get(MI->getAlignmentType(),
Owen Andersonf9f99362009-07-09 18:36:20 +00004529 Alignment, false));
Chris Lattner5af8a912008-04-30 06:39:11 +00004530 return MI;
4531 }
4532
4533 // Extract the length and alignment and fill if they are constant.
4534 ConstantInt *LenC = dyn_cast<ConstantInt>(MI->getLength());
4535 ConstantInt *FillC = dyn_cast<ConstantInt>(MI->getValue());
Chris Lattner03a27b42010-01-04 07:02:48 +00004536 if (!LenC || !FillC || FillC->getType() != Type::getInt8Ty(MI->getContext()))
Chris Lattner5af8a912008-04-30 06:39:11 +00004537 return 0;
4538 uint64_t Len = LenC->getZExtValue();
Chris Lattner3947da72009-03-08 03:59:00 +00004539 Alignment = MI->getAlignment();
Chris Lattner5af8a912008-04-30 06:39:11 +00004540
4541 // If the length is zero, this is a no-op
4542 if (Len == 0) return MI; // memset(d,c,0,a) -> noop
4543
4544 // memset(s,c,n) -> store s, c (for n=1,2,4,8)
4545 if (Len <= 8 && isPowerOf2_32((uint32_t)Len)) {
Chris Lattner03a27b42010-01-04 07:02:48 +00004546 const Type *ITy = IntegerType::get(MI->getContext(), Len*8); // n=1 -> i8.
Chris Lattner5af8a912008-04-30 06:39:11 +00004547
4548 Value *Dest = MI->getDest();
Chris Lattner78628292009-08-30 19:47:22 +00004549 Dest = Builder->CreateBitCast(Dest, PointerType::getUnqual(ITy));
Chris Lattner5af8a912008-04-30 06:39:11 +00004550
4551 // Alignment 0 is identity for alignment 1 for memset, but not store.
4552 if (Alignment == 0) Alignment = 1;
4553
4554 // Extract the fill value and store.
4555 uint64_t Fill = FillC->getZExtValue()*0x0101010101010101ULL;
Owen Andersoneacb44d2009-07-24 23:12:02 +00004556 InsertNewInstBefore(new StoreInst(ConstantInt::get(ITy, Fill),
Owen Anderson24be4c12009-07-03 00:17:18 +00004557 Dest, false, Alignment), *MI);
Chris Lattner5af8a912008-04-30 06:39:11 +00004558
4559 // Set the size of the copy to 0, it will be deleted on the next iteration.
Owen Andersonaac28372009-07-31 20:28:14 +00004560 MI->setLength(Constant::getNullValue(LenC->getType()));
Chris Lattner5af8a912008-04-30 06:39:11 +00004561 return MI;
4562 }
4563
4564 return 0;
4565}
4566
4567
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004568/// visitCallInst - CallInst simplification. This mostly only handles folding
4569/// of intrinsic instructions. For normal calls, it allows visitCallSite to do
4570/// the heavy lifting.
4571///
4572Instruction *InstCombiner::visitCallInst(CallInst &CI) {
Victor Hernandez93946082009-10-24 04:23:03 +00004573 if (isFreeCall(&CI))
4574 return visitFree(CI);
4575
Chris Lattneraa295aa2009-05-13 17:39:14 +00004576 // If the caller function is nounwind, mark the call as nounwind, even if the
4577 // callee isn't.
4578 if (CI.getParent()->getParent()->doesNotThrow() &&
4579 !CI.doesNotThrow()) {
4580 CI.setDoesNotThrow();
4581 return &CI;
4582 }
4583
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004584 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
4585 if (!II) return visitCallSite(&CI);
4586
4587 // Intrinsics cannot occur in an invoke, so handle them here instead of in
4588 // visitCallSite.
4589 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
4590 bool Changed = false;
4591
4592 // memmove/cpy/set of zero bytes is a noop.
4593 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
4594 if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
4595
4596 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
4597 if (CI->getZExtValue() == 1) {
4598 // Replace the instruction with just byte operations. We would
4599 // transform other cases to loads/stores, but we don't know if
4600 // alignment is sufficient.
4601 }
4602 }
4603
4604 // If we have a memmove and the source operation is a constant global,
4605 // then the source and dest pointers can't alias, so we can change this
4606 // into a call to memcpy.
Chris Lattner00ae5132008-01-13 23:50:23 +00004607 if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004608 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
4609 if (GVSrc->isConstant()) {
4610 Module *M = CI.getParent()->getParent()->getParent();
Chris Lattner82c2e432008-11-21 16:42:48 +00004611 Intrinsic::ID MemCpyID = Intrinsic::memcpy;
4612 const Type *Tys[1];
4613 Tys[0] = CI.getOperand(3)->getType();
4614 CI.setOperand(0,
4615 Intrinsic::getDeclaration(M, MemCpyID, Tys, 1));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004616 Changed = true;
4617 }
Eli Friedman626e32a2009-12-17 21:07:31 +00004618 }
Chris Lattner59b27d92008-05-28 05:30:41 +00004619
Eli Friedman626e32a2009-12-17 21:07:31 +00004620 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(MI)) {
Chris Lattner59b27d92008-05-28 05:30:41 +00004621 // memmove(x,x,size) -> noop.
Eli Friedman626e32a2009-12-17 21:07:31 +00004622 if (MTI->getSource() == MTI->getDest())
Chris Lattner59b27d92008-05-28 05:30:41 +00004623 return EraseInstFromFunction(CI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004624 }
4625
4626 // If we can determine a pointer alignment that is bigger than currently
4627 // set, update the alignment.
Chris Lattnera86628a2009-03-08 03:37:16 +00004628 if (isa<MemTransferInst>(MI)) {
Chris Lattner00ae5132008-01-13 23:50:23 +00004629 if (Instruction *I = SimplifyMemTransfer(MI))
4630 return I;
Chris Lattner5af8a912008-04-30 06:39:11 +00004631 } else if (MemSetInst *MSI = dyn_cast<MemSetInst>(MI)) {
4632 if (Instruction *I = SimplifyMemSet(MSI))
4633 return I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004634 }
4635
4636 if (Changed) return II;
Chris Lattner989ba312008-06-18 04:33:20 +00004637 }
4638
4639 switch (II->getIntrinsicID()) {
4640 default: break;
4641 case Intrinsic::bswap:
4642 // bswap(bswap(x)) -> x
4643 if (IntrinsicInst *Operand = dyn_cast<IntrinsicInst>(II->getOperand(1)))
4644 if (Operand->getIntrinsicID() == Intrinsic::bswap)
4645 return ReplaceInstUsesWith(CI, Operand->getOperand(1));
Chris Lattner723b9642010-01-01 18:34:40 +00004646
4647 // bswap(trunc(bswap(x))) -> trunc(lshr(x, c))
4648 if (TruncInst *TI = dyn_cast<TruncInst>(II->getOperand(1))) {
4649 if (IntrinsicInst *Operand = dyn_cast<IntrinsicInst>(TI->getOperand(0)))
4650 if (Operand->getIntrinsicID() == Intrinsic::bswap) {
4651 unsigned C = Operand->getType()->getPrimitiveSizeInBits() -
4652 TI->getType()->getPrimitiveSizeInBits();
4653 Value *CV = ConstantInt::get(Operand->getType(), C);
4654 Value *V = Builder->CreateLShr(Operand->getOperand(1), CV);
4655 return new TruncInst(V, TI->getType());
4656 }
4657 }
4658
Chris Lattner989ba312008-06-18 04:33:20 +00004659 break;
Chris Lattnerfd4f21a2010-01-01 01:52:15 +00004660 case Intrinsic::powi:
4661 if (ConstantInt *Power = dyn_cast<ConstantInt>(II->getOperand(2))) {
4662 // powi(x, 0) -> 1.0
4663 if (Power->isZero())
4664 return ReplaceInstUsesWith(CI, ConstantFP::get(CI.getType(), 1.0));
4665 // powi(x, 1) -> x
4666 if (Power->isOne())
4667 return ReplaceInstUsesWith(CI, II->getOperand(1));
4668 // powi(x, -1) -> 1/x
Chris Lattner60179fb2010-01-01 01:54:08 +00004669 if (Power->isAllOnesValue())
4670 return BinaryOperator::CreateFDiv(ConstantFP::get(CI.getType(), 1.0),
4671 II->getOperand(1));
Chris Lattnerfd4f21a2010-01-01 01:52:15 +00004672 }
4673 break;
4674
Chris Lattner0b452262009-11-26 21:42:47 +00004675 case Intrinsic::uadd_with_overflow: {
4676 Value *LHS = II->getOperand(1), *RHS = II->getOperand(2);
4677 const IntegerType *IT = cast<IntegerType>(II->getOperand(1)->getType());
4678 uint32_t BitWidth = IT->getBitWidth();
4679 APInt Mask = APInt::getSignBit(BitWidth);
Chris Lattner65e34842009-11-26 22:08:06 +00004680 APInt LHSKnownZero(BitWidth, 0);
4681 APInt LHSKnownOne(BitWidth, 0);
Chris Lattner0b452262009-11-26 21:42:47 +00004682 ComputeMaskedBits(LHS, Mask, LHSKnownZero, LHSKnownOne);
4683 bool LHSKnownNegative = LHSKnownOne[BitWidth - 1];
4684 bool LHSKnownPositive = LHSKnownZero[BitWidth - 1];
4685
4686 if (LHSKnownNegative || LHSKnownPositive) {
Chris Lattner65e34842009-11-26 22:08:06 +00004687 APInt RHSKnownZero(BitWidth, 0);
4688 APInt RHSKnownOne(BitWidth, 0);
Chris Lattner0b452262009-11-26 21:42:47 +00004689 ComputeMaskedBits(RHS, Mask, RHSKnownZero, RHSKnownOne);
4690 bool RHSKnownNegative = RHSKnownOne[BitWidth - 1];
4691 bool RHSKnownPositive = RHSKnownZero[BitWidth - 1];
4692 if (LHSKnownNegative && RHSKnownNegative) {
4693 // The sign bit is set in both cases: this MUST overflow.
4694 // Create a simple add instruction, and insert it into the struct.
4695 Instruction *Add = BinaryOperator::CreateAdd(LHS, RHS, "", &CI);
4696 Worklist.Add(Add);
Chris Lattnerdbbf1b22009-11-29 02:57:29 +00004697 Constant *V[] = {
Chris Lattner03a27b42010-01-04 07:02:48 +00004698 UndefValue::get(LHS->getType()),ConstantInt::getTrue(II->getContext())
Chris Lattnerdbbf1b22009-11-29 02:57:29 +00004699 };
Chris Lattner03a27b42010-01-04 07:02:48 +00004700 Constant *Struct = ConstantStruct::get(II->getContext(), V, 2, false);
Chris Lattner0b452262009-11-26 21:42:47 +00004701 return InsertValueInst::Create(Struct, Add, 0);
4702 }
4703
4704 if (LHSKnownPositive && RHSKnownPositive) {
4705 // The sign bit is clear in both cases: this CANNOT overflow.
4706 // Create a simple add instruction, and insert it into the struct.
4707 Instruction *Add = BinaryOperator::CreateNUWAdd(LHS, RHS, "", &CI);
4708 Worklist.Add(Add);
Chris Lattnerdbbf1b22009-11-29 02:57:29 +00004709 Constant *V[] = {
Chris Lattner03a27b42010-01-04 07:02:48 +00004710 UndefValue::get(LHS->getType()),
4711 ConstantInt::getFalse(II->getContext())
Chris Lattnerdbbf1b22009-11-29 02:57:29 +00004712 };
Chris Lattner03a27b42010-01-04 07:02:48 +00004713 Constant *Struct = ConstantStruct::get(II->getContext(), V, 2, false);
Chris Lattner0b452262009-11-26 21:42:47 +00004714 return InsertValueInst::Create(Struct, Add, 0);
4715 }
4716 }
4717 }
4718 // FALL THROUGH uadd into sadd
4719 case Intrinsic::sadd_with_overflow:
4720 // Canonicalize constants into the RHS.
4721 if (isa<Constant>(II->getOperand(1)) &&
4722 !isa<Constant>(II->getOperand(2))) {
4723 Value *LHS = II->getOperand(1);
4724 II->setOperand(1, II->getOperand(2));
4725 II->setOperand(2, LHS);
4726 return II;
4727 }
4728
4729 // X + undef -> undef
4730 if (isa<UndefValue>(II->getOperand(2)))
4731 return ReplaceInstUsesWith(CI, UndefValue::get(II->getType()));
4732
4733 if (ConstantInt *RHS = dyn_cast<ConstantInt>(II->getOperand(2))) {
4734 // X + 0 -> {X, false}
4735 if (RHS->isZero()) {
4736 Constant *V[] = {
Chris Lattnerdbbf1b22009-11-29 02:57:29 +00004737 UndefValue::get(II->getOperand(0)->getType()),
Chris Lattner03a27b42010-01-04 07:02:48 +00004738 ConstantInt::getFalse(II->getContext())
Chris Lattner0b452262009-11-26 21:42:47 +00004739 };
Chris Lattner03a27b42010-01-04 07:02:48 +00004740 Constant *Struct = ConstantStruct::get(II->getContext(), V, 2, false);
Chris Lattner0b452262009-11-26 21:42:47 +00004741 return InsertValueInst::Create(Struct, II->getOperand(1), 0);
4742 }
4743 }
4744 break;
4745 case Intrinsic::usub_with_overflow:
4746 case Intrinsic::ssub_with_overflow:
4747 // undef - X -> undef
4748 // X - undef -> undef
4749 if (isa<UndefValue>(II->getOperand(1)) ||
4750 isa<UndefValue>(II->getOperand(2)))
4751 return ReplaceInstUsesWith(CI, UndefValue::get(II->getType()));
4752
4753 if (ConstantInt *RHS = dyn_cast<ConstantInt>(II->getOperand(2))) {
4754 // X - 0 -> {X, false}
4755 if (RHS->isZero()) {
4756 Constant *V[] = {
Chris Lattnerdbbf1b22009-11-29 02:57:29 +00004757 UndefValue::get(II->getOperand(1)->getType()),
Chris Lattner03a27b42010-01-04 07:02:48 +00004758 ConstantInt::getFalse(II->getContext())
Chris Lattner0b452262009-11-26 21:42:47 +00004759 };
Chris Lattner03a27b42010-01-04 07:02:48 +00004760 Constant *Struct = ConstantStruct::get(II->getContext(), V, 2, false);
Chris Lattner0b452262009-11-26 21:42:47 +00004761 return InsertValueInst::Create(Struct, II->getOperand(1), 0);
4762 }
4763 }
4764 break;
4765 case Intrinsic::umul_with_overflow:
4766 case Intrinsic::smul_with_overflow:
4767 // Canonicalize constants into the RHS.
4768 if (isa<Constant>(II->getOperand(1)) &&
4769 !isa<Constant>(II->getOperand(2))) {
4770 Value *LHS = II->getOperand(1);
4771 II->setOperand(1, II->getOperand(2));
4772 II->setOperand(2, LHS);
4773 return II;
4774 }
4775
4776 // X * undef -> undef
4777 if (isa<UndefValue>(II->getOperand(2)))
4778 return ReplaceInstUsesWith(CI, UndefValue::get(II->getType()));
4779
4780 if (ConstantInt *RHSI = dyn_cast<ConstantInt>(II->getOperand(2))) {
4781 // X*0 -> {0, false}
4782 if (RHSI->isZero())
4783 return ReplaceInstUsesWith(CI, Constant::getNullValue(II->getType()));
4784
4785 // X * 1 -> {X, false}
4786 if (RHSI->equalsInt(1)) {
Chris Lattnerdbbf1b22009-11-29 02:57:29 +00004787 Constant *V[] = {
4788 UndefValue::get(II->getOperand(1)->getType()),
Chris Lattner03a27b42010-01-04 07:02:48 +00004789 ConstantInt::getFalse(II->getContext())
Chris Lattnerdbbf1b22009-11-29 02:57:29 +00004790 };
Chris Lattner03a27b42010-01-04 07:02:48 +00004791 Constant *Struct = ConstantStruct::get(II->getContext(), V, 2, false);
Chris Lattnerdbbf1b22009-11-29 02:57:29 +00004792 return InsertValueInst::Create(Struct, II->getOperand(1), 0);
Chris Lattner0b452262009-11-26 21:42:47 +00004793 }
4794 }
4795 break;
Chris Lattner989ba312008-06-18 04:33:20 +00004796 case Intrinsic::ppc_altivec_lvx:
4797 case Intrinsic::ppc_altivec_lvxl:
4798 case Intrinsic::x86_sse_loadu_ps:
4799 case Intrinsic::x86_sse2_loadu_pd:
4800 case Intrinsic::x86_sse2_loadu_dq:
4801 // Turn PPC lvx -> load if the pointer is known aligned.
4802 // Turn X86 loadups -> load if the pointer is known aligned.
4803 if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
Chris Lattner78628292009-08-30 19:47:22 +00004804 Value *Ptr = Builder->CreateBitCast(II->getOperand(1),
4805 PointerType::getUnqual(II->getType()));
Chris Lattner989ba312008-06-18 04:33:20 +00004806 return new LoadInst(Ptr);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004807 }
Chris Lattner989ba312008-06-18 04:33:20 +00004808 break;
4809 case Intrinsic::ppc_altivec_stvx:
4810 case Intrinsic::ppc_altivec_stvxl:
4811 // Turn stvx -> store if the pointer is known aligned.
4812 if (GetOrEnforceKnownAlignment(II->getOperand(2), 16) >= 16) {
4813 const Type *OpPtrTy =
Owen Anderson6b6e2d92009-07-29 22:17:13 +00004814 PointerType::getUnqual(II->getOperand(1)->getType());
Chris Lattner78628292009-08-30 19:47:22 +00004815 Value *Ptr = Builder->CreateBitCast(II->getOperand(2), OpPtrTy);
Chris Lattner989ba312008-06-18 04:33:20 +00004816 return new StoreInst(II->getOperand(1), Ptr);
4817 }
4818 break;
4819 case Intrinsic::x86_sse_storeu_ps:
4820 case Intrinsic::x86_sse2_storeu_pd:
4821 case Intrinsic::x86_sse2_storeu_dq:
Chris Lattner989ba312008-06-18 04:33:20 +00004822 // Turn X86 storeu -> store if the pointer is known aligned.
4823 if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
4824 const Type *OpPtrTy =
Owen Anderson6b6e2d92009-07-29 22:17:13 +00004825 PointerType::getUnqual(II->getOperand(2)->getType());
Chris Lattner78628292009-08-30 19:47:22 +00004826 Value *Ptr = Builder->CreateBitCast(II->getOperand(1), OpPtrTy);
Chris Lattner989ba312008-06-18 04:33:20 +00004827 return new StoreInst(II->getOperand(2), Ptr);
4828 }
4829 break;
4830
4831 case Intrinsic::x86_sse_cvttss2si: {
4832 // These intrinsics only demands the 0th element of its input vector. If
4833 // we can simplify the input based on that, do so now.
Evan Cheng63295ab2009-02-03 10:05:09 +00004834 unsigned VWidth =
4835 cast<VectorType>(II->getOperand(1)->getType())->getNumElements();
4836 APInt DemandedElts(VWidth, 1);
4837 APInt UndefElts(VWidth, 0);
4838 if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
Chris Lattner989ba312008-06-18 04:33:20 +00004839 UndefElts)) {
4840 II->setOperand(1, V);
4841 return II;
4842 }
4843 break;
4844 }
4845
4846 case Intrinsic::ppc_altivec_vperm:
4847 // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
4848 if (ConstantVector *Mask = dyn_cast<ConstantVector>(II->getOperand(3))) {
4849 assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004850
Chris Lattner989ba312008-06-18 04:33:20 +00004851 // Check that all of the elements are integer constants or undefs.
4852 bool AllEltsOk = true;
4853 for (unsigned i = 0; i != 16; ++i) {
4854 if (!isa<ConstantInt>(Mask->getOperand(i)) &&
4855 !isa<UndefValue>(Mask->getOperand(i))) {
4856 AllEltsOk = false;
4857 break;
4858 }
4859 }
4860
4861 if (AllEltsOk) {
4862 // Cast the input vectors to byte vectors.
Chris Lattner78628292009-08-30 19:47:22 +00004863 Value *Op0 = Builder->CreateBitCast(II->getOperand(1), Mask->getType());
4864 Value *Op1 = Builder->CreateBitCast(II->getOperand(2), Mask->getType());
Owen Andersonb99ecca2009-07-30 23:03:37 +00004865 Value *Result = UndefValue::get(Op0->getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004866
Chris Lattner989ba312008-06-18 04:33:20 +00004867 // Only extract each element once.
4868 Value *ExtractedElts[32];
4869 memset(ExtractedElts, 0, sizeof(ExtractedElts));
4870
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004871 for (unsigned i = 0; i != 16; ++i) {
Chris Lattner989ba312008-06-18 04:33:20 +00004872 if (isa<UndefValue>(Mask->getOperand(i)))
4873 continue;
4874 unsigned Idx=cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
4875 Idx &= 31; // Match the hardware behavior.
4876
4877 if (ExtractedElts[Idx] == 0) {
Chris Lattnerad7516a2009-08-30 18:50:58 +00004878 ExtractedElts[Idx] =
4879 Builder->CreateExtractElement(Idx < 16 ? Op0 : Op1,
Chris Lattner03a27b42010-01-04 07:02:48 +00004880 ConstantInt::get(Type::getInt32Ty(II->getContext()),
4881 Idx&15, false), "tmp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004882 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004883
Chris Lattner989ba312008-06-18 04:33:20 +00004884 // Insert this value into the result vector.
Chris Lattnerad7516a2009-08-30 18:50:58 +00004885 Result = Builder->CreateInsertElement(Result, ExtractedElts[Idx],
Chris Lattner03a27b42010-01-04 07:02:48 +00004886 ConstantInt::get(Type::getInt32Ty(II->getContext()),
4887 i, false), "tmp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004888 }
Chris Lattner989ba312008-06-18 04:33:20 +00004889 return CastInst::Create(Instruction::BitCast, Result, CI.getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004890 }
Chris Lattner989ba312008-06-18 04:33:20 +00004891 }
4892 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004893
Chris Lattner989ba312008-06-18 04:33:20 +00004894 case Intrinsic::stackrestore: {
4895 // If the save is right next to the restore, remove the restore. This can
4896 // happen when variable allocas are DCE'd.
4897 if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
4898 if (SS->getIntrinsicID() == Intrinsic::stacksave) {
4899 BasicBlock::iterator BI = SS;
4900 if (&*++BI == II)
4901 return EraseInstFromFunction(CI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004902 }
Chris Lattner989ba312008-06-18 04:33:20 +00004903 }
4904
4905 // Scan down this block to see if there is another stack restore in the
4906 // same block without an intervening call/alloca.
4907 BasicBlock::iterator BI = II;
4908 TerminatorInst *TI = II->getParent()->getTerminator();
4909 bool CannotRemove = false;
4910 for (++BI; &*BI != TI; ++BI) {
Victor Hernandez48c3c542009-09-18 22:35:49 +00004911 if (isa<AllocaInst>(BI) || isMalloc(BI)) {
Chris Lattner989ba312008-06-18 04:33:20 +00004912 CannotRemove = true;
4913 break;
4914 }
Chris Lattnera6b477c2008-06-25 05:59:28 +00004915 if (CallInst *BCI = dyn_cast<CallInst>(BI)) {
4916 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(BCI)) {
4917 // If there is a stackrestore below this one, remove this one.
4918 if (II->getIntrinsicID() == Intrinsic::stackrestore)
4919 return EraseInstFromFunction(CI);
4920 // Otherwise, ignore the intrinsic.
4921 } else {
4922 // If we found a non-intrinsic call, we can't remove the stack
4923 // restore.
Chris Lattner416d91c2008-02-18 06:12:38 +00004924 CannotRemove = true;
4925 break;
4926 }
Chris Lattner989ba312008-06-18 04:33:20 +00004927 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004928 }
Chris Lattner989ba312008-06-18 04:33:20 +00004929
4930 // If the stack restore is in a return/unwind block and if there are no
4931 // allocas or calls between the restore and the return, nuke the restore.
4932 if (!CannotRemove && (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)))
4933 return EraseInstFromFunction(CI);
4934 break;
4935 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004936 }
4937
4938 return visitCallSite(II);
4939}
4940
4941// InvokeInst simplification
4942//
4943Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
4944 return visitCallSite(&II);
4945}
4946
Dale Johannesen96021832008-04-25 21:16:07 +00004947/// isSafeToEliminateVarargsCast - If this cast does not affect the value
4948/// passed through the varargs area, we can eliminate the use of the cast.
Dale Johannesen35615462008-04-23 18:34:37 +00004949static bool isSafeToEliminateVarargsCast(const CallSite CS,
4950 const CastInst * const CI,
4951 const TargetData * const TD,
4952 const int ix) {
4953 if (!CI->isLosslessCast())
4954 return false;
4955
4956 // The size of ByVal arguments is derived from the type, so we
4957 // can't change to a type with a different size. If the size were
4958 // passed explicitly we could avoid this check.
Devang Pateld222f862008-09-25 21:00:45 +00004959 if (!CS.paramHasAttr(ix, Attribute::ByVal))
Dale Johannesen35615462008-04-23 18:34:37 +00004960 return true;
4961
4962 const Type* SrcTy =
4963 cast<PointerType>(CI->getOperand(0)->getType())->getElementType();
4964 const Type* DstTy = cast<PointerType>(CI->getType())->getElementType();
4965 if (!SrcTy->isSized() || !DstTy->isSized())
4966 return false;
Dan Gohmana80e2712009-07-21 23:21:54 +00004967 if (!TD || TD->getTypeAllocSize(SrcTy) != TD->getTypeAllocSize(DstTy))
Dale Johannesen35615462008-04-23 18:34:37 +00004968 return false;
4969 return true;
4970}
4971
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004972// visitCallSite - Improvements for call and invoke instructions.
4973//
4974Instruction *InstCombiner::visitCallSite(CallSite CS) {
4975 bool Changed = false;
4976
4977 // If the callee is a constexpr cast of a function, attempt to move the cast
4978 // to the arguments of the call/invoke.
4979 if (transformConstExprCastCall(CS)) return 0;
4980
4981 Value *Callee = CS.getCalledValue();
4982
4983 if (Function *CalleeF = dyn_cast<Function>(Callee))
4984 if (CalleeF->getCallingConv() != CS.getCallingConv()) {
4985 Instruction *OldCall = CS.getInstruction();
4986 // If the call and callee calling conventions don't match, this call must
4987 // be unreachable, as the call is undefined.
Chris Lattner03a27b42010-01-04 07:02:48 +00004988 new StoreInst(ConstantInt::getTrue(Callee->getContext()),
4989 UndefValue::get(Type::getInt1PtrTy(Callee->getContext())),
Owen Anderson24be4c12009-07-03 00:17:18 +00004990 OldCall);
Devang Patele3829c82009-10-13 22:56:32 +00004991 // If OldCall dues not return void then replaceAllUsesWith undef.
4992 // This allows ValueHandlers and custom metadata to adjust itself.
Devang Patele9d08b82009-10-14 17:29:00 +00004993 if (!OldCall->getType()->isVoidTy())
Devang Patele3829c82009-10-13 22:56:32 +00004994 OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004995 if (isa<CallInst>(OldCall)) // Not worth removing an invoke here.
4996 return EraseInstFromFunction(*OldCall);
4997 return 0;
4998 }
4999
5000 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
5001 // This instruction is not reachable, just remove it. We insert a store to
5002 // undef so that we know that this code is not reachable, despite the fact
5003 // that we can't modify the CFG here.
Chris Lattner03a27b42010-01-04 07:02:48 +00005004 new StoreInst(ConstantInt::getTrue(Callee->getContext()),
5005 UndefValue::get(Type::getInt1PtrTy(Callee->getContext())),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005006 CS.getInstruction());
5007
Devang Patele3829c82009-10-13 22:56:32 +00005008 // If CS dues not return void then replaceAllUsesWith undef.
5009 // This allows ValueHandlers and custom metadata to adjust itself.
Devang Patele9d08b82009-10-14 17:29:00 +00005010 if (!CS.getInstruction()->getType()->isVoidTy())
Devang Patele3829c82009-10-13 22:56:32 +00005011 CS.getInstruction()->
5012 replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005013
5014 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
5015 // Don't break the CFG, insert a dummy cond branch.
Gabor Greifd6da1d02008-04-06 20:25:17 +00005016 BranchInst::Create(II->getNormalDest(), II->getUnwindDest(),
Chris Lattner03a27b42010-01-04 07:02:48 +00005017 ConstantInt::getTrue(Callee->getContext()), II);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005018 }
5019 return EraseInstFromFunction(*CS.getInstruction());
5020 }
5021
Duncan Sands74833f22007-09-17 10:26:40 +00005022 if (BitCastInst *BC = dyn_cast<BitCastInst>(Callee))
5023 if (IntrinsicInst *In = dyn_cast<IntrinsicInst>(BC->getOperand(0)))
5024 if (In->getIntrinsicID() == Intrinsic::init_trampoline)
5025 return transformCallThroughTrampoline(CS);
5026
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005027 const PointerType *PTy = cast<PointerType>(Callee->getType());
5028 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
5029 if (FTy->isVarArg()) {
Dale Johannesen502336c2008-04-23 01:03:05 +00005030 int ix = FTy->getNumParams() + (isa<InvokeInst>(Callee) ? 3 : 1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005031 // See if we can optimize any arguments passed through the varargs area of
5032 // the call.
5033 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
Dale Johannesen35615462008-04-23 18:34:37 +00005034 E = CS.arg_end(); I != E; ++I, ++ix) {
5035 CastInst *CI = dyn_cast<CastInst>(*I);
5036 if (CI && isSafeToEliminateVarargsCast(CS, CI, TD, ix)) {
5037 *I = CI->getOperand(0);
5038 Changed = true;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005039 }
Dale Johannesen35615462008-04-23 18:34:37 +00005040 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005041 }
5042
Duncan Sands2937e352007-12-19 21:13:37 +00005043 if (isa<InlineAsm>(Callee) && !CS.doesNotThrow()) {
Duncan Sands7868f3c2007-12-16 15:51:49 +00005044 // Inline asm calls cannot throw - mark them 'nounwind'.
Duncan Sands2937e352007-12-19 21:13:37 +00005045 CS.setDoesNotThrow();
Duncan Sands7868f3c2007-12-16 15:51:49 +00005046 Changed = true;
5047 }
5048
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005049 return Changed ? CS.getInstruction() : 0;
5050}
5051
5052// transformConstExprCastCall - If the callee is a constexpr cast of a function,
5053// attempt to move the cast to the arguments of the call/invoke.
5054//
5055bool InstCombiner::transformConstExprCastCall(CallSite CS) {
5056 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
5057 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
5058 if (CE->getOpcode() != Instruction::BitCast ||
5059 !isa<Function>(CE->getOperand(0)))
5060 return false;
5061 Function *Callee = cast<Function>(CE->getOperand(0));
5062 Instruction *Caller = CS.getInstruction();
Devang Pateld222f862008-09-25 21:00:45 +00005063 const AttrListPtr &CallerPAL = CS.getAttributes();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005064
5065 // Okay, this is a cast from a function to a different type. Unless doing so
5066 // would cause a type conversion of one of our arguments, change this call to
5067 // be a direct call with arguments casted to the appropriate types.
5068 //
5069 const FunctionType *FT = Callee->getFunctionType();
5070 const Type *OldRetTy = Caller->getType();
Duncan Sands7901ce12008-06-01 07:38:42 +00005071 const Type *NewRetTy = FT->getReturnType();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005072
Duncan Sands7901ce12008-06-01 07:38:42 +00005073 if (isa<StructType>(NewRetTy))
Devang Pateld091d322008-03-11 18:04:06 +00005074 return false; // TODO: Handle multiple return values.
5075
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005076 // Check to see if we are changing the return type...
Duncan Sands7901ce12008-06-01 07:38:42 +00005077 if (OldRetTy != NewRetTy) {
Bill Wendlingd9644a42008-05-14 22:45:20 +00005078 if (Callee->isDeclaration() &&
Duncan Sands7901ce12008-06-01 07:38:42 +00005079 // Conversion is ok if changing from one pointer type to another or from
5080 // a pointer to an integer of the same size.
Dan Gohmana80e2712009-07-21 23:21:54 +00005081 !((isa<PointerType>(OldRetTy) || !TD ||
Owen Anderson35b47072009-08-13 21:58:54 +00005082 OldRetTy == TD->getIntPtrType(Caller->getContext())) &&
Dan Gohmana80e2712009-07-21 23:21:54 +00005083 (isa<PointerType>(NewRetTy) || !TD ||
Owen Anderson35b47072009-08-13 21:58:54 +00005084 NewRetTy == TD->getIntPtrType(Caller->getContext()))))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005085 return false; // Cannot transform this return value.
5086
Duncan Sands5c489582008-01-06 10:12:28 +00005087 if (!Caller->use_empty() &&
Duncan Sands5c489582008-01-06 10:12:28 +00005088 // void -> non-void is handled specially
Devang Patele9d08b82009-10-14 17:29:00 +00005089 !NewRetTy->isVoidTy() && !CastInst::isCastable(NewRetTy, OldRetTy))
Duncan Sands5c489582008-01-06 10:12:28 +00005090 return false; // Cannot transform this return value.
5091
Chris Lattner1c8733e2008-03-12 17:45:29 +00005092 if (!CallerPAL.isEmpty() && !Caller->use_empty()) {
Devang Patelf2a4a922008-09-26 22:53:05 +00005093 Attributes RAttrs = CallerPAL.getRetAttributes();
Devang Pateld222f862008-09-25 21:00:45 +00005094 if (RAttrs & Attribute::typeIncompatible(NewRetTy))
Duncan Sandsdbe97dc2008-01-07 17:16:06 +00005095 return false; // Attribute not compatible with transformed value.
5096 }
Duncan Sandsc849e662008-01-06 18:27:01 +00005097
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005098 // If the callsite is an invoke instruction, and the return value is used by
5099 // a PHI node in a successor, we cannot change the return type of the call
5100 // because there is no place to put the cast instruction (without breaking
5101 // the critical edge). Bail out in this case.
5102 if (!Caller->use_empty())
5103 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
5104 for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
5105 UI != E; ++UI)
5106 if (PHINode *PN = dyn_cast<PHINode>(*UI))
5107 if (PN->getParent() == II->getNormalDest() ||
5108 PN->getParent() == II->getUnwindDest())
5109 return false;
5110 }
5111
5112 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
5113 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
5114
5115 CallSite::arg_iterator AI = CS.arg_begin();
5116 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
5117 const Type *ParamTy = FT->getParamType(i);
5118 const Type *ActTy = (*AI)->getType();
Duncan Sands5c489582008-01-06 10:12:28 +00005119
5120 if (!CastInst::isCastable(ActTy, ParamTy))
Duncan Sandsc849e662008-01-06 18:27:01 +00005121 return false; // Cannot transform this parameter value.
5122
Devang Patelf2a4a922008-09-26 22:53:05 +00005123 if (CallerPAL.getParamAttributes(i + 1)
5124 & Attribute::typeIncompatible(ParamTy))
Chris Lattner1c8733e2008-03-12 17:45:29 +00005125 return false; // Attribute not compatible with transformed value.
Duncan Sands5c489582008-01-06 10:12:28 +00005126
Duncan Sands7901ce12008-06-01 07:38:42 +00005127 // Converting from one pointer type to another or between a pointer and an
5128 // integer of the same size is safe even if we do not have a body.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005129 bool isConvertible = ActTy == ParamTy ||
Owen Anderson35b47072009-08-13 21:58:54 +00005130 (TD && ((isa<PointerType>(ParamTy) ||
5131 ParamTy == TD->getIntPtrType(Caller->getContext())) &&
5132 (isa<PointerType>(ActTy) ||
5133 ActTy == TD->getIntPtrType(Caller->getContext()))));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005134 if (Callee->isDeclaration() && !isConvertible) return false;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005135 }
5136
5137 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
5138 Callee->isDeclaration())
Chris Lattner1c8733e2008-03-12 17:45:29 +00005139 return false; // Do not delete arguments unless we have a function body.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005140
Chris Lattner1c8733e2008-03-12 17:45:29 +00005141 if (FT->getNumParams() < NumActualArgs && FT->isVarArg() &&
5142 !CallerPAL.isEmpty())
Duncan Sandsc849e662008-01-06 18:27:01 +00005143 // In this case we have more arguments than the new function type, but we
Duncan Sands4ced1f82008-01-13 08:02:44 +00005144 // won't be dropping them. Check that these extra arguments have attributes
5145 // that are compatible with being a vararg call argument.
Chris Lattner1c8733e2008-03-12 17:45:29 +00005146 for (unsigned i = CallerPAL.getNumSlots(); i; --i) {
5147 if (CallerPAL.getSlot(i - 1).Index <= FT->getNumParams())
Duncan Sands4ced1f82008-01-13 08:02:44 +00005148 break;
Devang Patele480dfa2008-09-23 23:03:40 +00005149 Attributes PAttrs = CallerPAL.getSlot(i - 1).Attrs;
Devang Pateld222f862008-09-25 21:00:45 +00005150 if (PAttrs & Attribute::VarArgsIncompatible)
Duncan Sands4ced1f82008-01-13 08:02:44 +00005151 return false;
5152 }
Duncan Sandsc849e662008-01-06 18:27:01 +00005153
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005154 // Okay, we decided that this is a safe thing to do: go ahead and start
5155 // inserting cast instructions as necessary...
5156 std::vector<Value*> Args;
5157 Args.reserve(NumActualArgs);
Devang Pateld222f862008-09-25 21:00:45 +00005158 SmallVector<AttributeWithIndex, 8> attrVec;
Duncan Sandsc849e662008-01-06 18:27:01 +00005159 attrVec.reserve(NumCommonArgs);
5160
5161 // Get any return attributes.
Devang Patelf2a4a922008-09-26 22:53:05 +00005162 Attributes RAttrs = CallerPAL.getRetAttributes();
Duncan Sandsc849e662008-01-06 18:27:01 +00005163
5164 // If the return value is not being used, the type may not be compatible
5165 // with the existing attributes. Wipe out any problematic attributes.
Devang Pateld222f862008-09-25 21:00:45 +00005166 RAttrs &= ~Attribute::typeIncompatible(NewRetTy);
Duncan Sandsc849e662008-01-06 18:27:01 +00005167
5168 // Add the new return attributes.
5169 if (RAttrs)
Devang Pateld222f862008-09-25 21:00:45 +00005170 attrVec.push_back(AttributeWithIndex::get(0, RAttrs));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005171
5172 AI = CS.arg_begin();
5173 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
5174 const Type *ParamTy = FT->getParamType(i);
5175 if ((*AI)->getType() == ParamTy) {
5176 Args.push_back(*AI);
5177 } else {
5178 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
5179 false, ParamTy, false);
Chris Lattnerad7516a2009-08-30 18:50:58 +00005180 Args.push_back(Builder->CreateCast(opcode, *AI, ParamTy, "tmp"));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005181 }
Duncan Sandsc849e662008-01-06 18:27:01 +00005182
5183 // Add any parameter attributes.
Devang Patelf2a4a922008-09-26 22:53:05 +00005184 if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
Devang Pateld222f862008-09-25 21:00:45 +00005185 attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005186 }
5187
5188 // If the function takes more arguments than the call was taking, add them
Chris Lattnerad7516a2009-08-30 18:50:58 +00005189 // now.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005190 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
Owen Andersonaac28372009-07-31 20:28:14 +00005191 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005192
Chris Lattnerad7516a2009-08-30 18:50:58 +00005193 // If we are removing arguments to the function, emit an obnoxious warning.
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00005194 if (FT->getNumParams() < NumActualArgs) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005195 if (!FT->isVarArg()) {
Daniel Dunbar005975c2009-07-25 00:23:56 +00005196 errs() << "WARNING: While resolving call to function '"
5197 << Callee->getName() << "' arguments were dropped!\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005198 } else {
Chris Lattnerad7516a2009-08-30 18:50:58 +00005199 // Add all of the arguments in their promoted form to the arg list.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005200 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
5201 const Type *PTy = getPromotedType((*AI)->getType());
5202 if (PTy != (*AI)->getType()) {
5203 // Must promote to pass through va_arg area!
Chris Lattnerad7516a2009-08-30 18:50:58 +00005204 Instruction::CastOps opcode =
5205 CastInst::getCastOpcode(*AI, false, PTy, false);
5206 Args.push_back(Builder->CreateCast(opcode, *AI, PTy, "tmp"));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005207 } else {
5208 Args.push_back(*AI);
5209 }
Duncan Sandsc849e662008-01-06 18:27:01 +00005210
Duncan Sands4ced1f82008-01-13 08:02:44 +00005211 // Add any parameter attributes.
Devang Patelf2a4a922008-09-26 22:53:05 +00005212 if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
Devang Pateld222f862008-09-25 21:00:45 +00005213 attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
Duncan Sands4ced1f82008-01-13 08:02:44 +00005214 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005215 }
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00005216 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005217
Devang Patelf2a4a922008-09-26 22:53:05 +00005218 if (Attributes FnAttrs = CallerPAL.getFnAttributes())
5219 attrVec.push_back(AttributeWithIndex::get(~0, FnAttrs));
5220
Devang Patele9d08b82009-10-14 17:29:00 +00005221 if (NewRetTy->isVoidTy())
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005222 Caller->setName(""); // Void type should not have a name.
5223
Eric Christopher3e7381f2009-07-25 02:45:27 +00005224 const AttrListPtr &NewCallerPAL = AttrListPtr::get(attrVec.begin(),
5225 attrVec.end());
Duncan Sandsc849e662008-01-06 18:27:01 +00005226
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005227 Instruction *NC;
5228 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Gabor Greifd6da1d02008-04-06 20:25:17 +00005229 NC = InvokeInst::Create(Callee, II->getNormalDest(), II->getUnwindDest(),
Gabor Greifb91ea9d2008-05-15 10:04:30 +00005230 Args.begin(), Args.end(),
5231 Caller->getName(), Caller);
Reid Spencer6b0b09a2007-07-30 19:53:57 +00005232 cast<InvokeInst>(NC)->setCallingConv(II->getCallingConv());
Devang Pateld222f862008-09-25 21:00:45 +00005233 cast<InvokeInst>(NC)->setAttributes(NewCallerPAL);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005234 } else {
Gabor Greifd6da1d02008-04-06 20:25:17 +00005235 NC = CallInst::Create(Callee, Args.begin(), Args.end(),
5236 Caller->getName(), Caller);
Duncan Sandsf5588dc2007-11-27 13:23:08 +00005237 CallInst *CI = cast<CallInst>(Caller);
5238 if (CI->isTailCall())
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005239 cast<CallInst>(NC)->setTailCall();
Duncan Sandsf5588dc2007-11-27 13:23:08 +00005240 cast<CallInst>(NC)->setCallingConv(CI->getCallingConv());
Devang Pateld222f862008-09-25 21:00:45 +00005241 cast<CallInst>(NC)->setAttributes(NewCallerPAL);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005242 }
5243
5244 // Insert a cast of the return type as necessary.
5245 Value *NV = NC;
Duncan Sands5c489582008-01-06 10:12:28 +00005246 if (OldRetTy != NV->getType() && !Caller->use_empty()) {
Devang Patele9d08b82009-10-14 17:29:00 +00005247 if (!NV->getType()->isVoidTy()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005248 Instruction::CastOps opcode = CastInst::getCastOpcode(NC, false,
Duncan Sands5c489582008-01-06 10:12:28 +00005249 OldRetTy, false);
Gabor Greifa645dd32008-05-16 19:29:10 +00005250 NV = NC = CastInst::Create(opcode, NC, OldRetTy, "tmp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005251
5252 // If this is an invoke instruction, we should insert it after the first
5253 // non-phi, instruction in the normal successor block.
5254 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Dan Gohman514277c2008-05-23 21:05:58 +00005255 BasicBlock::iterator I = II->getNormalDest()->getFirstNonPHI();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005256 InsertNewInstBefore(NC, *I);
5257 } else {
5258 // Otherwise, it's a call, just insert cast right after the call instr
5259 InsertNewInstBefore(NC, *Caller);
5260 }
Chris Lattner4796b622009-08-30 06:22:51 +00005261 Worklist.AddUsersToWorkList(*Caller);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005262 } else {
Owen Andersonb99ecca2009-07-30 23:03:37 +00005263 NV = UndefValue::get(Caller->getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005264 }
5265 }
5266
Devang Pateledad36f2009-10-13 21:41:20 +00005267
Chris Lattner26b7f942009-08-31 05:17:58 +00005268 if (!Caller->use_empty())
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005269 Caller->replaceAllUsesWith(NV);
Chris Lattner26b7f942009-08-31 05:17:58 +00005270
5271 EraseInstFromFunction(*Caller);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005272 return true;
5273}
5274
Duncan Sands74833f22007-09-17 10:26:40 +00005275// transformCallThroughTrampoline - Turn a call to a function created by the
5276// init_trampoline intrinsic into a direct call to the underlying function.
5277//
5278Instruction *InstCombiner::transformCallThroughTrampoline(CallSite CS) {
5279 Value *Callee = CS.getCalledValue();
5280 const PointerType *PTy = cast<PointerType>(Callee->getType());
5281 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
Devang Pateld222f862008-09-25 21:00:45 +00005282 const AttrListPtr &Attrs = CS.getAttributes();
Duncan Sands48b81112008-01-14 19:52:09 +00005283
5284 // If the call already has the 'nest' attribute somewhere then give up -
5285 // otherwise 'nest' would occur twice after splicing in the chain.
Devang Pateld222f862008-09-25 21:00:45 +00005286 if (Attrs.hasAttrSomewhere(Attribute::Nest))
Duncan Sands48b81112008-01-14 19:52:09 +00005287 return 0;
Duncan Sands74833f22007-09-17 10:26:40 +00005288
5289 IntrinsicInst *Tramp =
5290 cast<IntrinsicInst>(cast<BitCastInst>(Callee)->getOperand(0));
5291
Anton Korobeynikov48fc88f2008-05-07 22:54:15 +00005292 Function *NestF = cast<Function>(Tramp->getOperand(2)->stripPointerCasts());
Duncan Sands74833f22007-09-17 10:26:40 +00005293 const PointerType *NestFPTy = cast<PointerType>(NestF->getType());
5294 const FunctionType *NestFTy = cast<FunctionType>(NestFPTy->getElementType());
5295
Devang Pateld222f862008-09-25 21:00:45 +00005296 const AttrListPtr &NestAttrs = NestF->getAttributes();
Chris Lattner1c8733e2008-03-12 17:45:29 +00005297 if (!NestAttrs.isEmpty()) {
Duncan Sands74833f22007-09-17 10:26:40 +00005298 unsigned NestIdx = 1;
5299 const Type *NestTy = 0;
Devang Pateld222f862008-09-25 21:00:45 +00005300 Attributes NestAttr = Attribute::None;
Duncan Sands74833f22007-09-17 10:26:40 +00005301
5302 // Look for a parameter marked with the 'nest' attribute.
5303 for (FunctionType::param_iterator I = NestFTy->param_begin(),
5304 E = NestFTy->param_end(); I != E; ++NestIdx, ++I)
Devang Pateld222f862008-09-25 21:00:45 +00005305 if (NestAttrs.paramHasAttr(NestIdx, Attribute::Nest)) {
Duncan Sands74833f22007-09-17 10:26:40 +00005306 // Record the parameter type and any other attributes.
5307 NestTy = *I;
Devang Patelf2a4a922008-09-26 22:53:05 +00005308 NestAttr = NestAttrs.getParamAttributes(NestIdx);
Duncan Sands74833f22007-09-17 10:26:40 +00005309 break;
5310 }
5311
5312 if (NestTy) {
5313 Instruction *Caller = CS.getInstruction();
5314 std::vector<Value*> NewArgs;
5315 NewArgs.reserve(unsigned(CS.arg_end()-CS.arg_begin())+1);
5316
Devang Pateld222f862008-09-25 21:00:45 +00005317 SmallVector<AttributeWithIndex, 8> NewAttrs;
Chris Lattner1c8733e2008-03-12 17:45:29 +00005318 NewAttrs.reserve(Attrs.getNumSlots() + 1);
Duncan Sands48b81112008-01-14 19:52:09 +00005319
Duncan Sands74833f22007-09-17 10:26:40 +00005320 // Insert the nest argument into the call argument list, which may
Duncan Sands48b81112008-01-14 19:52:09 +00005321 // mean appending it. Likewise for attributes.
5322
Devang Patelf2a4a922008-09-26 22:53:05 +00005323 // Add any result attributes.
5324 if (Attributes Attr = Attrs.getRetAttributes())
Devang Pateld222f862008-09-25 21:00:45 +00005325 NewAttrs.push_back(AttributeWithIndex::get(0, Attr));
Duncan Sands48b81112008-01-14 19:52:09 +00005326
Duncan Sands74833f22007-09-17 10:26:40 +00005327 {
5328 unsigned Idx = 1;
5329 CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
5330 do {
5331 if (Idx == NestIdx) {
Duncan Sands48b81112008-01-14 19:52:09 +00005332 // Add the chain argument and attributes.
Duncan Sands74833f22007-09-17 10:26:40 +00005333 Value *NestVal = Tramp->getOperand(3);
5334 if (NestVal->getType() != NestTy)
5335 NestVal = new BitCastInst(NestVal, NestTy, "nest", Caller);
5336 NewArgs.push_back(NestVal);
Devang Pateld222f862008-09-25 21:00:45 +00005337 NewAttrs.push_back(AttributeWithIndex::get(NestIdx, NestAttr));
Duncan Sands74833f22007-09-17 10:26:40 +00005338 }
5339
5340 if (I == E)
5341 break;
5342
Duncan Sands48b81112008-01-14 19:52:09 +00005343 // Add the original argument and attributes.
Duncan Sands74833f22007-09-17 10:26:40 +00005344 NewArgs.push_back(*I);
Devang Patelf2a4a922008-09-26 22:53:05 +00005345 if (Attributes Attr = Attrs.getParamAttributes(Idx))
Duncan Sands48b81112008-01-14 19:52:09 +00005346 NewAttrs.push_back
Devang Pateld222f862008-09-25 21:00:45 +00005347 (AttributeWithIndex::get(Idx + (Idx >= NestIdx), Attr));
Duncan Sands74833f22007-09-17 10:26:40 +00005348
5349 ++Idx, ++I;
5350 } while (1);
5351 }
5352
Devang Patelf2a4a922008-09-26 22:53:05 +00005353 // Add any function attributes.
5354 if (Attributes Attr = Attrs.getFnAttributes())
5355 NewAttrs.push_back(AttributeWithIndex::get(~0, Attr));
5356
Duncan Sands74833f22007-09-17 10:26:40 +00005357 // The trampoline may have been bitcast to a bogus type (FTy).
5358 // Handle this by synthesizing a new function type, equal to FTy
Duncan Sands48b81112008-01-14 19:52:09 +00005359 // with the chain parameter inserted.
Duncan Sands74833f22007-09-17 10:26:40 +00005360
Duncan Sands74833f22007-09-17 10:26:40 +00005361 std::vector<const Type*> NewTypes;
Duncan Sands74833f22007-09-17 10:26:40 +00005362 NewTypes.reserve(FTy->getNumParams()+1);
5363
Duncan Sands74833f22007-09-17 10:26:40 +00005364 // Insert the chain's type into the list of parameter types, which may
Duncan Sands48b81112008-01-14 19:52:09 +00005365 // mean appending it.
Duncan Sands74833f22007-09-17 10:26:40 +00005366 {
5367 unsigned Idx = 1;
5368 FunctionType::param_iterator I = FTy->param_begin(),
5369 E = FTy->param_end();
5370
5371 do {
Duncan Sands48b81112008-01-14 19:52:09 +00005372 if (Idx == NestIdx)
5373 // Add the chain's type.
Duncan Sands74833f22007-09-17 10:26:40 +00005374 NewTypes.push_back(NestTy);
Duncan Sands74833f22007-09-17 10:26:40 +00005375
5376 if (I == E)
5377 break;
5378
Duncan Sands48b81112008-01-14 19:52:09 +00005379 // Add the original type.
Duncan Sands74833f22007-09-17 10:26:40 +00005380 NewTypes.push_back(*I);
Duncan Sands74833f22007-09-17 10:26:40 +00005381
5382 ++Idx, ++I;
5383 } while (1);
5384 }
5385
5386 // Replace the trampoline call with a direct call. Let the generic
5387 // code sort out any function type mismatches.
Owen Anderson6b6e2d92009-07-29 22:17:13 +00005388 FunctionType *NewFTy = FunctionType::get(FTy->getReturnType(), NewTypes,
Owen Anderson24be4c12009-07-03 00:17:18 +00005389 FTy->isVarArg());
5390 Constant *NewCallee =
Owen Anderson6b6e2d92009-07-29 22:17:13 +00005391 NestF->getType() == PointerType::getUnqual(NewFTy) ?
Owen Anderson02b48c32009-07-29 18:55:55 +00005392 NestF : ConstantExpr::getBitCast(NestF,
Owen Anderson6b6e2d92009-07-29 22:17:13 +00005393 PointerType::getUnqual(NewFTy));
Eric Christopher3e7381f2009-07-25 02:45:27 +00005394 const AttrListPtr &NewPAL = AttrListPtr::get(NewAttrs.begin(),
5395 NewAttrs.end());
Duncan Sands74833f22007-09-17 10:26:40 +00005396
5397 Instruction *NewCaller;
5398 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Gabor Greifd6da1d02008-04-06 20:25:17 +00005399 NewCaller = InvokeInst::Create(NewCallee,
5400 II->getNormalDest(), II->getUnwindDest(),
5401 NewArgs.begin(), NewArgs.end(),
5402 Caller->getName(), Caller);
Duncan Sands74833f22007-09-17 10:26:40 +00005403 cast<InvokeInst>(NewCaller)->setCallingConv(II->getCallingConv());
Devang Pateld222f862008-09-25 21:00:45 +00005404 cast<InvokeInst>(NewCaller)->setAttributes(NewPAL);
Duncan Sands74833f22007-09-17 10:26:40 +00005405 } else {
Gabor Greifd6da1d02008-04-06 20:25:17 +00005406 NewCaller = CallInst::Create(NewCallee, NewArgs.begin(), NewArgs.end(),
5407 Caller->getName(), Caller);
Duncan Sands74833f22007-09-17 10:26:40 +00005408 if (cast<CallInst>(Caller)->isTailCall())
5409 cast<CallInst>(NewCaller)->setTailCall();
5410 cast<CallInst>(NewCaller)->
5411 setCallingConv(cast<CallInst>(Caller)->getCallingConv());
Devang Pateld222f862008-09-25 21:00:45 +00005412 cast<CallInst>(NewCaller)->setAttributes(NewPAL);
Duncan Sands74833f22007-09-17 10:26:40 +00005413 }
Devang Patele9d08b82009-10-14 17:29:00 +00005414 if (!Caller->getType()->isVoidTy())
Duncan Sands74833f22007-09-17 10:26:40 +00005415 Caller->replaceAllUsesWith(NewCaller);
5416 Caller->eraseFromParent();
Chris Lattner3183fb62009-08-30 06:13:40 +00005417 Worklist.Remove(Caller);
Duncan Sands74833f22007-09-17 10:26:40 +00005418 return 0;
5419 }
5420 }
5421
5422 // Replace the trampoline call with a direct call. Since there is no 'nest'
5423 // parameter, there is no need to adjust the argument list. Let the generic
5424 // code sort out any function type mismatches.
5425 Constant *NewCallee =
Owen Anderson24be4c12009-07-03 00:17:18 +00005426 NestF->getType() == PTy ? NestF :
Owen Anderson02b48c32009-07-29 18:55:55 +00005427 ConstantExpr::getBitCast(NestF, PTy);
Duncan Sands74833f22007-09-17 10:26:40 +00005428 CS.setCalledFunction(NewCallee);
5429 return CS.getInstruction();
5430}
5431
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005432
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005433
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005434Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
Chris Lattner5594a482009-11-27 00:29:05 +00005435 SmallVector<Value*, 8> Ops(GEP.op_begin(), GEP.op_end());
5436
5437 if (Value *V = SimplifyGEPInst(&Ops[0], Ops.size(), TD))
5438 return ReplaceInstUsesWith(GEP, V);
5439
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005440 Value *PtrOp = GEP.getOperand(0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005441
5442 if (isa<UndefValue>(GEP.getOperand(0)))
Owen Andersonb99ecca2009-07-30 23:03:37 +00005443 return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005444
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005445 // Eliminate unneeded casts for indices.
Chris Lattnerc0f553e2009-08-30 04:49:01 +00005446 if (TD) {
5447 bool MadeChange = false;
5448 unsigned PtrSize = TD->getPointerSizeInBits();
5449
5450 gep_type_iterator GTI = gep_type_begin(GEP);
5451 for (User::op_iterator I = GEP.op_begin() + 1, E = GEP.op_end();
5452 I != E; ++I, ++GTI) {
5453 if (!isa<SequentialType>(*GTI)) continue;
5454
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005455 // If we are using a wider index than needed for this platform, shrink it
Chris Lattnerc0f553e2009-08-30 04:49:01 +00005456 // to what we need. If narrower, sign-extend it to what we need. This
5457 // explicit cast can make subsequent optimizations more obvious.
5458 unsigned OpBits = cast<IntegerType>((*I)->getType())->getBitWidth();
Chris Lattnerc0f553e2009-08-30 04:49:01 +00005459 if (OpBits == PtrSize)
5460 continue;
5461
Chris Lattnerd6164c22009-08-30 20:01:10 +00005462 *I = Builder->CreateIntCast(*I, TD->getIntPtrType(GEP.getContext()),true);
Chris Lattnerc0f553e2009-08-30 04:49:01 +00005463 MadeChange = true;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005464 }
Chris Lattnerc0f553e2009-08-30 04:49:01 +00005465 if (MadeChange) return &GEP;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005466 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005467
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005468 // Combine Indices - If the source pointer to this getelementptr instruction
5469 // is a getelementptr instruction, combine the indices of the two
5470 // getelementptr instructions into a single instruction.
5471 //
Dan Gohman17f46f72009-07-28 01:40:03 +00005472 if (GEPOperator *Src = dyn_cast<GEPOperator>(PtrOp)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005473 // Note that if our source is a gep chain itself that we wait for that
5474 // chain to be resolved before we perform this transformation. This
5475 // avoids us creating a TON of code in some cases.
5476 //
Chris Lattnerc2c8a0a2009-08-30 05:08:50 +00005477 if (GetElementPtrInst *SrcGEP =
5478 dyn_cast<GetElementPtrInst>(Src->getOperand(0)))
5479 if (SrcGEP->getNumOperands() == 2)
5480 return 0; // Wait until our source is folded to completion.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005481
5482 SmallVector<Value*, 8> Indices;
5483
5484 // Find out whether the last index in the source GEP is a sequential idx.
5485 bool EndsWithSequential = false;
Chris Lattner1c641fc2009-08-30 05:30:55 +00005486 for (gep_type_iterator I = gep_type_begin(*Src), E = gep_type_end(*Src);
5487 I != E; ++I)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005488 EndsWithSequential = !isa<StructType>(*I);
5489
5490 // Can we combine the two pointer arithmetics offsets?
5491 if (EndsWithSequential) {
5492 // Replace: gep (gep %P, long B), long A, ...
5493 // With: T = long A+B; gep %P, T, ...
5494 //
Chris Lattnerc2c8a0a2009-08-30 05:08:50 +00005495 Value *Sum;
5496 Value *SO1 = Src->getOperand(Src->getNumOperands()-1);
5497 Value *GO1 = GEP.getOperand(1);
Owen Andersonaac28372009-07-31 20:28:14 +00005498 if (SO1 == Constant::getNullValue(SO1->getType())) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005499 Sum = GO1;
Owen Andersonaac28372009-07-31 20:28:14 +00005500 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005501 Sum = SO1;
5502 } else {
Chris Lattner1c641fc2009-08-30 05:30:55 +00005503 // If they aren't the same type, then the input hasn't been processed
5504 // by the loop above yet (which canonicalizes sequential index types to
5505 // intptr_t). Just avoid transforming this until the input has been
5506 // normalized.
5507 if (SO1->getType() != GO1->getType())
5508 return 0;
Chris Lattnerad7516a2009-08-30 18:50:58 +00005509 Sum = Builder->CreateAdd(SO1, GO1, PtrOp->getName()+".sum");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005510 }
5511
Chris Lattner1c641fc2009-08-30 05:30:55 +00005512 // Update the GEP in place if possible.
Chris Lattnerc2c8a0a2009-08-30 05:08:50 +00005513 if (Src->getNumOperands() == 2) {
5514 GEP.setOperand(0, Src->getOperand(0));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005515 GEP.setOperand(1, Sum);
5516 return &GEP;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005517 }
Chris Lattner1c641fc2009-08-30 05:30:55 +00005518 Indices.append(Src->op_begin()+1, Src->op_end()-1);
Chris Lattnerc0f553e2009-08-30 04:49:01 +00005519 Indices.push_back(Sum);
Chris Lattner1c641fc2009-08-30 05:30:55 +00005520 Indices.append(GEP.op_begin()+2, GEP.op_end());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005521 } else if (isa<Constant>(*GEP.idx_begin()) &&
5522 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
Chris Lattnerc2c8a0a2009-08-30 05:08:50 +00005523 Src->getNumOperands() != 1) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005524 // Otherwise we can do the fold if the first index of the GEP is a zero
Chris Lattner1c641fc2009-08-30 05:30:55 +00005525 Indices.append(Src->op_begin()+1, Src->op_end());
5526 Indices.append(GEP.idx_begin()+1, GEP.idx_end());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005527 }
5528
Dan Gohmanf3a08b82009-09-07 23:54:19 +00005529 if (!Indices.empty())
5530 return (cast<GEPOperator>(&GEP)->isInBounds() &&
5531 Src->isInBounds()) ?
5532 GetElementPtrInst::CreateInBounds(Src->getOperand(0), Indices.begin(),
5533 Indices.end(), GEP.getName()) :
Chris Lattnerc2c8a0a2009-08-30 05:08:50 +00005534 GetElementPtrInst::Create(Src->getOperand(0), Indices.begin(),
Chris Lattnerc0f553e2009-08-30 04:49:01 +00005535 Indices.end(), GEP.getName());
Chris Lattner95ba1ec2009-08-30 05:00:50 +00005536 }
5537
Chris Lattnerc2c8a0a2009-08-30 05:08:50 +00005538 // Handle gep(bitcast x) and gep(gep x, 0, 0, 0).
5539 if (Value *X = getBitCastOperand(PtrOp)) {
Chris Lattner95ba1ec2009-08-30 05:00:50 +00005540 assert(isa<PointerType>(X->getType()) && "Must be cast from pointer");
Chris Lattnerf3a23592009-08-30 20:36:46 +00005541
Chris Lattner83288fa2009-08-30 20:38:21 +00005542 // If the input bitcast is actually "bitcast(bitcast(x))", then we don't
5543 // want to change the gep until the bitcasts are eliminated.
5544 if (getBitCastOperand(X)) {
5545 Worklist.AddValue(PtrOp);
5546 return 0;
5547 }
5548
Chris Lattner5594a482009-11-27 00:29:05 +00005549 bool HasZeroPointerIndex = false;
5550 if (ConstantInt *C = dyn_cast<ConstantInt>(GEP.getOperand(1)))
5551 HasZeroPointerIndex = C->isZero();
5552
Chris Lattnerf3a23592009-08-30 20:36:46 +00005553 // Transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ...
5554 // into : GEP [10 x i8]* X, i32 0, ...
5555 //
5556 // Likewise, transform: GEP (bitcast i8* X to [0 x i8]*), i32 0, ...
5557 // into : GEP i8* X, ...
5558 //
5559 // This occurs when the program declares an array extern like "int X[];"
Chris Lattner95ba1ec2009-08-30 05:00:50 +00005560 if (HasZeroPointerIndex) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005561 const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
5562 const PointerType *XTy = cast<PointerType>(X->getType());
Duncan Sandscf866e62009-03-02 09:18:21 +00005563 if (const ArrayType *CATy =
5564 dyn_cast<ArrayType>(CPTy->getElementType())) {
5565 // GEP (bitcast i8* X to [0 x i8]*), i32 0, ... ?
5566 if (CATy->getElementType() == XTy->getElementType()) {
5567 // -> GEP i8* X, ...
5568 SmallVector<Value*, 8> Indices(GEP.idx_begin()+1, GEP.idx_end());
Dan Gohmanf3a08b82009-09-07 23:54:19 +00005569 return cast<GEPOperator>(&GEP)->isInBounds() ?
5570 GetElementPtrInst::CreateInBounds(X, Indices.begin(), Indices.end(),
5571 GEP.getName()) :
Dan Gohman17f46f72009-07-28 01:40:03 +00005572 GetElementPtrInst::Create(X, Indices.begin(), Indices.end(),
5573 GEP.getName());
Chris Lattnerf3a23592009-08-30 20:36:46 +00005574 }
5575
5576 if (const ArrayType *XATy = dyn_cast<ArrayType>(XTy->getElementType())){
Duncan Sandscf866e62009-03-02 09:18:21 +00005577 // GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ... ?
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005578 if (CATy->getElementType() == XATy->getElementType()) {
Duncan Sandscf866e62009-03-02 09:18:21 +00005579 // -> GEP [10 x i8]* X, i32 0, ...
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005580 // At this point, we know that the cast source type is a pointer
5581 // to an array of the same type as the destination pointer
5582 // array. Because the array type is never stepped over (there
5583 // is a leading zero) we can fold the cast into this GEP.
5584 GEP.setOperand(0, X);
5585 return &GEP;
5586 }
Duncan Sandscf866e62009-03-02 09:18:21 +00005587 }
5588 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005589 } else if (GEP.getNumOperands() == 2) {
5590 // Transform things like:
Wojciech Matyjewicz5b5ab532007-12-12 15:21:32 +00005591 // %t = getelementptr i32* bitcast ([2 x i32]* %str to i32*), i32 %V
5592 // into: %t1 = getelementptr [2 x i32]* %str, i32 0, i32 %V; bitcast
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005593 const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
5594 const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
Dan Gohmana80e2712009-07-21 23:21:54 +00005595 if (TD && isa<ArrayType>(SrcElTy) &&
Duncan Sandsec4f97d2009-05-09 07:06:46 +00005596 TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
5597 TD->getTypeAllocSize(ResElTy)) {
David Greene393be882007-09-04 15:46:09 +00005598 Value *Idx[2];
Chris Lattner03a27b42010-01-04 07:02:48 +00005599 Idx[0] = Constant::getNullValue(Type::getInt32Ty(GEP.getContext()));
David Greene393be882007-09-04 15:46:09 +00005600 Idx[1] = GEP.getOperand(1);
Dan Gohmanf3a08b82009-09-07 23:54:19 +00005601 Value *NewGEP = cast<GEPOperator>(&GEP)->isInBounds() ?
5602 Builder->CreateInBoundsGEP(X, Idx, Idx + 2, GEP.getName()) :
Chris Lattnerad7516a2009-08-30 18:50:58 +00005603 Builder->CreateGEP(X, Idx, Idx + 2, GEP.getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005604 // V and GEP are both pointer types --> BitCast
Chris Lattnerad7516a2009-08-30 18:50:58 +00005605 return new BitCastInst(NewGEP, GEP.getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005606 }
5607
5608 // Transform things like:
Wojciech Matyjewicz5b5ab532007-12-12 15:21:32 +00005609 // getelementptr i8* bitcast ([100 x double]* X to i8*), i32 %tmp
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005610 // (where tmp = 8*tmp2) into:
Wojciech Matyjewicz5b5ab532007-12-12 15:21:32 +00005611 // getelementptr [100 x double]* %arr, i32 0, i32 %tmp2; bitcast
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005612
Chris Lattner03a27b42010-01-04 07:02:48 +00005613 if (TD && isa<ArrayType>(SrcElTy) &&
5614 ResElTy == Type::getInt8Ty(GEP.getContext())) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005615 uint64_t ArrayEltSize =
Duncan Sandsec4f97d2009-05-09 07:06:46 +00005616 TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005617
5618 // Check to see if "tmp" is a scale by a multiple of ArrayEltSize. We
5619 // allow either a mul, shift, or constant here.
5620 Value *NewIdx = 0;
5621 ConstantInt *Scale = 0;
5622 if (ArrayEltSize == 1) {
5623 NewIdx = GEP.getOperand(1);
Chris Lattner1c641fc2009-08-30 05:30:55 +00005624 Scale = ConstantInt::get(cast<IntegerType>(NewIdx->getType()), 1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005625 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
Owen Andersoneacb44d2009-07-24 23:12:02 +00005626 NewIdx = ConstantInt::get(CI->getType(), 1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005627 Scale = CI;
5628 } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
5629 if (Inst->getOpcode() == Instruction::Shl &&
5630 isa<ConstantInt>(Inst->getOperand(1))) {
5631 ConstantInt *ShAmt = cast<ConstantInt>(Inst->getOperand(1));
5632 uint32_t ShAmtVal = ShAmt->getLimitedValue(64);
Owen Andersoneacb44d2009-07-24 23:12:02 +00005633 Scale = ConstantInt::get(cast<IntegerType>(Inst->getType()),
Dan Gohman8fd520a2009-06-15 22:12:54 +00005634 1ULL << ShAmtVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005635 NewIdx = Inst->getOperand(0);
5636 } else if (Inst->getOpcode() == Instruction::Mul &&
5637 isa<ConstantInt>(Inst->getOperand(1))) {
5638 Scale = cast<ConstantInt>(Inst->getOperand(1));
5639 NewIdx = Inst->getOperand(0);
5640 }
5641 }
Wojciech Matyjewicz5b5ab532007-12-12 15:21:32 +00005642
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005643 // If the index will be to exactly the right offset with the scale taken
Wojciech Matyjewicz5b5ab532007-12-12 15:21:32 +00005644 // out, perform the transformation. Note, we don't know whether Scale is
5645 // signed or not. We'll use unsigned version of division/modulo
5646 // operation after making sure Scale doesn't have the sign bit set.
Chris Lattner02962712009-02-25 18:20:01 +00005647 if (ArrayEltSize && Scale && Scale->getSExtValue() >= 0LL &&
Wojciech Matyjewicz5b5ab532007-12-12 15:21:32 +00005648 Scale->getZExtValue() % ArrayEltSize == 0) {
Owen Andersoneacb44d2009-07-24 23:12:02 +00005649 Scale = ConstantInt::get(Scale->getType(),
Wojciech Matyjewicz5b5ab532007-12-12 15:21:32 +00005650 Scale->getZExtValue() / ArrayEltSize);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005651 if (Scale->getZExtValue() != 1) {
Chris Lattnerbf09d632009-08-30 05:56:44 +00005652 Constant *C = ConstantExpr::getIntegerCast(Scale, NewIdx->getType(),
5653 false /*ZExt*/);
Chris Lattnerad7516a2009-08-30 18:50:58 +00005654 NewIdx = Builder->CreateMul(NewIdx, C, "idxscale");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005655 }
5656
5657 // Insert the new GEP instruction.
David Greene393be882007-09-04 15:46:09 +00005658 Value *Idx[2];
Chris Lattner03a27b42010-01-04 07:02:48 +00005659 Idx[0] = Constant::getNullValue(Type::getInt32Ty(GEP.getContext()));
David Greene393be882007-09-04 15:46:09 +00005660 Idx[1] = NewIdx;
Dan Gohmanf3a08b82009-09-07 23:54:19 +00005661 Value *NewGEP = cast<GEPOperator>(&GEP)->isInBounds() ?
5662 Builder->CreateInBoundsGEP(X, Idx, Idx + 2, GEP.getName()) :
5663 Builder->CreateGEP(X, Idx, Idx + 2, GEP.getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005664 // The NewGEP must be pointer typed, so must the old one -> BitCast
5665 return new BitCastInst(NewGEP, GEP.getType());
5666 }
5667 }
5668 }
5669 }
Chris Lattner111ea772009-01-09 04:53:57 +00005670
Chris Lattner94ccd5f2009-01-09 05:44:56 +00005671 /// See if we can simplify:
Chris Lattner5119c702009-08-30 05:55:36 +00005672 /// X = bitcast A* to B*
Chris Lattner94ccd5f2009-01-09 05:44:56 +00005673 /// Y = gep X, <...constant indices...>
5674 /// into a gep of the original struct. This is important for SROA and alias
5675 /// analysis of unions. If "A" is also a bitcast, wait for A/X to be merged.
Chris Lattner111ea772009-01-09 04:53:57 +00005676 if (BitCastInst *BCI = dyn_cast<BitCastInst>(PtrOp)) {
Dan Gohmana80e2712009-07-21 23:21:54 +00005677 if (TD &&
5678 !isa<BitCastInst>(BCI->getOperand(0)) && GEP.hasAllConstantIndices()) {
Chris Lattner94ccd5f2009-01-09 05:44:56 +00005679 // Determine how much the GEP moves the pointer. We are guaranteed to get
5680 // a constant back from EmitGEPOffset.
Chris Lattner63ac8422010-01-04 07:37:31 +00005681 ConstantInt *OffsetV = cast<ConstantInt>(EmitGEPOffset(&GEP));
Chris Lattner94ccd5f2009-01-09 05:44:56 +00005682 int64_t Offset = OffsetV->getSExtValue();
5683
5684 // If this GEP instruction doesn't move the pointer, just replace the GEP
5685 // with a bitcast of the real input to the dest type.
5686 if (Offset == 0) {
5687 // If the bitcast is of an allocation, and the allocation will be
5688 // converted to match the type of the cast, don't touch this.
Victor Hernandezb1687302009-10-23 21:09:37 +00005689 if (isa<AllocaInst>(BCI->getOperand(0)) ||
Victor Hernandez48c3c542009-09-18 22:35:49 +00005690 isMalloc(BCI->getOperand(0))) {
Chris Lattner94ccd5f2009-01-09 05:44:56 +00005691 // See if the bitcast simplifies, if so, don't nuke this GEP yet.
5692 if (Instruction *I = visitBitCast(*BCI)) {
5693 if (I != BCI) {
5694 I->takeName(BCI);
5695 BCI->getParent()->getInstList().insert(BCI, I);
5696 ReplaceInstUsesWith(*BCI, I);
5697 }
5698 return &GEP;
Chris Lattner111ea772009-01-09 04:53:57 +00005699 }
Chris Lattner111ea772009-01-09 04:53:57 +00005700 }
Chris Lattner94ccd5f2009-01-09 05:44:56 +00005701 return new BitCastInst(BCI->getOperand(0), GEP.getType());
Chris Lattner111ea772009-01-09 04:53:57 +00005702 }
Chris Lattner94ccd5f2009-01-09 05:44:56 +00005703
5704 // Otherwise, if the offset is non-zero, we need to find out if there is a
5705 // field at Offset in 'A's type. If so, we can pull the cast through the
5706 // GEP.
5707 SmallVector<Value*, 8> NewIndices;
5708 const Type *InTy =
5709 cast<PointerType>(BCI->getOperand(0)->getType())->getElementType();
Chris Lattner54826cd2010-01-04 07:53:58 +00005710 if (FindElementAtOffset(InTy, Offset, NewIndices)) {
Dan Gohmanf3a08b82009-09-07 23:54:19 +00005711 Value *NGEP = cast<GEPOperator>(&GEP)->isInBounds() ?
5712 Builder->CreateInBoundsGEP(BCI->getOperand(0), NewIndices.begin(),
5713 NewIndices.end()) :
5714 Builder->CreateGEP(BCI->getOperand(0), NewIndices.begin(),
5715 NewIndices.end());
Chris Lattnerad7516a2009-08-30 18:50:58 +00005716
5717 if (NGEP->getType() == GEP.getType())
5718 return ReplaceInstUsesWith(GEP, NGEP);
Chris Lattner94ccd5f2009-01-09 05:44:56 +00005719 NGEP->takeName(&GEP);
5720 return new BitCastInst(NGEP, GEP.getType());
5721 }
Chris Lattner111ea772009-01-09 04:53:57 +00005722 }
5723 }
5724
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005725 return 0;
5726}
5727
Victor Hernandez93946082009-10-24 04:23:03 +00005728Instruction *InstCombiner::visitFree(Instruction &FI) {
5729 Value *Op = FI.getOperand(1);
5730
5731 // free undef -> unreachable.
5732 if (isa<UndefValue>(Op)) {
5733 // Insert a new store to null because we cannot modify the CFG here.
Chris Lattner03a27b42010-01-04 07:02:48 +00005734 new StoreInst(ConstantInt::getTrue(FI.getContext()),
5735 UndefValue::get(Type::getInt1PtrTy(FI.getContext())), &FI);
Victor Hernandez93946082009-10-24 04:23:03 +00005736 return EraseInstFromFunction(FI);
5737 }
5738
5739 // If we have 'free null' delete the instruction. This can happen in stl code
5740 // when lots of inlining happens.
5741 if (isa<ConstantPointerNull>(Op))
5742 return EraseInstFromFunction(FI);
5743
Victor Hernandezf9a7a332009-10-26 23:43:48 +00005744 // If we have a malloc call whose only use is a free call, delete both.
Dan Gohman1674ea52009-10-27 00:11:02 +00005745 if (isMalloc(Op)) {
Victor Hernandez93946082009-10-24 04:23:03 +00005746 if (CallInst* CI = extractMallocCallFromBitCast(Op)) {
5747 if (Op->hasOneUse() && CI->hasOneUse()) {
5748 EraseInstFromFunction(FI);
5749 EraseInstFromFunction(*CI);
5750 return EraseInstFromFunction(*cast<Instruction>(Op));
5751 }
5752 } else {
5753 // Op is a call to malloc
5754 if (Op->hasOneUse()) {
5755 EraseInstFromFunction(FI);
5756 return EraseInstFromFunction(*cast<Instruction>(Op));
5757 }
5758 }
Dan Gohman1674ea52009-10-27 00:11:02 +00005759 }
Victor Hernandez93946082009-10-24 04:23:03 +00005760
5761 return 0;
5762}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005763
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005764
5765
5766Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
5767 // Change br (not X), label True, label False to: br X, label False, True
5768 Value *X = 0;
5769 BasicBlock *TrueDest;
5770 BasicBlock *FalseDest;
Dan Gohmancdff2122009-08-12 16:23:25 +00005771 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005772 !isa<Constant>(X)) {
5773 // Swap Destinations and condition...
5774 BI.setCondition(X);
5775 BI.setSuccessor(0, FalseDest);
5776 BI.setSuccessor(1, TrueDest);
5777 return &BI;
5778 }
5779
5780 // Cannonicalize fcmp_one -> fcmp_oeq
5781 FCmpInst::Predicate FPred; Value *Y;
5782 if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)),
Chris Lattner3183fb62009-08-30 06:13:40 +00005783 TrueDest, FalseDest)) &&
5784 BI.getCondition()->hasOneUse())
5785 if (FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
5786 FPred == FCmpInst::FCMP_OGE) {
5787 FCmpInst *Cond = cast<FCmpInst>(BI.getCondition());
5788 Cond->setPredicate(FCmpInst::getInversePredicate(FPred));
5789
5790 // Swap Destinations and condition.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005791 BI.setSuccessor(0, FalseDest);
5792 BI.setSuccessor(1, TrueDest);
Chris Lattner3183fb62009-08-30 06:13:40 +00005793 Worklist.Add(Cond);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005794 return &BI;
5795 }
5796
5797 // Cannonicalize icmp_ne -> icmp_eq
5798 ICmpInst::Predicate IPred;
5799 if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
Chris Lattner3183fb62009-08-30 06:13:40 +00005800 TrueDest, FalseDest)) &&
5801 BI.getCondition()->hasOneUse())
5802 if (IPred == ICmpInst::ICMP_NE || IPred == ICmpInst::ICMP_ULE ||
5803 IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
5804 IPred == ICmpInst::ICMP_SGE) {
5805 ICmpInst *Cond = cast<ICmpInst>(BI.getCondition());
5806 Cond->setPredicate(ICmpInst::getInversePredicate(IPred));
5807 // Swap Destinations and condition.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005808 BI.setSuccessor(0, FalseDest);
5809 BI.setSuccessor(1, TrueDest);
Chris Lattner3183fb62009-08-30 06:13:40 +00005810 Worklist.Add(Cond);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005811 return &BI;
5812 }
5813
5814 return 0;
5815}
5816
5817Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
5818 Value *Cond = SI.getCondition();
5819 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
5820 if (I->getOpcode() == Instruction::Add)
5821 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
5822 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
5823 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
Owen Anderson24be4c12009-07-03 00:17:18 +00005824 SI.setOperand(i,
Owen Anderson02b48c32009-07-29 18:55:55 +00005825 ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005826 AddRHS));
5827 SI.setOperand(0, I->getOperand(0));
Chris Lattner3183fb62009-08-30 06:13:40 +00005828 Worklist.Add(I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005829 return &SI;
5830 }
5831 }
5832 return 0;
5833}
5834
Matthijs Kooijmanda9ef702008-06-11 14:05:05 +00005835Instruction *InstCombiner::visitExtractValueInst(ExtractValueInst &EV) {
Matthijs Kooijman45e8eb42008-07-16 12:55:45 +00005836 Value *Agg = EV.getAggregateOperand();
Matthijs Kooijmanda9ef702008-06-11 14:05:05 +00005837
Matthijs Kooijman45e8eb42008-07-16 12:55:45 +00005838 if (!EV.hasIndices())
5839 return ReplaceInstUsesWith(EV, Agg);
5840
5841 if (Constant *C = dyn_cast<Constant>(Agg)) {
5842 if (isa<UndefValue>(C))
Owen Andersonb99ecca2009-07-30 23:03:37 +00005843 return ReplaceInstUsesWith(EV, UndefValue::get(EV.getType()));
Matthijs Kooijman45e8eb42008-07-16 12:55:45 +00005844
5845 if (isa<ConstantAggregateZero>(C))
Owen Andersonaac28372009-07-31 20:28:14 +00005846 return ReplaceInstUsesWith(EV, Constant::getNullValue(EV.getType()));
Matthijs Kooijman45e8eb42008-07-16 12:55:45 +00005847
5848 if (isa<ConstantArray>(C) || isa<ConstantStruct>(C)) {
5849 // Extract the element indexed by the first index out of the constant
5850 Value *V = C->getOperand(*EV.idx_begin());
5851 if (EV.getNumIndices() > 1)
5852 // Extract the remaining indices out of the constant indexed by the
5853 // first index
5854 return ExtractValueInst::Create(V, EV.idx_begin() + 1, EV.idx_end());
5855 else
5856 return ReplaceInstUsesWith(EV, V);
5857 }
5858 return 0; // Can't handle other constants
5859 }
5860 if (InsertValueInst *IV = dyn_cast<InsertValueInst>(Agg)) {
5861 // We're extracting from an insertvalue instruction, compare the indices
5862 const unsigned *exti, *exte, *insi, *inse;
5863 for (exti = EV.idx_begin(), insi = IV->idx_begin(),
5864 exte = EV.idx_end(), inse = IV->idx_end();
5865 exti != exte && insi != inse;
5866 ++exti, ++insi) {
5867 if (*insi != *exti)
5868 // The insert and extract both reference distinctly different elements.
5869 // This means the extract is not influenced by the insert, and we can
5870 // replace the aggregate operand of the extract with the aggregate
5871 // operand of the insert. i.e., replace
5872 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
5873 // %E = extractvalue { i32, { i32 } } %I, 0
5874 // with
5875 // %E = extractvalue { i32, { i32 } } %A, 0
5876 return ExtractValueInst::Create(IV->getAggregateOperand(),
5877 EV.idx_begin(), EV.idx_end());
5878 }
5879 if (exti == exte && insi == inse)
5880 // Both iterators are at the end: Index lists are identical. Replace
5881 // %B = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
5882 // %C = extractvalue { i32, { i32 } } %B, 1, 0
5883 // with "i32 42"
5884 return ReplaceInstUsesWith(EV, IV->getInsertedValueOperand());
5885 if (exti == exte) {
5886 // The extract list is a prefix of the insert list. i.e. replace
5887 // %I = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
5888 // %E = extractvalue { i32, { i32 } } %I, 1
5889 // with
5890 // %X = extractvalue { i32, { i32 } } %A, 1
5891 // %E = insertvalue { i32 } %X, i32 42, 0
5892 // by switching the order of the insert and extract (though the
5893 // insertvalue should be left in, since it may have other uses).
Chris Lattnerad7516a2009-08-30 18:50:58 +00005894 Value *NewEV = Builder->CreateExtractValue(IV->getAggregateOperand(),
5895 EV.idx_begin(), EV.idx_end());
Matthijs Kooijman45e8eb42008-07-16 12:55:45 +00005896 return InsertValueInst::Create(NewEV, IV->getInsertedValueOperand(),
5897 insi, inse);
5898 }
5899 if (insi == inse)
5900 // The insert list is a prefix of the extract list
5901 // We can simply remove the common indices from the extract and make it
5902 // operate on the inserted value instead of the insertvalue result.
5903 // i.e., replace
5904 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
5905 // %E = extractvalue { i32, { i32 } } %I, 1, 0
5906 // with
5907 // %E extractvalue { i32 } { i32 42 }, 0
5908 return ExtractValueInst::Create(IV->getInsertedValueOperand(),
5909 exti, exte);
5910 }
Chris Lattner69a70752009-11-09 07:07:56 +00005911 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Agg)) {
5912 // We're extracting from an intrinsic, see if we're the only user, which
5913 // allows us to simplify multiple result intrinsics to simpler things that
5914 // just get one value..
5915 if (II->hasOneUse()) {
5916 // Check if we're grabbing the overflow bit or the result of a 'with
5917 // overflow' intrinsic. If it's the latter we can remove the intrinsic
5918 // and replace it with a traditional binary instruction.
5919 switch (II->getIntrinsicID()) {
5920 case Intrinsic::uadd_with_overflow:
5921 case Intrinsic::sadd_with_overflow:
5922 if (*EV.idx_begin() == 0) { // Normal result.
5923 Value *LHS = II->getOperand(1), *RHS = II->getOperand(2);
5924 II->replaceAllUsesWith(UndefValue::get(II->getType()));
5925 EraseInstFromFunction(*II);
5926 return BinaryOperator::CreateAdd(LHS, RHS);
5927 }
5928 break;
5929 case Intrinsic::usub_with_overflow:
5930 case Intrinsic::ssub_with_overflow:
5931 if (*EV.idx_begin() == 0) { // Normal result.
5932 Value *LHS = II->getOperand(1), *RHS = II->getOperand(2);
5933 II->replaceAllUsesWith(UndefValue::get(II->getType()));
5934 EraseInstFromFunction(*II);
5935 return BinaryOperator::CreateSub(LHS, RHS);
5936 }
5937 break;
5938 case Intrinsic::umul_with_overflow:
5939 case Intrinsic::smul_with_overflow:
5940 if (*EV.idx_begin() == 0) { // Normal result.
5941 Value *LHS = II->getOperand(1), *RHS = II->getOperand(2);
5942 II->replaceAllUsesWith(UndefValue::get(II->getType()));
5943 EraseInstFromFunction(*II);
5944 return BinaryOperator::CreateMul(LHS, RHS);
5945 }
5946 break;
5947 default:
5948 break;
5949 }
5950 }
5951 }
Matthijs Kooijman45e8eb42008-07-16 12:55:45 +00005952 // Can't simplify extracts from other values. Note that nested extracts are
5953 // already simplified implicitely by the above (extract ( extract (insert) )
5954 // will be translated into extract ( insert ( extract ) ) first and then just
5955 // the value inserted, if appropriate).
Matthijs Kooijmanda9ef702008-06-11 14:05:05 +00005956 return 0;
5957}
5958
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005959
5960
5961
5962/// TryToSinkInstruction - Try to move the specified instruction from its
5963/// current block into the beginning of DestBlock, which can only happen if it's
5964/// safe to move the instruction past all of the instructions between it and the
5965/// end of its block.
5966static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
5967 assert(I->hasOneUse() && "Invariants didn't hold!");
5968
5969 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
Duncan Sands2f500832009-05-06 06:49:50 +00005970 if (isa<PHINode>(I) || I->mayHaveSideEffects() || isa<TerminatorInst>(I))
Chris Lattnercb19a1c2008-05-09 15:07:33 +00005971 return false;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005972
5973 // Do not sink alloca instructions out of the entry block.
5974 if (isa<AllocaInst>(I) && I->getParent() ==
5975 &DestBlock->getParent()->getEntryBlock())
5976 return false;
5977
5978 // We can only sink load instructions if there is nothing between the load and
5979 // the end of block that could change the value.
Chris Lattner0db40a62008-05-08 17:37:37 +00005980 if (I->mayReadFromMemory()) {
5981 for (BasicBlock::iterator Scan = I, E = I->getParent()->end();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005982 Scan != E; ++Scan)
5983 if (Scan->mayWriteToMemory())
5984 return false;
5985 }
5986
Dan Gohman514277c2008-05-23 21:05:58 +00005987 BasicBlock::iterator InsertPos = DestBlock->getFirstNonPHI();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005988
5989 I->moveBefore(InsertPos);
5990 ++NumSunkInst;
5991 return true;
5992}
5993
5994
5995/// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
5996/// all reachable code to the worklist.
5997///
5998/// This has a couple of tricks to make the code faster and more powerful. In
5999/// particular, we constant fold and DCE instructions as we go, to avoid adding
6000/// them to the worklist (this significantly speeds up instcombine on code where
6001/// many instructions are dead or constant). Additionally, if we find a branch
6002/// whose condition is a known constant, we only visit the reachable successors.
6003///
Chris Lattnerc4269e52009-10-15 04:59:28 +00006004static bool AddReachableCodeToWorklist(BasicBlock *BB,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006005 SmallPtrSet<BasicBlock*, 64> &Visited,
6006 InstCombiner &IC,
6007 const TargetData *TD) {
Chris Lattnerc4269e52009-10-15 04:59:28 +00006008 bool MadeIRChange = false;
Chris Lattnera06291a2008-08-15 04:03:01 +00006009 SmallVector<BasicBlock*, 256> Worklist;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006010 Worklist.push_back(BB);
Chris Lattnerb5663c72009-10-12 03:58:40 +00006011
6012 std::vector<Instruction*> InstrsForInstCombineWorklist;
6013 InstrsForInstCombineWorklist.reserve(128);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006014
Chris Lattnerc4269e52009-10-15 04:59:28 +00006015 SmallPtrSet<ConstantExpr*, 64> FoldedConstants;
6016
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006017 while (!Worklist.empty()) {
6018 BB = Worklist.back();
6019 Worklist.pop_back();
6020
6021 // We have now visited this block! If we've already been here, ignore it.
6022 if (!Visited.insert(BB)) continue;
Devang Patel794140c2008-11-19 18:56:50 +00006023
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006024 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
6025 Instruction *Inst = BBI++;
6026
6027 // DCE instruction if trivially dead.
6028 if (isInstructionTriviallyDead(Inst)) {
6029 ++NumDeadInst;
Chris Lattner8a6411c2009-08-23 04:37:46 +00006030 DEBUG(errs() << "IC: DCE: " << *Inst << '\n');
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006031 Inst->eraseFromParent();
6032 continue;
6033 }
6034
6035 // ConstantProp instruction if trivially constant.
Chris Lattneree5839b2009-10-15 04:13:44 +00006036 if (!Inst->use_empty() && isa<Constant>(Inst->getOperand(0)))
Chris Lattner6070c012009-11-06 04:27:31 +00006037 if (Constant *C = ConstantFoldInstruction(Inst, TD)) {
Chris Lattneree5839b2009-10-15 04:13:44 +00006038 DEBUG(errs() << "IC: ConstFold to: " << *C << " from: "
6039 << *Inst << '\n');
6040 Inst->replaceAllUsesWith(C);
6041 ++NumConstProp;
6042 Inst->eraseFromParent();
6043 continue;
6044 }
Chris Lattnerc4269e52009-10-15 04:59:28 +00006045
6046
6047
6048 if (TD) {
6049 // See if we can constant fold its operands.
6050 for (User::op_iterator i = Inst->op_begin(), e = Inst->op_end();
6051 i != e; ++i) {
6052 ConstantExpr *CE = dyn_cast<ConstantExpr>(i);
6053 if (CE == 0) continue;
6054
6055 // If we already folded this constant, don't try again.
6056 if (!FoldedConstants.insert(CE))
6057 continue;
6058
Chris Lattner6070c012009-11-06 04:27:31 +00006059 Constant *NewC = ConstantFoldConstantExpression(CE, TD);
Chris Lattnerc4269e52009-10-15 04:59:28 +00006060 if (NewC && NewC != CE) {
6061 *i = NewC;
6062 MadeIRChange = true;
6063 }
6064 }
6065 }
6066
Devang Patel794140c2008-11-19 18:56:50 +00006067
Chris Lattnerb5663c72009-10-12 03:58:40 +00006068 InstrsForInstCombineWorklist.push_back(Inst);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006069 }
6070
6071 // Recursively visit successors. If this is a branch or switch on a
6072 // constant, only visit the reachable successor.
6073 TerminatorInst *TI = BB->getTerminator();
6074 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
6075 if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
6076 bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
Nick Lewyckyd551cf12008-03-09 08:50:23 +00006077 BasicBlock *ReachableBB = BI->getSuccessor(!CondVal);
Nick Lewyckyd8aa33a2008-04-25 16:53:59 +00006078 Worklist.push_back(ReachableBB);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006079 continue;
6080 }
6081 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
6082 if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
6083 // See if this is an explicit destination.
6084 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
6085 if (SI->getCaseValue(i) == Cond) {
Nick Lewyckyd551cf12008-03-09 08:50:23 +00006086 BasicBlock *ReachableBB = SI->getSuccessor(i);
Nick Lewyckyd8aa33a2008-04-25 16:53:59 +00006087 Worklist.push_back(ReachableBB);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006088 continue;
6089 }
6090
6091 // Otherwise it is the default destination.
6092 Worklist.push_back(SI->getSuccessor(0));
6093 continue;
6094 }
6095 }
6096
6097 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
6098 Worklist.push_back(TI->getSuccessor(i));
6099 }
Chris Lattnerb5663c72009-10-12 03:58:40 +00006100
6101 // Once we've found all of the instructions to add to instcombine's worklist,
6102 // add them in reverse order. This way instcombine will visit from the top
6103 // of the function down. This jives well with the way that it adds all uses
6104 // of instructions to the worklist after doing a transformation, thus avoiding
6105 // some N^2 behavior in pathological cases.
6106 IC.Worklist.AddInitialGroup(&InstrsForInstCombineWorklist[0],
6107 InstrsForInstCombineWorklist.size());
Chris Lattnerc4269e52009-10-15 04:59:28 +00006108
6109 return MadeIRChange;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006110}
6111
6112bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) {
Chris Lattner21d79e22009-08-31 06:57:37 +00006113 MadeIRChange = false;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006114
Daniel Dunbar005975c2009-07-25 00:23:56 +00006115 DEBUG(errs() << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
6116 << F.getNameStr() << "\n");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006117
6118 {
6119 // Do a depth-first traversal of the function, populate the worklist with
6120 // the reachable instructions. Ignore blocks that are not reachable. Keep
6121 // track of which blocks we visit.
6122 SmallPtrSet<BasicBlock*, 64> Visited;
Chris Lattnerc4269e52009-10-15 04:59:28 +00006123 MadeIRChange |= AddReachableCodeToWorklist(F.begin(), Visited, *this, TD);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006124
6125 // Do a quick scan over the function. If we find any blocks that are
6126 // unreachable, remove any instructions inside of them. This prevents
6127 // the instcombine code from having to deal with some bad special cases.
6128 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
6129 if (!Visited.count(BB)) {
6130 Instruction *Term = BB->getTerminator();
6131 while (Term != BB->begin()) { // Remove instrs bottom-up
6132 BasicBlock::iterator I = Term; --I;
6133
Chris Lattner8a6411c2009-08-23 04:37:46 +00006134 DEBUG(errs() << "IC: DCE: " << *I << '\n');
Dale Johannesendf356c62009-03-10 21:19:49 +00006135 // A debug intrinsic shouldn't force another iteration if we weren't
6136 // going to do one without it.
6137 if (!isa<DbgInfoIntrinsic>(I)) {
6138 ++NumDeadInst;
Chris Lattner21d79e22009-08-31 06:57:37 +00006139 MadeIRChange = true;
Dale Johannesendf356c62009-03-10 21:19:49 +00006140 }
Devang Patele3829c82009-10-13 22:56:32 +00006141
Devang Patele3829c82009-10-13 22:56:32 +00006142 // If I is not void type then replaceAllUsesWith undef.
6143 // This allows ValueHandlers and custom metadata to adjust itself.
Devang Patele9d08b82009-10-14 17:29:00 +00006144 if (!I->getType()->isVoidTy())
Devang Patele3829c82009-10-13 22:56:32 +00006145 I->replaceAllUsesWith(UndefValue::get(I->getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006146 I->eraseFromParent();
6147 }
6148 }
6149 }
6150
Chris Lattner5119c702009-08-30 05:55:36 +00006151 while (!Worklist.isEmpty()) {
6152 Instruction *I = Worklist.RemoveOne();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006153 if (I == 0) continue; // skip null values.
6154
6155 // Check to see if we can DCE the instruction.
6156 if (isInstructionTriviallyDead(I)) {
Chris Lattner8a6411c2009-08-23 04:37:46 +00006157 DEBUG(errs() << "IC: DCE: " << *I << '\n');
Chris Lattner3183fb62009-08-30 06:13:40 +00006158 EraseInstFromFunction(*I);
6159 ++NumDeadInst;
Chris Lattner21d79e22009-08-31 06:57:37 +00006160 MadeIRChange = true;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006161 continue;
6162 }
6163
6164 // Instruction isn't dead, see if we can constant propagate it.
Chris Lattneree5839b2009-10-15 04:13:44 +00006165 if (!I->use_empty() && isa<Constant>(I->getOperand(0)))
Chris Lattner6070c012009-11-06 04:27:31 +00006166 if (Constant *C = ConstantFoldInstruction(I, TD)) {
Chris Lattneree5839b2009-10-15 04:13:44 +00006167 DEBUG(errs() << "IC: ConstFold to: " << *C << " from: " << *I << '\n');
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006168
Chris Lattneree5839b2009-10-15 04:13:44 +00006169 // Add operands to the worklist.
6170 ReplaceInstUsesWith(*I, C);
6171 ++NumConstProp;
6172 EraseInstFromFunction(*I);
6173 MadeIRChange = true;
6174 continue;
6175 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006176
6177 // See if we can trivially sink this instruction to a successor basic block.
Dan Gohman29474e92008-07-23 00:34:11 +00006178 if (I->hasOneUse()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006179 BasicBlock *BB = I->getParent();
Chris Lattnerf27a0432009-10-14 15:21:58 +00006180 Instruction *UserInst = cast<Instruction>(I->use_back());
6181 BasicBlock *UserParent;
6182
6183 // Get the block the use occurs in.
6184 if (PHINode *PN = dyn_cast<PHINode>(UserInst))
6185 UserParent = PN->getIncomingBlock(I->use_begin().getUse());
6186 else
6187 UserParent = UserInst->getParent();
6188
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006189 if (UserParent != BB) {
6190 bool UserIsSuccessor = false;
6191 // See if the user is one of our successors.
6192 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
6193 if (*SI == UserParent) {
6194 UserIsSuccessor = true;
6195 break;
6196 }
6197
6198 // If the user is one of our immediate successors, and if that successor
6199 // only has us as a predecessors (we'd have to split the critical edge
6200 // otherwise), we can keep going.
Chris Lattnerf27a0432009-10-14 15:21:58 +00006201 if (UserIsSuccessor && UserParent->getSinglePredecessor())
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006202 // Okay, the CFG is simple enough, try to sink this instruction.
Chris Lattner21d79e22009-08-31 06:57:37 +00006203 MadeIRChange |= TryToSinkInstruction(I, UserParent);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006204 }
6205 }
6206
Chris Lattnerc7694852009-08-30 07:44:24 +00006207 // Now that we have an instruction, try combining it to simplify it.
6208 Builder->SetInsertPoint(I->getParent(), I);
6209
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006210#ifndef NDEBUG
6211 std::string OrigI;
6212#endif
Chris Lattner8a6411c2009-08-23 04:37:46 +00006213 DEBUG(raw_string_ostream SS(OrigI); I->print(SS); OrigI = SS.str(););
Jeffrey Yasskin17091f02009-10-08 00:12:24 +00006214 DEBUG(errs() << "IC: Visiting: " << OrigI << '\n');
6215
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006216 if (Instruction *Result = visit(*I)) {
6217 ++NumCombined;
6218 // Should we replace the old instruction with a new one?
6219 if (Result != I) {
Chris Lattner8a6411c2009-08-23 04:37:46 +00006220 DEBUG(errs() << "IC: Old = " << *I << '\n'
6221 << " New = " << *Result << '\n');
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006222
6223 // Everything uses the new instruction now.
6224 I->replaceAllUsesWith(Result);
6225
6226 // Push the new instruction and any users onto the worklist.
Chris Lattner3183fb62009-08-30 06:13:40 +00006227 Worklist.Add(Result);
Chris Lattner4796b622009-08-30 06:22:51 +00006228 Worklist.AddUsersToWorkList(*Result);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006229
6230 // Move the name to the new instruction first.
6231 Result->takeName(I);
6232
6233 // Insert the new instruction into the basic block...
6234 BasicBlock *InstParent = I->getParent();
6235 BasicBlock::iterator InsertPos = I;
6236
6237 if (!isa<PHINode>(Result)) // If combining a PHI, don't insert
6238 while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
6239 ++InsertPos;
6240
6241 InstParent->getInstList().insert(InsertPos, Result);
6242
Chris Lattner3183fb62009-08-30 06:13:40 +00006243 EraseInstFromFunction(*I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006244 } else {
6245#ifndef NDEBUG
Chris Lattner8a6411c2009-08-23 04:37:46 +00006246 DEBUG(errs() << "IC: Mod = " << OrigI << '\n'
6247 << " New = " << *I << '\n');
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006248#endif
6249
6250 // If the instruction was modified, it's possible that it is now dead.
6251 // if so, remove it.
6252 if (isInstructionTriviallyDead(I)) {
Chris Lattner3183fb62009-08-30 06:13:40 +00006253 EraseInstFromFunction(*I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006254 } else {
Chris Lattner3183fb62009-08-30 06:13:40 +00006255 Worklist.Add(I);
Chris Lattner4796b622009-08-30 06:22:51 +00006256 Worklist.AddUsersToWorkList(*I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006257 }
6258 }
Chris Lattner21d79e22009-08-31 06:57:37 +00006259 MadeIRChange = true;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006260 }
6261 }
6262
Chris Lattner5119c702009-08-30 05:55:36 +00006263 Worklist.Zap();
Chris Lattner21d79e22009-08-31 06:57:37 +00006264 return MadeIRChange;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006265}
6266
6267
6268bool InstCombiner::runOnFunction(Function &F) {
6269 MustPreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
Chris Lattneree5839b2009-10-15 04:13:44 +00006270 TD = getAnalysisIfAvailable<TargetData>();
6271
Chris Lattnerc7694852009-08-30 07:44:24 +00006272
6273 /// Builder - This is an IRBuilder that automatically inserts new
6274 /// instructions into the worklist when they are created.
Chris Lattneree5839b2009-10-15 04:13:44 +00006275 IRBuilder<true, TargetFolder, InstCombineIRInserter>
Chris Lattner002e65d2009-11-06 05:59:53 +00006276 TheBuilder(F.getContext(), TargetFolder(TD),
Chris Lattnerc7694852009-08-30 07:44:24 +00006277 InstCombineIRInserter(Worklist));
6278 Builder = &TheBuilder;
6279
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006280 bool EverMadeChange = false;
6281
6282 // Iterate while there is work to do.
6283 unsigned Iteration = 0;
Bill Wendlingd9644a42008-05-14 22:45:20 +00006284 while (DoOneIteration(F, Iteration++))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006285 EverMadeChange = true;
Chris Lattnerc7694852009-08-30 07:44:24 +00006286
6287 Builder = 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006288 return EverMadeChange;
6289}
6290
6291FunctionPass *llvm::createInstructionCombiningPass() {
6292 return new InstCombiner();
6293}