blob: f9acd20b55526b033fcfdcfc4dbe37561654fc5e [file] [log] [blame]
Chris Lattner233f7dc2002-08-12 21:17:25 +00001//===- InstructionCombining.cpp - Combine multiple instructions -----------===//
Misha Brukmanfd939082005-04-21 23:48:37 +00002//
John Criswellb576c942003-10-20 19:43:21 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattner4ee451d2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Misha Brukmanfd939082005-04-21 23:48:37 +00007//
John Criswellb576c942003-10-20 19:43:21 +00008//===----------------------------------------------------------------------===//
Chris Lattner8a2a3112001-12-14 16:52:21 +00009//
10// InstructionCombining - Combine instructions to form fewer, simple
Dan Gohman844731a2008-05-13 00:00:25 +000011// instructions. This pass does not modify the CFG. This pass is where
12// algebraic simplification happens.
Chris Lattner8a2a3112001-12-14 16:52:21 +000013//
14// This pass combines things like:
Chris Lattner318bf792007-03-18 22:51:34 +000015// %Y = add i32 %X, 1
16// %Z = add i32 %Y, 1
Chris Lattner8a2a3112001-12-14 16:52:21 +000017// into:
Chris Lattner318bf792007-03-18 22:51:34 +000018// %Z = add i32 %X, 2
Chris Lattner8a2a3112001-12-14 16:52:21 +000019//
20// This is a simple worklist driven algorithm.
21//
Chris Lattner065a6162003-09-10 05:29:43 +000022// This pass guarantees that the following canonicalizations are performed on
Chris Lattner2cd91962003-07-23 21:41:57 +000023// the program:
24// 1. If a binary operator has a constant operand, it is moved to the RHS
Chris Lattnerdf17af12003-08-12 21:53:41 +000025// 2. Bitwise operators with constant operands are always grouped so that
26// shifts are performed first, then or's, then and's, then xor's.
Reid Spencere4d87aa2006-12-23 06:05:41 +000027// 3. Compare instructions are converted from <,>,<=,>= to ==,!= if possible
28// 4. All cmp instructions on boolean values are replaced with logical ops
Chris Lattnere92d2f42003-08-13 04:18:28 +000029// 5. add X, X is represented as (X*2) => (X << 1)
30// 6. Multiplies with a power-of-two constant argument are transformed into
31// shifts.
Chris Lattnerbac32862004-11-14 19:13:23 +000032// ... etc.
Chris Lattner2cd91962003-07-23 21:41:57 +000033//
Chris Lattner8a2a3112001-12-14 16:52:21 +000034//===----------------------------------------------------------------------===//
35
Chris Lattner0cea42a2004-03-13 23:54:27 +000036#define DEBUG_TYPE "instcombine"
Chris Lattner022103b2002-05-07 20:03:00 +000037#include "llvm/Transforms/Scalar.h"
Chris Lattnerac8f2fd2010-01-04 07:12:23 +000038#include "InstCombine.h"
Chris Lattner35b9e482004-10-12 04:52:52 +000039#include "llvm/IntrinsicInst.h"
Owen Andersond672ecb2009-07-03 00:17:18 +000040#include "llvm/LLVMContext.h"
Chris Lattner0864acf2002-11-04 16:18:53 +000041#include "llvm/DerivedTypes.h"
Chris Lattner833b8a42003-06-26 05:06:25 +000042#include "llvm/GlobalVariable.h"
Dan Gohmanca178902009-07-17 20:47:02 +000043#include "llvm/Operator.h"
Chris Lattner79066fa2007-01-30 23:46:24 +000044#include "llvm/Analysis/ConstantFolding.h"
Chris Lattner9dbb4292009-11-09 23:28:39 +000045#include "llvm/Analysis/InstructionSimplify.h"
Victor Hernandezf006b182009-10-27 20:05:49 +000046#include "llvm/Analysis/MemoryBuiltins.h"
Chris Lattnerbc61e662003-11-02 05:57:39 +000047#include "llvm/Target/TargetData.h"
48#include "llvm/Transforms/Utils/BasicBlockUtils.h"
49#include "llvm/Transforms/Utils/Local.h"
Chris Lattner28977af2004-04-05 01:30:19 +000050#include "llvm/Support/CallSite.h"
Chris Lattnerea1c4542004-12-08 23:43:58 +000051#include "llvm/Support/Debug.h"
Torok Edwin7d696d82009-07-11 13:10:19 +000052#include "llvm/Support/ErrorHandling.h"
Chris Lattner28977af2004-04-05 01:30:19 +000053#include "llvm/Support/GetElementPtrTypeIterator.h"
Chris Lattnerbcd7db52005-08-02 19:16:58 +000054#include "llvm/Support/MathExtras.h"
Chris Lattneracd1f0f2004-07-30 07:50:03 +000055#include "llvm/Support/PatternMatch.h"
Chris Lattner1f87a582007-02-15 19:41:52 +000056#include "llvm/ADT/SmallPtrSet.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000057#include "llvm/ADT/Statistic.h"
Chris Lattnerea1c4542004-12-08 23:43:58 +000058#include "llvm/ADT/STLExtras.h"
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +000059#include <algorithm>
Torok Edwin3eaee312008-04-20 08:33:11 +000060#include <climits>
Chris Lattner67b1e1b2003-12-07 01:24:23 +000061using namespace llvm;
Chris Lattneracd1f0f2004-07-30 07:50:03 +000062using namespace llvm::PatternMatch;
Brian Gaeked0fde302003-11-11 22:41:34 +000063
Chris Lattner0e5f4992006-12-19 21:40:18 +000064STATISTIC(NumCombined , "Number of insts combined");
65STATISTIC(NumConstProp, "Number of constant folds");
66STATISTIC(NumDeadInst , "Number of dead inst eliminated");
Chris Lattner0e5f4992006-12-19 21:40:18 +000067STATISTIC(NumSunkInst , "Number of instructions sunk");
Chris Lattnera92f6962002-10-01 22:38:41 +000068
Chris Lattnerdd841ae2002-04-18 17:39:14 +000069
Dan Gohman844731a2008-05-13 00:00:25 +000070char InstCombiner::ID = 0;
71static RegisterPass<InstCombiner>
72X("instcombine", "Combine redundant instructions");
73
Chris Lattnere0b4b722010-01-04 07:17:19 +000074void InstCombiner::getAnalysisUsage(AnalysisUsage &AU) const {
75 AU.addPreservedID(LCSSAID);
76 AU.setPreservesCFG();
77}
78
79
Chris Lattnerc8802d22003-03-11 00:12:48 +000080// isOnlyUse - Return true if this instruction will be deleted if we stop using
81// it.
82static bool isOnlyUse(Value *V) {
Chris Lattnerfd059242003-10-15 16:48:29 +000083 return V->hasOneUse() || isa<Constant>(V);
Chris Lattnerc8802d22003-03-11 00:12:48 +000084}
85
Chris Lattner4cb170c2004-02-23 06:38:22 +000086// getPromotedType - Return the specified type promoted as it would be to pass
87// though a va_arg area...
88static const Type *getPromotedType(const Type *Ty) {
Reid Spencera54b7cb2007-01-12 07:05:14 +000089 if (const IntegerType* ITy = dyn_cast<IntegerType>(Ty)) {
90 if (ITy->getBitWidth() < 32)
Owen Anderson1d0be152009-08-13 21:58:54 +000091 return Type::getInt32Ty(Ty->getContext());
Chris Lattner2b7e0ad2007-05-23 01:17:04 +000092 }
Reid Spencera54b7cb2007-01-12 07:05:14 +000093 return Ty;
Chris Lattner4cb170c2004-02-23 06:38:22 +000094}
95
Chris Lattnerc22d4d12009-11-10 07:23:37 +000096/// ShouldChangeType - Return true if it is desirable to convert a computation
97/// from 'From' to 'To'. We don't want to convert from a legal to an illegal
98/// type for example, or from a smaller to a larger illegal type.
Chris Lattner80f43d32010-01-04 07:53:58 +000099bool InstCombiner::ShouldChangeType(const Type *From, const Type *To) const {
Chris Lattnerc22d4d12009-11-10 07:23:37 +0000100 assert(isa<IntegerType>(From) && isa<IntegerType>(To));
101
102 // If we don't have TD, we don't know if the source/dest are legal.
103 if (!TD) return false;
104
105 unsigned FromWidth = From->getPrimitiveSizeInBits();
106 unsigned ToWidth = To->getPrimitiveSizeInBits();
107 bool FromLegal = TD->isLegalInteger(FromWidth);
108 bool ToLegal = TD->isLegalInteger(ToWidth);
109
110 // If this is a legal integer from type, and the result would be an illegal
111 // type, don't do the transformation.
112 if (FromLegal && !ToLegal)
113 return false;
114
115 // Otherwise, if both are illegal, do not increase the size of the result. We
116 // do allow things like i160 -> i64, but not i64 -> i160.
117 if (!FromLegal && !ToLegal && ToWidth > FromWidth)
118 return false;
119
120 return true;
121}
122
Matthijs Kooijman7e6d9b92008-10-13 15:17:01 +0000123/// getBitCastOperand - If the specified operand is a CastInst, a constant
124/// expression bitcast, or a GetElementPtrInst with all zero indices, return the
125/// operand value, otherwise return null.
Reid Spencer3da59db2006-11-27 01:05:10 +0000126static Value *getBitCastOperand(Value *V) {
Dan Gohman016de812009-07-17 23:55:56 +0000127 if (Operator *O = dyn_cast<Operator>(V)) {
128 if (O->getOpcode() == Instruction::BitCast)
129 return O->getOperand(0);
130 if (GEPOperator *GEP = dyn_cast<GEPOperator>(V))
131 if (GEP->hasAllZeroIndices())
132 return GEP->getPointerOperand();
Matthijs Kooijman7e6d9b92008-10-13 15:17:01 +0000133 }
Chris Lattnereed48272005-09-13 00:40:14 +0000134 return 0;
135}
136
Dan Gohmance9fe9f2009-07-21 23:21:54 +0000137
Chris Lattner33a61132006-05-06 09:00:16 +0000138
Chris Lattner4f98c562003-03-10 21:43:22 +0000139// SimplifyCommutative - This performs a few simplifications for commutative
140// operators:
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000141//
Chris Lattner4f98c562003-03-10 21:43:22 +0000142// 1. Order operands such that they are listed from right (least complex) to
143// left (most complex). This puts constants before unary operators before
144// binary operators.
145//
Chris Lattnerc8802d22003-03-11 00:12:48 +0000146// 2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
147// 3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattner4f98c562003-03-10 21:43:22 +0000148//
Chris Lattnerc8802d22003-03-11 00:12:48 +0000149bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +0000150 bool Changed = false;
Dan Gohman14ef4f02009-08-29 23:39:38 +0000151 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
Chris Lattner4f98c562003-03-10 21:43:22 +0000152 Changed = !I.swapOperands();
Misha Brukmanfd939082005-04-21 23:48:37 +0000153
Chris Lattner4f98c562003-03-10 21:43:22 +0000154 if (!I.isAssociative()) return Changed;
155 Instruction::BinaryOps Opcode = I.getOpcode();
Chris Lattnerc8802d22003-03-11 00:12:48 +0000156 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
157 if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
158 if (isa<Constant>(I.getOperand(1))) {
Owen Andersonbaf3c402009-07-29 18:55:55 +0000159 Constant *Folded = ConstantExpr::get(I.getOpcode(),
Chris Lattner2a9c8472003-05-27 16:40:51 +0000160 cast<Constant>(I.getOperand(1)),
161 cast<Constant>(Op->getOperand(1)));
Chris Lattnerc8802d22003-03-11 00:12:48 +0000162 I.setOperand(0, Op->getOperand(0));
163 I.setOperand(1, Folded);
164 return true;
165 } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
166 if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
167 isOnlyUse(Op) && isOnlyUse(Op1)) {
168 Constant *C1 = cast<Constant>(Op->getOperand(1));
169 Constant *C2 = cast<Constant>(Op1->getOperand(1));
170
171 // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Owen Andersonbaf3c402009-07-29 18:55:55 +0000172 Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000173 Instruction *New = BinaryOperator::Create(Opcode, Op->getOperand(0),
Chris Lattnerc8802d22003-03-11 00:12:48 +0000174 Op1->getOperand(0),
175 Op1->getName(), &I);
Chris Lattner7a1e9242009-08-30 06:13:40 +0000176 Worklist.Add(New);
Chris Lattnerc8802d22003-03-11 00:12:48 +0000177 I.setOperand(0, New);
178 I.setOperand(1, Folded);
179 return true;
Misha Brukmanfd939082005-04-21 23:48:37 +0000180 }
Chris Lattner4f98c562003-03-10 21:43:22 +0000181 }
Chris Lattner4f98c562003-03-10 21:43:22 +0000182 return Changed;
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000183}
Chris Lattner8a2a3112001-12-14 16:52:21 +0000184
Chris Lattner8d969642003-03-10 23:06:50 +0000185// dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
186// if the LHS is a constant zero (which is the 'negate' form).
Chris Lattnerb35dde12002-05-06 16:49:18 +0000187//
Chris Lattner02446fc2010-01-04 07:37:31 +0000188Value *InstCombiner::dyn_castNegVal(Value *V) const {
Owen Andersonfa82b6e2009-07-13 22:18:28 +0000189 if (BinaryOperator::isNeg(V))
Chris Lattnera1df33c2005-04-24 07:30:14 +0000190 return BinaryOperator::getNegArgument(V);
Chris Lattner8d969642003-03-10 23:06:50 +0000191
Chris Lattner0ce85802004-12-14 20:08:06 +0000192 // Constants can be considered to be negated values if they can be folded.
193 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
Owen Andersonbaf3c402009-07-29 18:55:55 +0000194 return ConstantExpr::getNeg(C);
Nick Lewycky18b3da62008-05-23 04:54:45 +0000195
196 if (ConstantVector *C = dyn_cast<ConstantVector>(V))
197 if (C->getType()->getElementType()->isInteger())
Owen Andersonbaf3c402009-07-29 18:55:55 +0000198 return ConstantExpr::getNeg(C);
Nick Lewycky18b3da62008-05-23 04:54:45 +0000199
Chris Lattner8d969642003-03-10 23:06:50 +0000200 return 0;
Chris Lattnerb35dde12002-05-06 16:49:18 +0000201}
202
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000203// dyn_castFNegVal - Given a 'fsub' instruction, return the RHS of the
204// instruction if the LHS is a constant negative zero (which is the 'negate'
205// form).
206//
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000207Value *InstCombiner::dyn_castFNegVal(Value *V) const {
Owen Andersonfa82b6e2009-07-13 22:18:28 +0000208 if (BinaryOperator::isFNeg(V))
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000209 return BinaryOperator::getFNegArgument(V);
210
211 // Constants can be considered to be negated values if they can be folded.
212 if (ConstantFP *C = dyn_cast<ConstantFP>(V))
Owen Andersonbaf3c402009-07-29 18:55:55 +0000213 return ConstantExpr::getFNeg(C);
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000214
215 if (ConstantVector *C = dyn_cast<ConstantVector>(V))
216 if (C->getType()->getElementType()->isFloatingPoint())
Owen Andersonbaf3c402009-07-29 18:55:55 +0000217 return ConstantExpr::getFNeg(C);
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000218
219 return 0;
220}
221
Chris Lattner48b59ec2009-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 Cheng85def162009-10-26 03:51:32 +0000226 if (BinaryOperator::isNot(V))
Chris Lattner48b59ec2009-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 }
Chris Lattner8d969642003-03-10 23:06:50 +0000248
249 // Constants can be considered to be not'ed values...
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000250 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
Dan Gohman186a6362009-08-12 16:04:34 +0000251 return ConstantInt::get(C->getType(), ~C->getValue());
Chris Lattner8d969642003-03-10 23:06:50 +0000252 return 0;
253}
254
Chris Lattner48b59ec2009-10-26 15:40:07 +0000255
256
Chris Lattnerc8802d22003-03-11 00:12:48 +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
Chris Lattner50af16a2004-11-13 19:50:12 +0000259// non-constant operand of the multiply, and set CST to point to the multiplier.
260// Otherwise, return null.
Chris Lattnerc8802d22003-03-11 00:12:48 +0000261//
Dan Gohman186a6362009-08-12 16:04:34 +0000262static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST) {
Chris Lattner42a75512007-01-15 02:27:26 +0000263 if (V->hasOneUse() && V->getType()->isInteger())
Chris Lattner50af16a2004-11-13 19:50:12 +0000264 if (Instruction *I = dyn_cast<Instruction>(V)) {
Chris Lattnerc8802d22003-03-11 00:12:48 +0000265 if (I->getOpcode() == Instruction::Mul)
Chris Lattner50e60c72004-11-15 05:54:07 +0000266 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
Chris Lattnerc8802d22003-03-11 00:12:48 +0000267 return I->getOperand(0);
Chris Lattner50af16a2004-11-13 19:50:12 +0000268 if (I->getOpcode() == Instruction::Shl)
Chris Lattner50e60c72004-11-15 05:54:07 +0000269 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
Chris Lattner50af16a2004-11-13 19:50:12 +0000270 // The multiplier is really 1 << CST.
Zhou Sheng97b52c22007-03-29 01:57:21 +0000271 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +0000272 uint32_t CSTVal = CST->getLimitedValue(BitWidth);
Dan Gohman186a6362009-08-12 16:04:34 +0000273 CST = ConstantInt::get(V->getType()->getContext(),
274 APInt(BitWidth, 1).shl(CSTVal));
Chris Lattner50af16a2004-11-13 19:50:12 +0000275 return I->getOperand(0);
276 }
277 }
Chris Lattnerc8802d22003-03-11 00:12:48 +0000278 return 0;
Chris Lattnera2881962003-02-18 19:28:33 +0000279}
Chris Lattneraf2930e2002-08-14 17:51:49 +0000280
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000281/// AddOne - Add one to a ConstantInt.
Dan Gohman186a6362009-08-12 16:04:34 +0000282static Constant *AddOne(Constant *C) {
Chris Lattner02446fc2010-01-04 07:37:31 +0000283 return ConstantExpr::getAdd(C, ConstantInt::get(C->getType(), 1));
Chris Lattner955f3312004-09-28 21:48:02 +0000284}
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000285/// SubOne - Subtract one from a ConstantInt.
Dan Gohman186a6362009-08-12 16:04:34 +0000286static Constant *SubOne(ConstantInt *C) {
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000287 return ConstantInt::get(C->getContext(), C->getValue()-1);
Chris Lattner955f3312004-09-28 21:48:02 +0000288}
Reid Spencere7816b52007-03-08 01:52:58 +0000289
Dan Gohman45b4e482008-05-19 22:14:15 +0000290
Chris Lattner564a7272003-08-13 19:01:45 +0000291/// AssociativeOpt - Perform an optimization on an associative operator. This
292/// function is designed to check a chain of associative operators for a
293/// potential to apply a certain optimization. Since the optimization may be
294/// applicable if the expression was reassociated, this checks the chain, then
295/// reassociates the expression as necessary to expose the optimization
296/// opportunity. This makes use of a special Functor, which must define
297/// 'shouldApply' and 'apply' methods.
298///
299template<typename Functor>
Dan Gohman186a6362009-08-12 16:04:34 +0000300static Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
Chris Lattner564a7272003-08-13 19:01:45 +0000301 // Quick check, see if the immediate LHS matches...
Chris Lattnerd0db8e82010-01-05 06:24:06 +0000302 if (F.shouldApply(Root.getOperand(0)))
Chris Lattner564a7272003-08-13 19:01:45 +0000303 return F.apply(Root);
304
Chris Lattner564a7272003-08-13 19:01:45 +0000305 return 0;
306}
307
Chris Lattner6e7ba452005-01-01 16:22:27 +0000308static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
Chris Lattner2eefe512004-04-09 19:05:30 +0000309 InstCombiner *IC) {
Chris Lattner08142f22009-08-30 19:47:22 +0000310 if (CastInst *CI = dyn_cast<CastInst>(&I))
Chris Lattner2345d1d2009-08-30 20:01:10 +0000311 return IC->Builder->CreateCast(CI->getOpcode(), SO, I.getType());
Chris Lattner6e7ba452005-01-01 16:22:27 +0000312
Chris Lattner2eefe512004-04-09 19:05:30 +0000313 // Figure out if the constant is the left or the right argument.
Chris Lattner6e7ba452005-01-01 16:22:27 +0000314 bool ConstIsRHS = isa<Constant>(I.getOperand(1));
315 Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
Chris Lattner564a7272003-08-13 19:01:45 +0000316
Chris Lattner2eefe512004-04-09 19:05:30 +0000317 if (Constant *SOC = dyn_cast<Constant>(SO)) {
318 if (ConstIsRHS)
Owen Andersonbaf3c402009-07-29 18:55:55 +0000319 return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
320 return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
Chris Lattner2eefe512004-04-09 19:05:30 +0000321 }
322
323 Value *Op0 = SO, *Op1 = ConstOperand;
324 if (!ConstIsRHS)
325 std::swap(Op0, Op1);
Chris Lattner74381062009-08-30 07:44:24 +0000326
Chris Lattner6e7ba452005-01-01 16:22:27 +0000327 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
Chris Lattner74381062009-08-30 07:44:24 +0000328 return IC->Builder->CreateBinOp(BO->getOpcode(), Op0, Op1,
329 SO->getName()+".op");
330 if (ICmpInst *CI = dyn_cast<ICmpInst>(&I))
331 return IC->Builder->CreateICmp(CI->getPredicate(), Op0, Op1,
332 SO->getName()+".cmp");
333 if (FCmpInst *CI = dyn_cast<FCmpInst>(&I))
334 return IC->Builder->CreateICmp(CI->getPredicate(), Op0, Op1,
335 SO->getName()+".cmp");
336 llvm_unreachable("Unknown binary instruction type!");
Chris Lattner6e7ba452005-01-01 16:22:27 +0000337}
338
339// FoldOpIntoSelect - Given an instruction with a select as one operand and a
340// constant as the other operand, try to fold the binary operator into the
341// select arguments. This also works for Cast instructions, which obviously do
342// not have a second operand.
Chris Lattner80f43d32010-01-04 07:53:58 +0000343Instruction *InstCombiner::FoldOpIntoSelect(Instruction &Op, SelectInst *SI) {
Chris Lattner6e7ba452005-01-01 16:22:27 +0000344 // Don't modify shared select instructions
345 if (!SI->hasOneUse()) return 0;
346 Value *TV = SI->getOperand(1);
347 Value *FV = SI->getOperand(2);
348
349 if (isa<Constant>(TV) || isa<Constant>(FV)) {
Chris Lattner956db272005-04-21 05:43:13 +0000350 // Bool selects with constant operands can be folded to logical ops.
Chris Lattner4de84762010-01-04 07:02:48 +0000351 if (SI->getType() == Type::getInt1Ty(SI->getContext())) return 0;
Chris Lattner956db272005-04-21 05:43:13 +0000352
Chris Lattner80f43d32010-01-04 07:53:58 +0000353 Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, this);
354 Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, this);
Chris Lattner6e7ba452005-01-01 16:22:27 +0000355
Gabor Greif051a9502008-04-06 20:25:17 +0000356 return SelectInst::Create(SI->getCondition(), SelectTrueVal,
357 SelectFalseVal);
Chris Lattner6e7ba452005-01-01 16:22:27 +0000358 }
359 return 0;
Chris Lattner2eefe512004-04-09 19:05:30 +0000360}
361
Chris Lattner4e998b22004-09-29 05:07:12 +0000362
Chris Lattner5d1704d2009-09-27 19:57:57 +0000363/// FoldOpIntoPhi - Given a binary operator, cast instruction, or select which
364/// has a PHI node as operand #0, see if we can fold the instruction into the
365/// PHI (which is only possible if all operands to the PHI are constants).
Chris Lattner213cd612009-09-27 20:46:36 +0000366///
367/// If AllowAggressive is true, FoldOpIntoPhi will allow certain transforms
368/// that would normally be unprofitable because they strongly encourage jump
369/// threading.
370Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I,
371 bool AllowAggressive) {
372 AllowAggressive = false;
Chris Lattner4e998b22004-09-29 05:07:12 +0000373 PHINode *PN = cast<PHINode>(I.getOperand(0));
Chris Lattnerbac32862004-11-14 19:13:23 +0000374 unsigned NumPHIValues = PN->getNumIncomingValues();
Chris Lattner213cd612009-09-27 20:46:36 +0000375 if (NumPHIValues == 0 ||
376 // We normally only transform phis with a single use, unless we're trying
377 // hard to make jump threading happen.
378 (!PN->hasOneUse() && !AllowAggressive))
379 return 0;
380
381
Chris Lattner5d1704d2009-09-27 19:57:57 +0000382 // Check to see if all of the operands of the PHI are simple constants
383 // (constantint/constantfp/undef). If there is one non-constant value,
Chris Lattnerc6df8f42009-09-27 20:18:49 +0000384 // remember the BB it is in. If there is more than one or if *it* is a PHI,
385 // bail out. We don't do arbitrary constant expressions here because moving
386 // their computation can be expensive without a cost model.
Chris Lattner2a86f3b2006-09-09 22:02:56 +0000387 BasicBlock *NonConstBB = 0;
388 for (unsigned i = 0; i != NumPHIValues; ++i)
Chris Lattner5d1704d2009-09-27 19:57:57 +0000389 if (!isa<Constant>(PN->getIncomingValue(i)) ||
390 isa<ConstantExpr>(PN->getIncomingValue(i))) {
Chris Lattner2a86f3b2006-09-09 22:02:56 +0000391 if (NonConstBB) return 0; // More than one non-const value.
Chris Lattnerb3036682007-02-24 01:03:45 +0000392 if (isa<PHINode>(PN->getIncomingValue(i))) return 0; // Itself a phi.
Chris Lattner2a86f3b2006-09-09 22:02:56 +0000393 NonConstBB = PN->getIncomingBlock(i);
394
395 // If the incoming non-constant value is in I's block, we have an infinite
396 // loop.
397 if (NonConstBB == I.getParent())
398 return 0;
399 }
400
401 // If there is exactly one non-constant value, we can insert a copy of the
402 // operation in that block. However, if this is a critical edge, we would be
403 // inserting the computation one some other paths (e.g. inside a loop). Only
404 // do this if the pred block is unconditionally branching into the phi block.
Chris Lattner213cd612009-09-27 20:46:36 +0000405 if (NonConstBB != 0 && !AllowAggressive) {
Chris Lattner2a86f3b2006-09-09 22:02:56 +0000406 BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
407 if (!BI || !BI->isUnconditional()) return 0;
408 }
Chris Lattner4e998b22004-09-29 05:07:12 +0000409
410 // Okay, we can do the transformation: create the new PHI node.
Gabor Greif051a9502008-04-06 20:25:17 +0000411 PHINode *NewPN = PHINode::Create(I.getType(), "");
Chris Lattner55517062005-01-29 00:39:08 +0000412 NewPN->reserveOperandSpace(PN->getNumOperands()/2);
Chris Lattner857eb572009-10-21 23:41:58 +0000413 InsertNewInstBefore(NewPN, *PN);
414 NewPN->takeName(PN);
Chris Lattner4e998b22004-09-29 05:07:12 +0000415
416 // Next, add all of the operands to the PHI.
Chris Lattner5d1704d2009-09-27 19:57:57 +0000417 if (SelectInst *SI = dyn_cast<SelectInst>(&I)) {
418 // We only currently try to fold the condition of a select when it is a phi,
419 // not the true/false values.
Chris Lattnerc6df8f42009-09-27 20:18:49 +0000420 Value *TrueV = SI->getTrueValue();
421 Value *FalseV = SI->getFalseValue();
Chris Lattner3ddfb212009-09-28 06:49:44 +0000422 BasicBlock *PhiTransBB = PN->getParent();
Chris Lattner5d1704d2009-09-27 19:57:57 +0000423 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattnerc6df8f42009-09-27 20:18:49 +0000424 BasicBlock *ThisBB = PN->getIncomingBlock(i);
Chris Lattner3ddfb212009-09-28 06:49:44 +0000425 Value *TrueVInPred = TrueV->DoPHITranslation(PhiTransBB, ThisBB);
426 Value *FalseVInPred = FalseV->DoPHITranslation(PhiTransBB, ThisBB);
Chris Lattner5d1704d2009-09-27 19:57:57 +0000427 Value *InV = 0;
428 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Chris Lattnerc6df8f42009-09-27 20:18:49 +0000429 InV = InC->isNullValue() ? FalseVInPred : TrueVInPred;
Chris Lattner5d1704d2009-09-27 19:57:57 +0000430 } else {
431 assert(PN->getIncomingBlock(i) == NonConstBB);
Chris Lattnerc6df8f42009-09-27 20:18:49 +0000432 InV = SelectInst::Create(PN->getIncomingValue(i), TrueVInPred,
433 FalseVInPred,
Chris Lattner5d1704d2009-09-27 19:57:57 +0000434 "phitmp", NonConstBB->getTerminator());
Chris Lattner857eb572009-10-21 23:41:58 +0000435 Worklist.Add(cast<Instruction>(InV));
Chris Lattner5d1704d2009-09-27 19:57:57 +0000436 }
Chris Lattnerc6df8f42009-09-27 20:18:49 +0000437 NewPN->addIncoming(InV, ThisBB);
Chris Lattner5d1704d2009-09-27 19:57:57 +0000438 }
439 } else if (I.getNumOperands() == 2) {
Chris Lattner4e998b22004-09-29 05:07:12 +0000440 Constant *C = cast<Constant>(I.getOperand(1));
Chris Lattnerbac32862004-11-14 19:13:23 +0000441 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattnera9ff5eb2007-08-05 08:47:58 +0000442 Value *InV = 0;
Chris Lattner2a86f3b2006-09-09 22:02:56 +0000443 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Reid Spencere4d87aa2006-12-23 06:05:41 +0000444 if (CmpInst *CI = dyn_cast<CmpInst>(&I))
Owen Andersonbaf3c402009-07-29 18:55:55 +0000445 InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C);
Reid Spencere4d87aa2006-12-23 06:05:41 +0000446 else
Owen Andersonbaf3c402009-07-29 18:55:55 +0000447 InV = ConstantExpr::get(I.getOpcode(), InC, C);
Chris Lattner2a86f3b2006-09-09 22:02:56 +0000448 } else {
449 assert(PN->getIncomingBlock(i) == NonConstBB);
450 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000451 InV = BinaryOperator::Create(BO->getOpcode(),
Chris Lattner2a86f3b2006-09-09 22:02:56 +0000452 PN->getIncomingValue(i), C, "phitmp",
453 NonConstBB->getTerminator());
Reid Spencere4d87aa2006-12-23 06:05:41 +0000454 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
Dan Gohman1c8a23c2009-08-25 23:17:54 +0000455 InV = CmpInst::Create(CI->getOpcode(),
Reid Spencere4d87aa2006-12-23 06:05:41 +0000456 CI->getPredicate(),
457 PN->getIncomingValue(i), C, "phitmp",
458 NonConstBB->getTerminator());
Chris Lattner2a86f3b2006-09-09 22:02:56 +0000459 else
Torok Edwinc23197a2009-07-14 16:55:14 +0000460 llvm_unreachable("Unknown binop!");
Chris Lattner857eb572009-10-21 23:41:58 +0000461
462 Worklist.Add(cast<Instruction>(InV));
Chris Lattner2a86f3b2006-09-09 22:02:56 +0000463 }
464 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner4e998b22004-09-29 05:07:12 +0000465 }
Reid Spencer3da59db2006-11-27 01:05:10 +0000466 } else {
467 CastInst *CI = cast<CastInst>(&I);
468 const Type *RetTy = CI->getType();
Chris Lattnerbac32862004-11-14 19:13:23 +0000469 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattner2a86f3b2006-09-09 22:02:56 +0000470 Value *InV;
471 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Owen Andersonbaf3c402009-07-29 18:55:55 +0000472 InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
Chris Lattner2a86f3b2006-09-09 22:02:56 +0000473 } else {
474 assert(PN->getIncomingBlock(i) == NonConstBB);
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000475 InV = CastInst::Create(CI->getOpcode(), PN->getIncomingValue(i),
Reid Spencer3da59db2006-11-27 01:05:10 +0000476 I.getType(), "phitmp",
477 NonConstBB->getTerminator());
Chris Lattner857eb572009-10-21 23:41:58 +0000478 Worklist.Add(cast<Instruction>(InV));
Chris Lattner2a86f3b2006-09-09 22:02:56 +0000479 }
480 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner4e998b22004-09-29 05:07:12 +0000481 }
482 }
483 return ReplaceInstUsesWith(I, NewPN);
484}
485
Chris Lattner2454a2e2008-01-29 06:52:45 +0000486
Chris Lattner3d28b1b2008-05-20 05:46:13 +0000487/// WillNotOverflowSignedAdd - Return true if we can prove that:
488/// (sext (add LHS, RHS)) === (add (sext LHS), (sext RHS))
489/// This basically requires proving that the add in the original type would not
490/// overflow to change the sign bit or have a carry out.
491bool InstCombiner::WillNotOverflowSignedAdd(Value *LHS, Value *RHS) {
492 // There are different heuristics we can use for this. Here are some simple
493 // ones.
494
495 // Add has the property that adding any two 2's complement numbers can only
496 // have one carry bit which can change a sign. As such, if LHS and RHS each
Chris Lattner8aee8ef2009-11-27 17:42:22 +0000497 // have at least two sign bits, we know that the addition of the two values
498 // will sign extend fine.
Chris Lattner3d28b1b2008-05-20 05:46:13 +0000499 if (ComputeNumSignBits(LHS) > 1 && ComputeNumSignBits(RHS) > 1)
500 return true;
501
502
503 // If one of the operands only has one non-zero bit, and if the other operand
504 // has a known-zero bit in a more significant place than it (not including the
505 // sign bit) the ripple may go up to and fill the zero, but won't change the
506 // sign. For example, (X & ~4) + 1.
507
508 // TODO: Implement.
509
510 return false;
511}
512
Chris Lattner2454a2e2008-01-29 06:52:45 +0000513
Chris Lattner7e708292002-06-25 16:13:24 +0000514Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +0000515 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +0000516 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
Chris Lattnerb35dde12002-05-06 16:49:18 +0000517
Chris Lattner8aee8ef2009-11-27 17:42:22 +0000518 if (Value *V = SimplifyAddInst(LHS, RHS, I.hasNoSignedWrap(),
519 I.hasNoUnsignedWrap(), TD))
520 return ReplaceInstUsesWith(I, V);
521
522
Chris Lattner66331a42004-04-10 22:01:55 +0000523 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
Chris Lattner66331a42004-04-10 22:01:55 +0000524 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
Chris Lattnerb4a2f052006-11-09 05:12:27 +0000525 // X + (signbit) --> X ^ signbit
Zhou Sheng3a507fd2007-04-01 17:13:37 +0000526 const APInt& Val = CI->getValue();
Zhou Sheng4351c642007-04-02 08:20:41 +0000527 uint32_t BitWidth = Val.getBitWidth();
Reid Spencer2ec619a2007-03-23 21:24:59 +0000528 if (Val == APInt::getSignBit(BitWidth))
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000529 return BinaryOperator::CreateXor(LHS, RHS);
Chris Lattnerb4a2f052006-11-09 05:12:27 +0000530
531 // See if SimplifyDemandedBits can simplify this. This handles stuff like
532 // (X & 254)+1 -> (X&254)|1
Dan Gohman6de29f82009-06-15 22:12:54 +0000533 if (SimplifyDemandedInstructionBits(I))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000534 return &I;
Dan Gohman1975d032008-10-30 20:40:10 +0000535
Eli Friedman709b33d2009-07-13 22:27:52 +0000536 // zext(bool) + C -> bool ? C + 1 : C
Dan Gohman1975d032008-10-30 20:40:10 +0000537 if (ZExtInst *ZI = dyn_cast<ZExtInst>(LHS))
Chris Lattner4de84762010-01-04 07:02:48 +0000538 if (ZI->getSrcTy() == Type::getInt1Ty(I.getContext()))
Dan Gohman186a6362009-08-12 16:04:34 +0000539 return SelectInst::Create(ZI->getOperand(0), AddOne(CI), CI);
Chris Lattner66331a42004-04-10 22:01:55 +0000540 }
Chris Lattner4e998b22004-09-29 05:07:12 +0000541
542 if (isa<PHINode>(LHS))
543 if (Instruction *NV = FoldOpIntoPhi(I))
544 return NV;
Chris Lattner5931c542005-09-24 23:43:33 +0000545
Chris Lattner4f637d42006-01-06 17:59:59 +0000546 ConstantInt *XorRHS = 0;
547 Value *XorLHS = 0;
Chris Lattnerc5eff442007-01-30 22:32:46 +0000548 if (isa<ConstantInt>(RHSC) &&
Dan Gohman4ae51262009-08-12 16:23:25 +0000549 match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
Dan Gohman6de29f82009-06-15 22:12:54 +0000550 uint32_t TySizeBits = I.getType()->getScalarSizeInBits();
Zhou Sheng3a507fd2007-04-01 17:13:37 +0000551 const APInt& RHSVal = cast<ConstantInt>(RHSC)->getValue();
Chris Lattner5931c542005-09-24 23:43:33 +0000552
Zhou Sheng4351c642007-04-02 08:20:41 +0000553 uint32_t Size = TySizeBits / 2;
Reid Spencer2ec619a2007-03-23 21:24:59 +0000554 APInt C0080Val(APInt(TySizeBits, 1ULL).shl(Size - 1));
555 APInt CFF80Val(-C0080Val);
Chris Lattner5931c542005-09-24 23:43:33 +0000556 do {
557 if (TySizeBits > Size) {
Chris Lattner5931c542005-09-24 23:43:33 +0000558 // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
559 // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
Reid Spencer2ec619a2007-03-23 21:24:59 +0000560 if ((RHSVal == CFF80Val && XorRHS->getValue() == C0080Val) ||
561 (RHSVal == C0080Val && XorRHS->getValue() == CFF80Val)) {
Chris Lattner5931c542005-09-24 23:43:33 +0000562 // This is a sign extend if the top bits are known zero.
Zhou Sheng290bec52007-03-29 08:15:12 +0000563 if (!MaskedValueIsZero(XorLHS,
564 APInt::getHighBitsSet(TySizeBits, TySizeBits - Size)))
Chris Lattner5931c542005-09-24 23:43:33 +0000565 Size = 0; // Not a sign ext, but can't be any others either.
Reid Spencer2ec619a2007-03-23 21:24:59 +0000566 break;
Chris Lattner5931c542005-09-24 23:43:33 +0000567 }
568 }
569 Size >>= 1;
Reid Spencer2ec619a2007-03-23 21:24:59 +0000570 C0080Val = APIntOps::lshr(C0080Val, Size);
571 CFF80Val = APIntOps::ashr(CFF80Val, Size);
572 } while (Size >= 1);
Chris Lattner5931c542005-09-24 23:43:33 +0000573
Reid Spencer35c38852007-03-28 01:36:16 +0000574 // FIXME: This shouldn't be necessary. When the backends can handle types
Chris Lattner0c7a9a02008-05-19 20:25:04 +0000575 // with funny bit widths then this switch statement should be removed. It
576 // is just here to get the size of the "middle" type back up to something
577 // that the back ends can handle.
Reid Spencer35c38852007-03-28 01:36:16 +0000578 const Type *MiddleType = 0;
579 switch (Size) {
580 default: break;
Chris Lattner4de84762010-01-04 07:02:48 +0000581 case 32:
582 case 16:
583 case 8: MiddleType = IntegerType::get(I.getContext(), Size); break;
Reid Spencer35c38852007-03-28 01:36:16 +0000584 }
585 if (MiddleType) {
Chris Lattner74381062009-08-30 07:44:24 +0000586 Value *NewTrunc = Builder->CreateTrunc(XorLHS, MiddleType, "sext");
Reid Spencer35c38852007-03-28 01:36:16 +0000587 return new SExtInst(NewTrunc, I.getType(), I.getName());
Chris Lattner5931c542005-09-24 23:43:33 +0000588 }
589 }
Chris Lattner66331a42004-04-10 22:01:55 +0000590 }
Chris Lattnerb35dde12002-05-06 16:49:18 +0000591
Chris Lattner4de84762010-01-04 07:02:48 +0000592 if (I.getType() == Type::getInt1Ty(I.getContext()))
Nick Lewycky9419ddb2008-05-31 17:59:52 +0000593 return BinaryOperator::CreateXor(LHS, RHS);
594
Nick Lewycky9419ddb2008-05-31 17:59:52 +0000595 if (I.getType()->isInteger()) {
Chris Lattner32c0cf52010-01-05 06:29:13 +0000596 // X + X --> X << 1
597 if (LHS == RHS)
598 return BinaryOperator::CreateShl(LHS, ConstantInt::get(I.getType(), 1));
Chris Lattner7edc8c22005-04-07 17:14:51 +0000599
600 if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
601 if (RHSI->getOpcode() == Instruction::Sub)
602 if (LHS == RHSI->getOperand(1)) // A + (B - A) --> B
603 return ReplaceInstUsesWith(I, RHSI->getOperand(0));
604 }
605 if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
606 if (LHSI->getOpcode() == Instruction::Sub)
607 if (RHS == LHSI->getOperand(1)) // (B - A) + A --> B
608 return ReplaceInstUsesWith(I, LHSI->getOperand(0));
609 }
Robert Bocchino71698282004-07-27 21:02:21 +0000610 }
Chris Lattnere92d2f42003-08-13 04:18:28 +0000611
Chris Lattner5c4afb92002-05-08 22:46:53 +0000612 // -A + B --> B - A
Chris Lattnerdd12f962008-02-17 21:03:36 +0000613 // -A + -B --> -(A + B)
Dan Gohman186a6362009-08-12 16:04:34 +0000614 if (Value *LHSV = dyn_castNegVal(LHS)) {
Chris Lattnere10c0b92008-02-18 17:50:16 +0000615 if (LHS->getType()->isIntOrIntVector()) {
Dan Gohman186a6362009-08-12 16:04:34 +0000616 if (Value *RHSV = dyn_castNegVal(RHS)) {
Chris Lattner74381062009-08-30 07:44:24 +0000617 Value *NewAdd = Builder->CreateAdd(LHSV, RHSV, "sum");
Dan Gohman4ae51262009-08-12 16:23:25 +0000618 return BinaryOperator::CreateNeg(NewAdd);
Chris Lattnere10c0b92008-02-18 17:50:16 +0000619 }
Chris Lattnerdd12f962008-02-17 21:03:36 +0000620 }
621
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000622 return BinaryOperator::CreateSub(RHS, LHSV);
Chris Lattnerdd12f962008-02-17 21:03:36 +0000623 }
Chris Lattnerb35dde12002-05-06 16:49:18 +0000624
625 // A + -B --> A - B
Chris Lattner8d969642003-03-10 23:06:50 +0000626 if (!isa<Constant>(RHS))
Dan Gohman186a6362009-08-12 16:04:34 +0000627 if (Value *V = dyn_castNegVal(RHS))
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000628 return BinaryOperator::CreateSub(LHS, V);
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000629
Misha Brukmanfd939082005-04-21 23:48:37 +0000630
Chris Lattner50af16a2004-11-13 19:50:12 +0000631 ConstantInt *C2;
Dan Gohman186a6362009-08-12 16:04:34 +0000632 if (Value *X = dyn_castFoldableMul(LHS, C2)) {
Chris Lattner50af16a2004-11-13 19:50:12 +0000633 if (X == RHS) // X*C + X --> X * (C+1)
Dan Gohman186a6362009-08-12 16:04:34 +0000634 return BinaryOperator::CreateMul(RHS, AddOne(C2));
Chris Lattner50af16a2004-11-13 19:50:12 +0000635
636 // X*C1 + X*C2 --> X * (C1+C2)
637 ConstantInt *C1;
Dan Gohman186a6362009-08-12 16:04:34 +0000638 if (X == dyn_castFoldableMul(RHS, C1))
Owen Andersonbaf3c402009-07-29 18:55:55 +0000639 return BinaryOperator::CreateMul(X, ConstantExpr::getAdd(C1, C2));
Chris Lattnerad3448c2003-02-18 19:57:07 +0000640 }
641
642 // X + X*C --> X * (C+1)
Dan Gohman186a6362009-08-12 16:04:34 +0000643 if (dyn_castFoldableMul(RHS, C2) == LHS)
644 return BinaryOperator::CreateMul(LHS, AddOne(C2));
Chris Lattner50af16a2004-11-13 19:50:12 +0000645
Chris Lattnere617c9e2007-01-05 02:17:46 +0000646 // X + ~X --> -1 since ~X = -X-1
Dan Gohman186a6362009-08-12 16:04:34 +0000647 if (dyn_castNotVal(LHS) == RHS ||
648 dyn_castNotVal(RHS) == LHS)
Owen Andersona7235ea2009-07-31 20:28:14 +0000649 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnere617c9e2007-01-05 02:17:46 +0000650
Chris Lattnerad3448c2003-02-18 19:57:07 +0000651
Chris Lattner5e0d7182008-05-19 20:01:56 +0000652 // A+B --> A|B iff A and B have no bits set in common.
653 if (const IntegerType *IT = dyn_cast<IntegerType>(I.getType())) {
654 APInt Mask = APInt::getAllOnesValue(IT->getBitWidth());
655 APInt LHSKnownOne(IT->getBitWidth(), 0);
656 APInt LHSKnownZero(IT->getBitWidth(), 0);
657 ComputeMaskedBits(LHS, Mask, LHSKnownZero, LHSKnownOne);
658 if (LHSKnownZero != 0) {
659 APInt RHSKnownOne(IT->getBitWidth(), 0);
660 APInt RHSKnownZero(IT->getBitWidth(), 0);
661 ComputeMaskedBits(RHS, Mask, RHSKnownZero, RHSKnownOne);
662
663 // No bits in common -> bitwise or.
Chris Lattner9d60ba92008-05-19 20:03:53 +0000664 if ((LHSKnownZero|RHSKnownZero).isAllOnesValue())
Chris Lattner5e0d7182008-05-19 20:01:56 +0000665 return BinaryOperator::CreateOr(LHS, RHS);
Chris Lattner5e0d7182008-05-19 20:01:56 +0000666 }
667 }
Chris Lattnerc8802d22003-03-11 00:12:48 +0000668
Nick Lewyckyb6eabff2008-02-03 07:42:09 +0000669 // W*X + Y*Z --> W * (X+Z) iff W == Y
Nick Lewycky0c2c3f62008-02-03 08:19:11 +0000670 if (I.getType()->isIntOrIntVector()) {
Nick Lewyckyb6eabff2008-02-03 07:42:09 +0000671 Value *W, *X, *Y, *Z;
Dan Gohman4ae51262009-08-12 16:23:25 +0000672 if (match(LHS, m_Mul(m_Value(W), m_Value(X))) &&
673 match(RHS, m_Mul(m_Value(Y), m_Value(Z)))) {
Nick Lewyckyb6eabff2008-02-03 07:42:09 +0000674 if (W != Y) {
675 if (W == Z) {
Bill Wendling587c01d2008-02-26 10:53:30 +0000676 std::swap(Y, Z);
Nick Lewyckyb6eabff2008-02-03 07:42:09 +0000677 } else if (Y == X) {
Bill Wendling587c01d2008-02-26 10:53:30 +0000678 std::swap(W, X);
679 } else if (X == Z) {
Nick Lewyckyb6eabff2008-02-03 07:42:09 +0000680 std::swap(Y, Z);
681 std::swap(W, X);
682 }
683 }
684
685 if (W == Y) {
Chris Lattner74381062009-08-30 07:44:24 +0000686 Value *NewAdd = Builder->CreateAdd(X, Z, LHS->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000687 return BinaryOperator::CreateMul(W, NewAdd);
Nick Lewyckyb6eabff2008-02-03 07:42:09 +0000688 }
689 }
690 }
691
Chris Lattner6b032052003-10-02 15:11:26 +0000692 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
Chris Lattner4f637d42006-01-06 17:59:59 +0000693 Value *X = 0;
Dan Gohman4ae51262009-08-12 16:23:25 +0000694 if (match(LHS, m_Not(m_Value(X)))) // ~X + C --> (C-1) - X
Dan Gohman186a6362009-08-12 16:04:34 +0000695 return BinaryOperator::CreateSub(SubOne(CRHS), X);
Chris Lattneracd1f0f2004-07-30 07:50:03 +0000696
Chris Lattnerb99d6b12004-10-08 05:07:56 +0000697 // (X & FF00) + xx00 -> (X+xx00) & FF00
Owen Andersonc7d2ce72009-07-10 17:35:01 +0000698 if (LHS->hasOneUse() &&
Dan Gohman4ae51262009-08-12 16:23:25 +0000699 match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
Owen Andersonbaf3c402009-07-29 18:55:55 +0000700 Constant *Anded = ConstantExpr::getAnd(CRHS, C2);
Chris Lattnerb99d6b12004-10-08 05:07:56 +0000701 if (Anded == CRHS) {
702 // See if all bits from the first bit set in the Add RHS up are included
703 // in the mask. First, get the rightmost bit.
Chris Lattner32c0cf52010-01-05 06:29:13 +0000704 const APInt &AddRHSV = CRHS->getValue();
Chris Lattnerb99d6b12004-10-08 05:07:56 +0000705
706 // Form a mask of all bits from the lowest bit added through the top.
Zhou Sheng3a507fd2007-04-01 17:13:37 +0000707 APInt AddRHSHighBits(~((AddRHSV & -AddRHSV)-1));
Chris Lattnerb99d6b12004-10-08 05:07:56 +0000708
709 // See if the and mask includes all of these bits.
Zhou Sheng3a507fd2007-04-01 17:13:37 +0000710 APInt AddRHSHighBitsAnd(AddRHSHighBits & C2->getValue());
Misha Brukmanfd939082005-04-21 23:48:37 +0000711
Chris Lattnerb99d6b12004-10-08 05:07:56 +0000712 if (AddRHSHighBits == AddRHSHighBitsAnd) {
713 // Okay, the xform is safe. Insert the new add pronto.
Chris Lattner74381062009-08-30 07:44:24 +0000714 Value *NewAdd = Builder->CreateAdd(X, CRHS, LHS->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000715 return BinaryOperator::CreateAnd(NewAdd, C2);
Chris Lattnerb99d6b12004-10-08 05:07:56 +0000716 }
717 }
718 }
719
Chris Lattneracd1f0f2004-07-30 07:50:03 +0000720 // Try to fold constant add into select arguments.
721 if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
Chris Lattner80f43d32010-01-04 07:53:58 +0000722 if (Instruction *R = FoldOpIntoSelect(I, SI))
Chris Lattneracd1f0f2004-07-30 07:50:03 +0000723 return R;
Chris Lattner6b032052003-10-02 15:11:26 +0000724 }
725
Chris Lattner42790482007-12-20 01:56:58 +0000726 // add (select X 0 (sub n A)) A --> select X A n
Christopher Lamb30f017a2007-12-18 09:34:41 +0000727 {
728 SelectInst *SI = dyn_cast<SelectInst>(LHS);
Chris Lattner6046fb72008-11-16 04:46:19 +0000729 Value *A = RHS;
Christopher Lamb30f017a2007-12-18 09:34:41 +0000730 if (!SI) {
731 SI = dyn_cast<SelectInst>(RHS);
Chris Lattner6046fb72008-11-16 04:46:19 +0000732 A = LHS;
Christopher Lamb30f017a2007-12-18 09:34:41 +0000733 }
Chris Lattner42790482007-12-20 01:56:58 +0000734 if (SI && SI->hasOneUse()) {
Christopher Lamb30f017a2007-12-18 09:34:41 +0000735 Value *TV = SI->getTrueValue();
736 Value *FV = SI->getFalseValue();
Chris Lattner6046fb72008-11-16 04:46:19 +0000737 Value *N;
Christopher Lamb30f017a2007-12-18 09:34:41 +0000738
739 // Can we fold the add into the argument of the select?
740 // We check both true and false select arguments for a matching subtract.
Dan Gohman4ae51262009-08-12 16:23:25 +0000741 if (match(FV, m_Zero()) &&
742 match(TV, m_Sub(m_Value(N), m_Specific(A))))
Chris Lattner6046fb72008-11-16 04:46:19 +0000743 // Fold the add into the true select value.
Gabor Greif051a9502008-04-06 20:25:17 +0000744 return SelectInst::Create(SI->getCondition(), N, A);
Dan Gohman4ae51262009-08-12 16:23:25 +0000745 if (match(TV, m_Zero()) &&
746 match(FV, m_Sub(m_Value(N), m_Specific(A))))
Chris Lattner6046fb72008-11-16 04:46:19 +0000747 // Fold the add into the false select value.
Gabor Greif051a9502008-04-06 20:25:17 +0000748 return SelectInst::Create(SI->getCondition(), A, N);
Christopher Lamb30f017a2007-12-18 09:34:41 +0000749 }
750 }
Andrew Lenharth16d79552006-09-19 18:24:51 +0000751
Chris Lattner3d28b1b2008-05-20 05:46:13 +0000752 // Check for (add (sext x), y), see if we can merge this into an
753 // integer add followed by a sext.
754 if (SExtInst *LHSConv = dyn_cast<SExtInst>(LHS)) {
755 // (add (sext x), cst) --> (sext (add x, cst'))
756 if (ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS)) {
757 Constant *CI =
Owen Andersonbaf3c402009-07-29 18:55:55 +0000758 ConstantExpr::getTrunc(RHSC, LHSConv->getOperand(0)->getType());
Chris Lattner3d28b1b2008-05-20 05:46:13 +0000759 if (LHSConv->hasOneUse() &&
Owen Andersonbaf3c402009-07-29 18:55:55 +0000760 ConstantExpr::getSExt(CI, I.getType()) == RHSC &&
Chris Lattner3d28b1b2008-05-20 05:46:13 +0000761 WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
762 // Insert the new, smaller add.
Dan Gohmanfe359552009-10-26 22:14:22 +0000763 Value *NewAdd = Builder->CreateNSWAdd(LHSConv->getOperand(0),
764 CI, "addconv");
Chris Lattner3d28b1b2008-05-20 05:46:13 +0000765 return new SExtInst(NewAdd, I.getType());
766 }
767 }
768
769 // (add (sext x), (sext y)) --> (sext (add int x, y))
770 if (SExtInst *RHSConv = dyn_cast<SExtInst>(RHS)) {
771 // Only do this if x/y have the same type, if at last one of them has a
772 // single use (so we don't increase the number of sexts), and if the
773 // integer add will not overflow.
774 if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
775 (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
776 WillNotOverflowSignedAdd(LHSConv->getOperand(0),
777 RHSConv->getOperand(0))) {
778 // Insert the new integer add.
Dan Gohmanfe359552009-10-26 22:14:22 +0000779 Value *NewAdd = Builder->CreateNSWAdd(LHSConv->getOperand(0),
780 RHSConv->getOperand(0), "addconv");
Chris Lattner3d28b1b2008-05-20 05:46:13 +0000781 return new SExtInst(NewAdd, I.getType());
782 }
783 }
784 }
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000785
786 return Changed ? &I : 0;
787}
788
789Instruction *InstCombiner::visitFAdd(BinaryOperator &I) {
790 bool Changed = SimplifyCommutative(I);
791 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
792
793 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
794 // X + 0 --> X
795 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
Owen Anderson6f83c9c2009-07-27 20:59:43 +0000796 if (CFP->isExactlyValue(ConstantFP::getNegativeZero
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000797 (I.getType())->getValueAPF()))
798 return ReplaceInstUsesWith(I, LHS);
799 }
800
801 if (isa<PHINode>(LHS))
802 if (Instruction *NV = FoldOpIntoPhi(I))
803 return NV;
804 }
805
806 // -A + B --> B - A
807 // -A + -B --> -(A + B)
Dan Gohman186a6362009-08-12 16:04:34 +0000808 if (Value *LHSV = dyn_castFNegVal(LHS))
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000809 return BinaryOperator::CreateFSub(RHS, LHSV);
810
811 // A + -B --> A - B
812 if (!isa<Constant>(RHS))
Dan Gohman186a6362009-08-12 16:04:34 +0000813 if (Value *V = dyn_castFNegVal(RHS))
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000814 return BinaryOperator::CreateFSub(LHS, V);
815
816 // Check for X+0.0. Simplify it to X if we know X is not -0.0.
817 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS))
818 if (CFP->getValueAPF().isPosZero() && CannotBeNegativeZero(LHS))
819 return ReplaceInstUsesWith(I, LHS);
820
Chris Lattner3d28b1b2008-05-20 05:46:13 +0000821 // Check for (add double (sitofp x), y), see if we can merge this into an
822 // integer add followed by a promotion.
823 if (SIToFPInst *LHSConv = dyn_cast<SIToFPInst>(LHS)) {
824 // (add double (sitofp x), fpcst) --> (sitofp (add int x, intcst))
825 // ... if the constant fits in the integer value. This is useful for things
826 // like (double)(x & 1234) + 4.0 -> (double)((X & 1234)+4) which no longer
827 // requires a constant pool load, and generally allows the add to be better
828 // instcombined.
829 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS)) {
830 Constant *CI =
Owen Andersonbaf3c402009-07-29 18:55:55 +0000831 ConstantExpr::getFPToSI(CFP, LHSConv->getOperand(0)->getType());
Chris Lattner3d28b1b2008-05-20 05:46:13 +0000832 if (LHSConv->hasOneUse() &&
Owen Andersonbaf3c402009-07-29 18:55:55 +0000833 ConstantExpr::getSIToFP(CI, I.getType()) == CFP &&
Chris Lattner3d28b1b2008-05-20 05:46:13 +0000834 WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
835 // Insert the new integer add.
Dan Gohmanfe359552009-10-26 22:14:22 +0000836 Value *NewAdd = Builder->CreateNSWAdd(LHSConv->getOperand(0),
837 CI, "addconv");
Chris Lattner3d28b1b2008-05-20 05:46:13 +0000838 return new SIToFPInst(NewAdd, I.getType());
839 }
840 }
841
842 // (add double (sitofp x), (sitofp y)) --> (sitofp (add int x, y))
843 if (SIToFPInst *RHSConv = dyn_cast<SIToFPInst>(RHS)) {
844 // Only do this if x/y have the same type, if at last one of them has a
845 // single use (so we don't increase the number of int->fp conversions),
846 // and if the integer add will not overflow.
847 if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
848 (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
849 WillNotOverflowSignedAdd(LHSConv->getOperand(0),
850 RHSConv->getOperand(0))) {
851 // Insert the new integer add.
Dan Gohmanfe359552009-10-26 22:14:22 +0000852 Value *NewAdd = Builder->CreateNSWAdd(LHSConv->getOperand(0),
Chris Lattner092543c2009-11-04 08:05:20 +0000853 RHSConv->getOperand(0),"addconv");
Chris Lattner3d28b1b2008-05-20 05:46:13 +0000854 return new SIToFPInst(NewAdd, I.getType());
855 }
856 }
857 }
858
Chris Lattner7e708292002-06-25 16:13:24 +0000859 return Changed ? &I : 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000860}
861
Chris Lattner092543c2009-11-04 08:05:20 +0000862
863/// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
864/// code necessary to compute the offset from the base pointer (without adding
865/// in the base pointer). Return the result as a signed integer of intptr size.
Chris Lattner02446fc2010-01-04 07:37:31 +0000866Value *InstCombiner::EmitGEPOffset(User *GEP) {
867 TargetData &TD = *getTargetData();
Chris Lattner092543c2009-11-04 08:05:20 +0000868 gep_type_iterator GTI = gep_type_begin(GEP);
869 const Type *IntPtrTy = TD.getIntPtrType(GEP->getContext());
870 Value *Result = Constant::getNullValue(IntPtrTy);
871
872 // Build a mask for high order bits.
873 unsigned IntPtrWidth = TD.getPointerSizeInBits();
874 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
875
876 for (User::op_iterator i = GEP->op_begin() + 1, e = GEP->op_end(); i != e;
877 ++i, ++GTI) {
878 Value *Op = *i;
879 uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType()) & PtrSizeMask;
880 if (ConstantInt *OpC = dyn_cast<ConstantInt>(Op)) {
881 if (OpC->isZero()) continue;
882
883 // Handle a struct index, which adds its field offset to the pointer.
884 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
885 Size = TD.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
886
Chris Lattner02446fc2010-01-04 07:37:31 +0000887 Result = Builder->CreateAdd(Result,
888 ConstantInt::get(IntPtrTy, Size),
889 GEP->getName()+".offs");
Chris Lattner092543c2009-11-04 08:05:20 +0000890 continue;
891 }
892
893 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
894 Constant *OC =
895 ConstantExpr::getIntegerCast(OpC, IntPtrTy, true /*SExt*/);
896 Scale = ConstantExpr::getMul(OC, Scale);
897 // Emit an add instruction.
Chris Lattner02446fc2010-01-04 07:37:31 +0000898 Result = Builder->CreateAdd(Result, Scale, GEP->getName()+".offs");
Chris Lattner092543c2009-11-04 08:05:20 +0000899 continue;
900 }
901 // Convert to correct type.
902 if (Op->getType() != IntPtrTy)
Chris Lattner02446fc2010-01-04 07:37:31 +0000903 Op = Builder->CreateIntCast(Op, IntPtrTy, true, Op->getName()+".c");
Chris Lattner092543c2009-11-04 08:05:20 +0000904 if (Size != 1) {
905 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
906 // We'll let instcombine(mul) convert this to a shl if possible.
Chris Lattner02446fc2010-01-04 07:37:31 +0000907 Op = Builder->CreateMul(Op, Scale, GEP->getName()+".idx");
Chris Lattner092543c2009-11-04 08:05:20 +0000908 }
909
910 // Emit an add instruction.
Chris Lattner02446fc2010-01-04 07:37:31 +0000911 Result = Builder->CreateAdd(Op, Result, GEP->getName()+".offs");
Chris Lattner092543c2009-11-04 08:05:20 +0000912 }
913 return Result;
914}
915
916
Chris Lattner092543c2009-11-04 08:05:20 +0000917
918
919/// Optimize pointer differences into the same array into a size. Consider:
920/// &A[10] - &A[0]: we should compile this to "10". LHS/RHS are the pointer
921/// operands to the ptrtoint instructions for the LHS/RHS of the subtract.
922///
923Value *InstCombiner::OptimizePointerDifference(Value *LHS, Value *RHS,
924 const Type *Ty) {
925 assert(TD && "Must have target data info for this");
926
927 // If LHS is a gep based on RHS or RHS is a gep based on LHS, we can optimize
928 // this.
Chris Lattner0cb1e9e2010-01-04 18:48:26 +0000929 bool Swapped = false;
Chris Lattner85c1c962010-01-01 22:42:29 +0000930 GetElementPtrInst *GEP = 0;
931 ConstantExpr *CstGEP = 0;
Chris Lattner092543c2009-11-04 08:05:20 +0000932
Chris Lattner85c1c962010-01-01 22:42:29 +0000933 // TODO: Could also optimize &A[i] - &A[j] -> "i-j", and "&A.foo[i] - &A.foo".
934 // For now we require one side to be the base pointer "A" or a constant
935 // expression derived from it.
936 if (GetElementPtrInst *LHSGEP = dyn_cast<GetElementPtrInst>(LHS)) {
937 // (gep X, ...) - X
938 if (LHSGEP->getOperand(0) == RHS) {
939 GEP = LHSGEP;
940 Swapped = false;
941 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(RHS)) {
942 // (gep X, ...) - (ce_gep X, ...)
943 if (CE->getOpcode() == Instruction::GetElementPtr &&
944 LHSGEP->getOperand(0) == CE->getOperand(0)) {
945 CstGEP = CE;
946 GEP = LHSGEP;
947 Swapped = false;
948 }
949 }
950 }
951
952 if (GetElementPtrInst *RHSGEP = dyn_cast<GetElementPtrInst>(RHS)) {
953 // X - (gep X, ...)
954 if (RHSGEP->getOperand(0) == LHS) {
955 GEP = RHSGEP;
956 Swapped = true;
957 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(LHS)) {
958 // (ce_gep X, ...) - (gep X, ...)
959 if (CE->getOpcode() == Instruction::GetElementPtr &&
960 RHSGEP->getOperand(0) == CE->getOperand(0)) {
961 CstGEP = CE;
962 GEP = RHSGEP;
963 Swapped = true;
964 }
965 }
966 }
967
968 if (GEP == 0)
Chris Lattner092543c2009-11-04 08:05:20 +0000969 return 0;
970
Chris Lattner092543c2009-11-04 08:05:20 +0000971 // Emit the offset of the GEP and an intptr_t.
Chris Lattner02446fc2010-01-04 07:37:31 +0000972 Value *Result = EmitGEPOffset(GEP);
Chris Lattner85c1c962010-01-01 22:42:29 +0000973
974 // If we had a constant expression GEP on the other side offsetting the
975 // pointer, subtract it from the offset we have.
976 if (CstGEP) {
Chris Lattner02446fc2010-01-04 07:37:31 +0000977 Value *CstOffset = EmitGEPOffset(CstGEP);
Chris Lattner85c1c962010-01-01 22:42:29 +0000978 Result = Builder->CreateSub(Result, CstOffset);
979 }
980
Chris Lattner092543c2009-11-04 08:05:20 +0000981
982 // If we have p - gep(p, ...) then we have to negate the result.
983 if (Swapped)
984 Result = Builder->CreateNeg(Result, "diff.neg");
985
986 return Builder->CreateIntCast(Result, Ty, true);
987}
988
989
Chris Lattner7e708292002-06-25 16:13:24 +0000990Instruction *InstCombiner::visitSub(BinaryOperator &I) {
Chris Lattner7e708292002-06-25 16:13:24 +0000991 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +0000992
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000993 if (Op0 == Op1) // sub X, X -> 0
Owen Andersona7235ea2009-07-31 20:28:14 +0000994 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000995
Chris Lattner3bf68152009-12-21 04:04:05 +0000996 // If this is a 'B = x-(-A)', change to B = x+A. This preserves NSW/NUW.
997 if (Value *V = dyn_castNegVal(Op1)) {
998 BinaryOperator *Res = BinaryOperator::CreateAdd(Op0, V);
999 Res->setHasNoSignedWrap(I.hasNoSignedWrap());
1000 Res->setHasNoUnsignedWrap(I.hasNoUnsignedWrap());
1001 return Res;
1002 }
Chris Lattnerb35dde12002-05-06 16:49:18 +00001003
Chris Lattnere87597f2004-10-16 18:11:37 +00001004 if (isa<UndefValue>(Op0))
1005 return ReplaceInstUsesWith(I, Op0); // undef - X -> undef
1006 if (isa<UndefValue>(Op1))
1007 return ReplaceInstUsesWith(I, Op1); // X - undef -> undef
Chris Lattner4de84762010-01-04 07:02:48 +00001008 if (I.getType() == Type::getInt1Ty(I.getContext()))
Chris Lattner092543c2009-11-04 08:05:20 +00001009 return BinaryOperator::CreateXor(Op0, Op1);
1010
Chris Lattnerd65460f2003-11-05 01:06:05 +00001011 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
Chris Lattner092543c2009-11-04 08:05:20 +00001012 // Replace (-1 - A) with (~A).
Chris Lattnera2881962003-02-18 19:28:33 +00001013 if (C->isAllOnesValue())
Dan Gohman4ae51262009-08-12 16:23:25 +00001014 return BinaryOperator::CreateNot(Op1);
Chris Lattner40371712002-05-09 01:29:19 +00001015
Chris Lattnerd65460f2003-11-05 01:06:05 +00001016 // C - ~X == X + (1+C)
Reid Spencer4b828e62005-06-18 17:37:34 +00001017 Value *X = 0;
Dan Gohman4ae51262009-08-12 16:23:25 +00001018 if (match(Op1, m_Not(m_Value(X))))
Dan Gohman186a6362009-08-12 16:04:34 +00001019 return BinaryOperator::CreateAdd(X, AddOne(C));
Reid Spencer7177c3a2007-03-25 05:33:51 +00001020
Chris Lattner76b7a062007-01-15 07:02:54 +00001021 // -(X >>u 31) -> (X >>s 31)
1022 // -(X >>s 31) -> (X >>u 31)
Zhou Sheng302748d2007-03-30 17:20:39 +00001023 if (C->isZero()) {
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00001024 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op1)) {
Reid Spencer3822ff52006-11-08 06:47:33 +00001025 if (SI->getOpcode() == Instruction::LShr) {
Reid Spencerb83eb642006-10-20 07:07:24 +00001026 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
Chris Lattner9c290672004-03-12 23:53:13 +00001027 // Check to see if we are shifting out everything but the sign bit.
Zhou Sheng302748d2007-03-30 17:20:39 +00001028 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
Reid Spencerb83eb642006-10-20 07:07:24 +00001029 SI->getType()->getPrimitiveSizeInBits()-1) {
Reid Spencer3822ff52006-11-08 06:47:33 +00001030 // Ok, the transformation is safe. Insert AShr.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001031 return BinaryOperator::Create(Instruction::AShr,
Reid Spencer832254e2007-02-02 02:16:23 +00001032 SI->getOperand(0), CU, SI->getName());
Chris Lattner9c290672004-03-12 23:53:13 +00001033 }
1034 }
Chris Lattner092543c2009-11-04 08:05:20 +00001035 } else if (SI->getOpcode() == Instruction::AShr) {
Reid Spencer3822ff52006-11-08 06:47:33 +00001036 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
1037 // Check to see if we are shifting out everything but the sign bit.
Zhou Sheng302748d2007-03-30 17:20:39 +00001038 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
Reid Spencer3822ff52006-11-08 06:47:33 +00001039 SI->getType()->getPrimitiveSizeInBits()-1) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00001040 // Ok, the transformation is safe. Insert LShr.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001041 return BinaryOperator::CreateLShr(
Reid Spencer832254e2007-02-02 02:16:23 +00001042 SI->getOperand(0), CU, SI->getName());
Reid Spencer3822ff52006-11-08 06:47:33 +00001043 }
1044 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00001045 }
1046 }
Chris Lattnerbfe492b2004-03-13 00:11:49 +00001047 }
Chris Lattner2eefe512004-04-09 19:05:30 +00001048
1049 // Try to fold constant sub into select arguments.
1050 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner80f43d32010-01-04 07:53:58 +00001051 if (Instruction *R = FoldOpIntoSelect(I, SI))
Chris Lattner2eefe512004-04-09 19:05:30 +00001052 return R;
Eli Friedman709b33d2009-07-13 22:27:52 +00001053
1054 // C - zext(bool) -> bool ? C - 1 : C
1055 if (ZExtInst *ZI = dyn_cast<ZExtInst>(Op1))
Chris Lattner4de84762010-01-04 07:02:48 +00001056 if (ZI->getSrcTy() == Type::getInt1Ty(I.getContext()))
Dan Gohman186a6362009-08-12 16:04:34 +00001057 return SelectInst::Create(ZI->getOperand(0), SubOne(C), C);
Chris Lattnerd65460f2003-11-05 01:06:05 +00001058 }
1059
Chris Lattner43d84d62005-04-07 16:15:25 +00001060 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001061 if (Op1I->getOpcode() == Instruction::Add) {
Chris Lattner08954a22005-04-07 16:28:01 +00001062 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
Dan Gohman4ae51262009-08-12 16:23:25 +00001063 return BinaryOperator::CreateNeg(Op1I->getOperand(1),
Owen Anderson0a5372e2009-07-13 04:09:18 +00001064 I.getName());
Chris Lattner08954a22005-04-07 16:28:01 +00001065 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
Dan Gohman4ae51262009-08-12 16:23:25 +00001066 return BinaryOperator::CreateNeg(Op1I->getOperand(0),
Owen Anderson0a5372e2009-07-13 04:09:18 +00001067 I.getName());
Chris Lattner08954a22005-04-07 16:28:01 +00001068 else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
1069 if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
1070 // C1-(X+C2) --> (C1-C2)-X
Owen Andersond672ecb2009-07-03 00:17:18 +00001071 return BinaryOperator::CreateSub(
Owen Andersonbaf3c402009-07-29 18:55:55 +00001072 ConstantExpr::getSub(CI1, CI2), Op1I->getOperand(0));
Chris Lattner08954a22005-04-07 16:28:01 +00001073 }
Chris Lattner43d84d62005-04-07 16:15:25 +00001074 }
1075
Chris Lattnerfd059242003-10-15 16:48:29 +00001076 if (Op1I->hasOneUse()) {
Chris Lattnera2881962003-02-18 19:28:33 +00001077 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
1078 // is not used by anyone else...
1079 //
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001080 if (Op1I->getOpcode() == Instruction::Sub) {
Chris Lattnera2881962003-02-18 19:28:33 +00001081 // Swap the two operands of the subexpr...
1082 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
1083 Op1I->setOperand(0, IIOp1);
1084 Op1I->setOperand(1, IIOp0);
Misha Brukmanfd939082005-04-21 23:48:37 +00001085
Chris Lattnera2881962003-02-18 19:28:33 +00001086 // Create the new top level add instruction...
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001087 return BinaryOperator::CreateAdd(Op0, Op1);
Chris Lattnera2881962003-02-18 19:28:33 +00001088 }
1089
1090 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
1091 //
1092 if (Op1I->getOpcode() == Instruction::And &&
1093 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
1094 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
1095
Chris Lattner74381062009-08-30 07:44:24 +00001096 Value *NewNot = Builder->CreateNot(OtherOp, "B.not");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001097 return BinaryOperator::CreateAnd(Op0, NewNot);
Chris Lattnera2881962003-02-18 19:28:33 +00001098 }
Chris Lattnerad3448c2003-02-18 19:57:07 +00001099
Reid Spencerac5209e2006-10-16 23:08:08 +00001100 // 0 - (X sdiv C) -> (X sdiv -C)
Reid Spencer1628cec2006-10-26 06:15:43 +00001101 if (Op1I->getOpcode() == Instruction::SDiv)
Reid Spencerb83eb642006-10-20 07:07:24 +00001102 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
Zhou Sheng843f07672007-04-19 05:39:12 +00001103 if (CSI->isZero())
Chris Lattner91ccc152004-10-06 15:08:25 +00001104 if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001105 return BinaryOperator::CreateSDiv(Op1I->getOperand(0),
Owen Andersonbaf3c402009-07-29 18:55:55 +00001106 ConstantExpr::getNeg(DivRHS));
Chris Lattner91ccc152004-10-06 15:08:25 +00001107
Chris Lattnerad3448c2003-02-18 19:57:07 +00001108 // X - X*C --> X * (1-C)
Reid Spencer4b828e62005-06-18 17:37:34 +00001109 ConstantInt *C2 = 0;
Dan Gohman186a6362009-08-12 16:04:34 +00001110 if (dyn_castFoldableMul(Op1I, C2) == Op0) {
Owen Andersond672ecb2009-07-03 00:17:18 +00001111 Constant *CP1 =
Owen Andersonbaf3c402009-07-29 18:55:55 +00001112 ConstantExpr::getSub(ConstantInt::get(I.getType(), 1),
Dan Gohman6de29f82009-06-15 22:12:54 +00001113 C2);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001114 return BinaryOperator::CreateMul(Op0, CP1);
Chris Lattnerad3448c2003-02-18 19:57:07 +00001115 }
Chris Lattner40371712002-05-09 01:29:19 +00001116 }
Chris Lattner43d84d62005-04-07 16:15:25 +00001117 }
Chris Lattnera2881962003-02-18 19:28:33 +00001118
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001119 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
1120 if (Op0I->getOpcode() == Instruction::Add) {
1121 if (Op0I->getOperand(0) == Op1) // (Y+X)-Y == X
1122 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
1123 else if (Op0I->getOperand(1) == Op1) // (X+Y)-Y == X
1124 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
1125 } else if (Op0I->getOpcode() == Instruction::Sub) {
1126 if (Op0I->getOperand(0) == Op1) // (X-Y)-X == -Y
Dan Gohman4ae51262009-08-12 16:23:25 +00001127 return BinaryOperator::CreateNeg(Op0I->getOperand(1),
Owen Anderson0a5372e2009-07-13 04:09:18 +00001128 I.getName());
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00001129 }
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001130 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001131
Chris Lattner50af16a2004-11-13 19:50:12 +00001132 ConstantInt *C1;
Dan Gohman186a6362009-08-12 16:04:34 +00001133 if (Value *X = dyn_castFoldableMul(Op0, C1)) {
Reid Spencer7177c3a2007-03-25 05:33:51 +00001134 if (X == Op1) // X*C - X --> X * (C-1)
Dan Gohman186a6362009-08-12 16:04:34 +00001135 return BinaryOperator::CreateMul(Op1, SubOne(C1));
Chris Lattnerad3448c2003-02-18 19:57:07 +00001136
Chris Lattner50af16a2004-11-13 19:50:12 +00001137 ConstantInt *C2; // X*C1 - X*C2 -> X * (C1-C2)
Dan Gohman186a6362009-08-12 16:04:34 +00001138 if (X == dyn_castFoldableMul(Op1, C2))
Owen Andersonbaf3c402009-07-29 18:55:55 +00001139 return BinaryOperator::CreateMul(X, ConstantExpr::getSub(C1, C2));
Chris Lattner50af16a2004-11-13 19:50:12 +00001140 }
Chris Lattner092543c2009-11-04 08:05:20 +00001141
1142 // Optimize pointer differences into the same array into a size. Consider:
1143 // &A[10] - &A[0]: we should compile this to "10".
1144 if (TD) {
Chris Lattner33767182010-01-01 22:12:03 +00001145 Value *LHSOp, *RHSOp;
Chris Lattnerf2ebc682010-01-01 22:29:12 +00001146 if (match(Op0, m_PtrToInt(m_Value(LHSOp))) &&
1147 match(Op1, m_PtrToInt(m_Value(RHSOp))))
Chris Lattner33767182010-01-01 22:12:03 +00001148 if (Value *Res = OptimizePointerDifference(LHSOp, RHSOp, I.getType()))
1149 return ReplaceInstUsesWith(I, Res);
Chris Lattner092543c2009-11-04 08:05:20 +00001150
1151 // trunc(p)-trunc(q) -> trunc(p-q)
Chris Lattnerf2ebc682010-01-01 22:29:12 +00001152 if (match(Op0, m_Trunc(m_PtrToInt(m_Value(LHSOp)))) &&
1153 match(Op1, m_Trunc(m_PtrToInt(m_Value(RHSOp)))))
1154 if (Value *Res = OptimizePointerDifference(LHSOp, RHSOp, I.getType()))
1155 return ReplaceInstUsesWith(I, Res);
Chris Lattner092543c2009-11-04 08:05:20 +00001156 }
1157
Chris Lattner3f5b8772002-05-06 16:14:14 +00001158 return 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00001159}
1160
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001161Instruction *InstCombiner::visitFSub(BinaryOperator &I) {
1162 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1163
1164 // If this is a 'B = x-(-A)', change to B = x+A...
Dan Gohman186a6362009-08-12 16:04:34 +00001165 if (Value *V = dyn_castFNegVal(Op1))
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001166 return BinaryOperator::CreateFAdd(Op0, V);
1167
1168 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
1169 if (Op1I->getOpcode() == Instruction::FAdd) {
1170 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
Dan Gohman4ae51262009-08-12 16:23:25 +00001171 return BinaryOperator::CreateFNeg(Op1I->getOperand(1),
Owen Anderson0a5372e2009-07-13 04:09:18 +00001172 I.getName());
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001173 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
Dan Gohman4ae51262009-08-12 16:23:25 +00001174 return BinaryOperator::CreateFNeg(Op1I->getOperand(0),
Owen Anderson0a5372e2009-07-13 04:09:18 +00001175 I.getName());
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001176 }
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001177 }
1178
1179 return 0;
1180}
1181
Reid Spencere4d87aa2006-12-23 06:05:41 +00001182/// getICmpCode - Encode a icmp predicate into a three bit mask. These bits
Chris Lattneraa9c1f12003-08-13 20:16:26 +00001183/// are carefully arranged to allow folding of expressions such as:
1184///
1185/// (A < B) | (A > B) --> (A != B)
1186///
Reid Spencere4d87aa2006-12-23 06:05:41 +00001187/// Note that this is only valid if the first and second predicates have the
1188/// same sign. Is illegal to do: (A u< B) | (A s> B)
Chris Lattneraa9c1f12003-08-13 20:16:26 +00001189///
Reid Spencere4d87aa2006-12-23 06:05:41 +00001190/// Three bits are used to represent the condition, as follows:
1191/// 0 A > B
1192/// 1 A == B
1193/// 2 A < B
1194///
1195/// <=> Value Definition
1196/// 000 0 Always false
1197/// 001 1 A > B
1198/// 010 2 A == B
1199/// 011 3 A >= B
1200/// 100 4 A < B
1201/// 101 5 A != B
1202/// 110 6 A <= B
1203/// 111 7 Always true
1204///
1205static unsigned getICmpCode(const ICmpInst *ICI) {
1206 switch (ICI->getPredicate()) {
Chris Lattneraa9c1f12003-08-13 20:16:26 +00001207 // False -> 0
Reid Spencere4d87aa2006-12-23 06:05:41 +00001208 case ICmpInst::ICMP_UGT: return 1; // 001
1209 case ICmpInst::ICMP_SGT: return 1; // 001
1210 case ICmpInst::ICMP_EQ: return 2; // 010
1211 case ICmpInst::ICMP_UGE: return 3; // 011
1212 case ICmpInst::ICMP_SGE: return 3; // 011
1213 case ICmpInst::ICMP_ULT: return 4; // 100
1214 case ICmpInst::ICMP_SLT: return 4; // 100
1215 case ICmpInst::ICMP_NE: return 5; // 101
1216 case ICmpInst::ICMP_ULE: return 6; // 110
1217 case ICmpInst::ICMP_SLE: return 6; // 110
Chris Lattneraa9c1f12003-08-13 20:16:26 +00001218 // True -> 7
1219 default:
Torok Edwinc23197a2009-07-14 16:55:14 +00001220 llvm_unreachable("Invalid ICmp predicate!");
Chris Lattneraa9c1f12003-08-13 20:16:26 +00001221 return 0;
1222 }
1223}
1224
Evan Cheng8db90722008-10-14 17:15:11 +00001225/// getFCmpCode - Similar to getICmpCode but for FCmpInst. This encodes a fcmp
1226/// predicate into a three bit mask. It also returns whether it is an ordered
1227/// predicate by reference.
1228static unsigned getFCmpCode(FCmpInst::Predicate CC, bool &isOrdered) {
1229 isOrdered = false;
1230 switch (CC) {
1231 case FCmpInst::FCMP_ORD: isOrdered = true; return 0; // 000
1232 case FCmpInst::FCMP_UNO: return 0; // 000
Evan Cheng4990b252008-10-14 18:13:38 +00001233 case FCmpInst::FCMP_OGT: isOrdered = true; return 1; // 001
1234 case FCmpInst::FCMP_UGT: return 1; // 001
1235 case FCmpInst::FCMP_OEQ: isOrdered = true; return 2; // 010
1236 case FCmpInst::FCMP_UEQ: return 2; // 010
Evan Cheng8db90722008-10-14 17:15:11 +00001237 case FCmpInst::FCMP_OGE: isOrdered = true; return 3; // 011
1238 case FCmpInst::FCMP_UGE: return 3; // 011
1239 case FCmpInst::FCMP_OLT: isOrdered = true; return 4; // 100
1240 case FCmpInst::FCMP_ULT: return 4; // 100
Evan Cheng4990b252008-10-14 18:13:38 +00001241 case FCmpInst::FCMP_ONE: isOrdered = true; return 5; // 101
1242 case FCmpInst::FCMP_UNE: return 5; // 101
Evan Cheng8db90722008-10-14 17:15:11 +00001243 case FCmpInst::FCMP_OLE: isOrdered = true; return 6; // 110
1244 case FCmpInst::FCMP_ULE: return 6; // 110
Evan Cheng40300622008-10-14 18:44:08 +00001245 // True -> 7
Evan Cheng8db90722008-10-14 17:15:11 +00001246 default:
1247 // Not expecting FCMP_FALSE and FCMP_TRUE;
Torok Edwinc23197a2009-07-14 16:55:14 +00001248 llvm_unreachable("Unexpected FCmp predicate!");
Evan Cheng8db90722008-10-14 17:15:11 +00001249 return 0;
1250 }
1251}
1252
Reid Spencere4d87aa2006-12-23 06:05:41 +00001253/// getICmpValue - This is the complement of getICmpCode, which turns an
1254/// opcode and two operands into either a constant true or false, or a brand
Dan Gohman5d066ff2007-09-17 17:31:57 +00001255/// new ICmp instruction. The sign is passed in to determine which kind
Evan Cheng8db90722008-10-14 17:15:11 +00001256/// of predicate to use in the new icmp instruction.
Chris Lattnera317e042010-01-05 06:59:49 +00001257static Value *getICmpValue(bool Sign, unsigned Code, Value *LHS, Value *RHS) {
1258 switch (Code) {
1259 default: assert(0 && "Illegal ICmp code!");
1260 case 0:
1261 return ConstantInt::getFalse(LHS->getContext());
1262 case 1:
1263 if (Sign)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00001264 return new ICmpInst(ICmpInst::ICMP_SGT, LHS, RHS);
Chris Lattnera317e042010-01-05 06:59:49 +00001265 return new ICmpInst(ICmpInst::ICMP_UGT, LHS, RHS);
1266 case 2:
1267 return new ICmpInst(ICmpInst::ICMP_EQ, LHS, RHS);
1268 case 3:
1269 if (Sign)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00001270 return new ICmpInst(ICmpInst::ICMP_SGE, LHS, RHS);
Chris Lattnera317e042010-01-05 06:59:49 +00001271 return new ICmpInst(ICmpInst::ICMP_UGE, LHS, RHS);
1272 case 4:
1273 if (Sign)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00001274 return new ICmpInst(ICmpInst::ICMP_SLT, LHS, RHS);
Chris Lattnera317e042010-01-05 06:59:49 +00001275 return new ICmpInst(ICmpInst::ICMP_ULT, LHS, RHS);
1276 case 5:
1277 return new ICmpInst(ICmpInst::ICMP_NE, LHS, RHS);
1278 case 6:
1279 if (Sign)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00001280 return new ICmpInst(ICmpInst::ICMP_SLE, LHS, RHS);
Chris Lattnera317e042010-01-05 06:59:49 +00001281 return new ICmpInst(ICmpInst::ICMP_ULE, LHS, RHS);
1282 case 7:
1283 return ConstantInt::getTrue(LHS->getContext());
Chris Lattneraa9c1f12003-08-13 20:16:26 +00001284 }
1285}
1286
Evan Cheng8db90722008-10-14 17:15:11 +00001287/// getFCmpValue - This is the complement of getFCmpCode, which turns an
1288/// opcode and two operands into either a FCmp instruction. isordered is passed
1289/// in to determine which kind of predicate to use in the new fcmp instruction.
1290static Value *getFCmpValue(bool isordered, unsigned code,
Chris Lattner4de84762010-01-04 07:02:48 +00001291 Value *LHS, Value *RHS) {
Evan Cheng8db90722008-10-14 17:15:11 +00001292 switch (code) {
Torok Edwinc23197a2009-07-14 16:55:14 +00001293 default: llvm_unreachable("Illegal FCmp code!");
Evan Cheng8db90722008-10-14 17:15:11 +00001294 case 0:
1295 if (isordered)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00001296 return new FCmpInst(FCmpInst::FCMP_ORD, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00001297 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00001298 return new FCmpInst(FCmpInst::FCMP_UNO, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00001299 case 1:
1300 if (isordered)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00001301 return new FCmpInst(FCmpInst::FCMP_OGT, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00001302 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00001303 return new FCmpInst(FCmpInst::FCMP_UGT, LHS, RHS);
Evan Cheng4990b252008-10-14 18:13:38 +00001304 case 2:
1305 if (isordered)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00001306 return new FCmpInst(FCmpInst::FCMP_OEQ, LHS, RHS);
Evan Cheng4990b252008-10-14 18:13:38 +00001307 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00001308 return new FCmpInst(FCmpInst::FCMP_UEQ, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00001309 case 3:
1310 if (isordered)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00001311 return new FCmpInst(FCmpInst::FCMP_OGE, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00001312 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00001313 return new FCmpInst(FCmpInst::FCMP_UGE, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00001314 case 4:
1315 if (isordered)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00001316 return new FCmpInst(FCmpInst::FCMP_OLT, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00001317 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00001318 return new FCmpInst(FCmpInst::FCMP_ULT, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00001319 case 5:
1320 if (isordered)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00001321 return new FCmpInst(FCmpInst::FCMP_ONE, LHS, RHS);
Evan Cheng4990b252008-10-14 18:13:38 +00001322 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00001323 return new FCmpInst(FCmpInst::FCMP_UNE, LHS, RHS);
Evan Cheng4990b252008-10-14 18:13:38 +00001324 case 6:
1325 if (isordered)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00001326 return new FCmpInst(FCmpInst::FCMP_OLE, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00001327 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00001328 return new FCmpInst(FCmpInst::FCMP_ULE, LHS, RHS);
Chris Lattner4de84762010-01-04 07:02:48 +00001329 case 7: return ConstantInt::getTrue(LHS->getContext());
Evan Cheng8db90722008-10-14 17:15:11 +00001330 }
1331}
1332
Chris Lattnerb9553d62008-11-16 04:55:20 +00001333/// PredicatesFoldable - Return true if both predicates match sign or if at
1334/// least one of them is an equality comparison (which is signless).
Reid Spencere4d87aa2006-12-23 06:05:41 +00001335static bool PredicatesFoldable(ICmpInst::Predicate p1, ICmpInst::Predicate p2) {
Nick Lewycky4a134af2009-10-25 05:20:17 +00001336 return (CmpInst::isSigned(p1) == CmpInst::isSigned(p2)) ||
1337 (CmpInst::isSigned(p1) && ICmpInst::isEquality(p2)) ||
1338 (CmpInst::isSigned(p2) && ICmpInst::isEquality(p1));
Reid Spencere4d87aa2006-12-23 06:05:41 +00001339}
1340
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00001341// OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
1342// the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
Reid Spencer832254e2007-02-02 02:16:23 +00001343// guaranteed to be a binary operator.
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00001344Instruction *InstCombiner::OptAndOp(Instruction *Op,
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00001345 ConstantInt *OpRHS,
1346 ConstantInt *AndRHS,
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00001347 BinaryOperator &TheAnd) {
1348 Value *X = Op->getOperand(0);
Chris Lattner76f7fe22004-01-12 19:47:05 +00001349 Constant *Together = 0;
Reid Spencer832254e2007-02-02 02:16:23 +00001350 if (!Op->isShift())
Owen Andersonbaf3c402009-07-29 18:55:55 +00001351 Together = ConstantExpr::getAnd(AndRHS, OpRHS);
Chris Lattner7c4049c2004-01-12 19:35:11 +00001352
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00001353 switch (Op->getOpcode()) {
1354 case Instruction::Xor:
Chris Lattner6e7ba452005-01-01 16:22:27 +00001355 if (Op->hasOneUse()) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00001356 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
Chris Lattner74381062009-08-30 07:44:24 +00001357 Value *And = Builder->CreateAnd(X, AndRHS);
Chris Lattner6934a042007-02-11 01:23:03 +00001358 And->takeName(Op);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001359 return BinaryOperator::CreateXor(And, Together);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00001360 }
1361 break;
1362 case Instruction::Or:
Chris Lattner6e7ba452005-01-01 16:22:27 +00001363 if (Together == AndRHS) // (X | C) & C --> C
1364 return ReplaceInstUsesWith(TheAnd, AndRHS);
Misha Brukmanfd939082005-04-21 23:48:37 +00001365
Chris Lattner6e7ba452005-01-01 16:22:27 +00001366 if (Op->hasOneUse() && Together != OpRHS) {
1367 // (X | C1) & C2 --> (X | (C1&C2)) & C2
Chris Lattner74381062009-08-30 07:44:24 +00001368 Value *Or = Builder->CreateOr(X, Together);
Chris Lattner6934a042007-02-11 01:23:03 +00001369 Or->takeName(Op);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001370 return BinaryOperator::CreateAnd(Or, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00001371 }
1372 break;
1373 case Instruction::Add:
Chris Lattnerfd059242003-10-15 16:48:29 +00001374 if (Op->hasOneUse()) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00001375 // Adding a one to a single bit bit-field should be turned into an XOR
1376 // of the bit. First thing to check is to see if this AND is with a
1377 // single bit constant.
Chris Lattnerc6334b92010-01-05 06:03:12 +00001378 const APInt &AndRHSV = cast<ConstantInt>(AndRHS)->getValue();
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00001379
Chris Lattnerc6334b92010-01-05 06:03:12 +00001380 // If there is only one bit set.
1381 if (AndRHSV.isPowerOf2()) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00001382 // Ok, at this point, we know that we are masking the result of the
1383 // ADD down to exactly one bit. If the constant we are adding has
1384 // no bits set below this bit, then we can eliminate the ADD.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00001385 const APInt& AddRHS = cast<ConstantInt>(OpRHS)->getValue();
Misha Brukmanfd939082005-04-21 23:48:37 +00001386
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00001387 // Check to see if any bits below the one bit set in AndRHSV are set.
1388 if ((AddRHS & (AndRHSV-1)) == 0) {
1389 // If not, the only thing that can effect the output of the AND is
1390 // the bit specified by AndRHSV. If that bit is set, the effect of
1391 // the XOR is to toggle the bit. If it is clear, then the ADD has
1392 // no effect.
1393 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
1394 TheAnd.setOperand(0, X);
1395 return &TheAnd;
1396 } else {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00001397 // Pull the XOR out of the AND.
Chris Lattner74381062009-08-30 07:44:24 +00001398 Value *NewAnd = Builder->CreateAnd(X, AndRHS);
Chris Lattner6934a042007-02-11 01:23:03 +00001399 NewAnd->takeName(Op);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001400 return BinaryOperator::CreateXor(NewAnd, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00001401 }
1402 }
1403 }
1404 }
1405 break;
Chris Lattner62a355c2003-09-19 19:05:02 +00001406
1407 case Instruction::Shl: {
1408 // We know that the AND will not produce any of the bits shifted in, so if
1409 // the anded constant includes them, clear them now!
1410 //
Zhou Sheng290bec52007-03-29 08:15:12 +00001411 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00001412 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +00001413 APInt ShlMask(APInt::getHighBitsSet(BitWidth, BitWidth-OpRHSVal));
Chris Lattner4de84762010-01-04 07:02:48 +00001414 ConstantInt *CI = ConstantInt::get(AndRHS->getContext(),
1415 AndRHS->getValue() & ShlMask);
Misha Brukmanfd939082005-04-21 23:48:37 +00001416
Zhou Sheng290bec52007-03-29 08:15:12 +00001417 if (CI->getValue() == ShlMask) {
1418 // Masking out bits that the shift already masks
Chris Lattner0c967662004-09-24 15:21:34 +00001419 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
1420 } else if (CI != AndRHS) { // Reducing bits set in and.
Chris Lattner62a355c2003-09-19 19:05:02 +00001421 TheAnd.setOperand(1, CI);
1422 return &TheAnd;
1423 }
1424 break;
Misha Brukmanfd939082005-04-21 23:48:37 +00001425 }
Chris Lattner4de84762010-01-04 07:02:48 +00001426 case Instruction::LShr: {
Chris Lattner62a355c2003-09-19 19:05:02 +00001427 // We know that the AND will not produce any of the bits shifted in, so if
1428 // the anded constant includes them, clear them now! This only applies to
1429 // unsigned shifts, because a signed shr may bring in set bits!
1430 //
Zhou Sheng290bec52007-03-29 08:15:12 +00001431 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00001432 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +00001433 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
Chris Lattner4de84762010-01-04 07:02:48 +00001434 ConstantInt *CI = ConstantInt::get(Op->getContext(),
1435 AndRHS->getValue() & ShrMask);
Chris Lattner0c967662004-09-24 15:21:34 +00001436
Zhou Sheng290bec52007-03-29 08:15:12 +00001437 if (CI->getValue() == ShrMask) {
1438 // Masking out bits that the shift already masks.
Reid Spencer3822ff52006-11-08 06:47:33 +00001439 return ReplaceInstUsesWith(TheAnd, Op);
1440 } else if (CI != AndRHS) {
1441 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
1442 return &TheAnd;
1443 }
1444 break;
1445 }
1446 case Instruction::AShr:
1447 // Signed shr.
1448 // See if this is shifting in some sign extension, then masking it out
1449 // with an and.
1450 if (Op->hasOneUse()) {
Zhou Sheng290bec52007-03-29 08:15:12 +00001451 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00001452 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +00001453 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
Chris Lattner4de84762010-01-04 07:02:48 +00001454 Constant *C = ConstantInt::get(Op->getContext(),
1455 AndRHS->getValue() & ShrMask);
Reid Spencer7eb76382006-12-13 17:19:09 +00001456 if (C == AndRHS) { // Masking out bits shifted in.
Reid Spencer17212df2006-12-12 09:18:51 +00001457 // (Val ashr C1) & C2 -> (Val lshr C1) & C2
Reid Spencer3822ff52006-11-08 06:47:33 +00001458 // Make the argument unsigned.
1459 Value *ShVal = Op->getOperand(0);
Chris Lattner74381062009-08-30 07:44:24 +00001460 ShVal = Builder->CreateLShr(ShVal, OpRHS, Op->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001461 return BinaryOperator::CreateAnd(ShVal, AndRHS, TheAnd.getName());
Chris Lattner0c967662004-09-24 15:21:34 +00001462 }
Chris Lattner62a355c2003-09-19 19:05:02 +00001463 }
1464 break;
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00001465 }
1466 return 0;
1467}
1468
Chris Lattner8b170942002-08-09 23:47:40 +00001469
Chris Lattnera96879a2004-09-29 17:40:11 +00001470/// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
1471/// true, otherwise (V < Lo || V >= Hi). In pratice, we emit the more efficient
Reid Spencere4d87aa2006-12-23 06:05:41 +00001472/// (V-Lo) <u Hi-Lo. This method expects that Lo <= Hi. isSigned indicates
1473/// whether to treat the V, Lo and HI as signed or not. IB is the location to
Chris Lattnera96879a2004-09-29 17:40:11 +00001474/// insert new instructions.
1475Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
Reid Spencere4d87aa2006-12-23 06:05:41 +00001476 bool isSigned, bool Inside,
1477 Instruction &IB) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00001478 assert(cast<ConstantInt>(ConstantExpr::getICmp((isSigned ?
Reid Spencer579dca12007-01-12 04:24:46 +00001479 ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
Chris Lattnera96879a2004-09-29 17:40:11 +00001480 "Lo is not <= Hi in range emission code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00001481
Chris Lattnera96879a2004-09-29 17:40:11 +00001482 if (Inside) {
1483 if (Lo == Hi) // Trivially false.
Dan Gohman1c8a23c2009-08-25 23:17:54 +00001484 return new ICmpInst(ICmpInst::ICMP_NE, V, V);
Misha Brukmanfd939082005-04-21 23:48:37 +00001485
Reid Spencere4d87aa2006-12-23 06:05:41 +00001486 // V >= Min && V < Hi --> V < Hi
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00001487 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
Reid Spencere4e40032007-03-21 23:19:50 +00001488 ICmpInst::Predicate pred = (isSigned ?
Reid Spencere4d87aa2006-12-23 06:05:41 +00001489 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00001490 return new ICmpInst(pred, V, Hi);
Reid Spencere4d87aa2006-12-23 06:05:41 +00001491 }
1492
1493 // Emit V-Lo <u Hi-Lo
Owen Andersonbaf3c402009-07-29 18:55:55 +00001494 Constant *NegLo = ConstantExpr::getNeg(Lo);
Chris Lattner74381062009-08-30 07:44:24 +00001495 Value *Add = Builder->CreateAdd(V, NegLo, V->getName()+".off");
Owen Andersonbaf3c402009-07-29 18:55:55 +00001496 Constant *UpperBound = ConstantExpr::getAdd(NegLo, Hi);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00001497 return new ICmpInst(ICmpInst::ICMP_ULT, Add, UpperBound);
Chris Lattnera96879a2004-09-29 17:40:11 +00001498 }
1499
1500 if (Lo == Hi) // Trivially true.
Dan Gohman1c8a23c2009-08-25 23:17:54 +00001501 return new ICmpInst(ICmpInst::ICMP_EQ, V, V);
Chris Lattnera96879a2004-09-29 17:40:11 +00001502
Reid Spencere4e40032007-03-21 23:19:50 +00001503 // V < Min || V >= Hi -> V > Hi-1
Dan Gohman186a6362009-08-12 16:04:34 +00001504 Hi = SubOne(cast<ConstantInt>(Hi));
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00001505 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00001506 ICmpInst::Predicate pred = (isSigned ?
1507 ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00001508 return new ICmpInst(pred, V, Hi);
Reid Spencere4d87aa2006-12-23 06:05:41 +00001509 }
Reid Spencerb83eb642006-10-20 07:07:24 +00001510
Reid Spencere4e40032007-03-21 23:19:50 +00001511 // Emit V-Lo >u Hi-1-Lo
1512 // Note that Hi has already had one subtracted from it, above.
Owen Andersonbaf3c402009-07-29 18:55:55 +00001513 ConstantInt *NegLo = cast<ConstantInt>(ConstantExpr::getNeg(Lo));
Chris Lattner74381062009-08-30 07:44:24 +00001514 Value *Add = Builder->CreateAdd(V, NegLo, V->getName()+".off");
Owen Andersonbaf3c402009-07-29 18:55:55 +00001515 Constant *LowerBound = ConstantExpr::getAdd(NegLo, Hi);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00001516 return new ICmpInst(ICmpInst::ICMP_UGT, Add, LowerBound);
Chris Lattnera96879a2004-09-29 17:40:11 +00001517}
1518
Chris Lattner7203e152005-09-18 07:22:02 +00001519// isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
1520// any number of 0s on either side. The 1s are allowed to wrap from LSB to
1521// MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs. 0x0F0F0000 is
1522// not, since all 1s are not contiguous.
Zhou Sheng4351c642007-04-02 08:20:41 +00001523static bool isRunOfOnes(ConstantInt *Val, uint32_t &MB, uint32_t &ME) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00001524 const APInt& V = Val->getValue();
Reid Spencerf2442522007-03-24 00:42:08 +00001525 uint32_t BitWidth = Val->getType()->getBitWidth();
1526 if (!APIntOps::isShiftedMask(BitWidth, V)) return false;
Chris Lattner7203e152005-09-18 07:22:02 +00001527
1528 // look for the first zero bit after the run of ones
Reid Spencerf2442522007-03-24 00:42:08 +00001529 MB = BitWidth - ((V - 1) ^ V).countLeadingZeros();
Chris Lattner7203e152005-09-18 07:22:02 +00001530 // look for the first non-zero bit
Reid Spencerf2442522007-03-24 00:42:08 +00001531 ME = V.getActiveBits();
Chris Lattner7203e152005-09-18 07:22:02 +00001532 return true;
1533}
1534
Chris Lattner7203e152005-09-18 07:22:02 +00001535/// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
1536/// where isSub determines whether the operator is a sub. If we can fold one of
1537/// the following xforms:
Chris Lattnerc8e77562005-09-18 04:24:45 +00001538///
1539/// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
1540/// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
1541/// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
1542///
1543/// return (A +/- B).
1544///
1545Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00001546 ConstantInt *Mask, bool isSub,
Chris Lattnerc8e77562005-09-18 04:24:45 +00001547 Instruction &I) {
1548 Instruction *LHSI = dyn_cast<Instruction>(LHS);
1549 if (!LHSI || LHSI->getNumOperands() != 2 ||
1550 !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
1551
1552 ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
1553
1554 switch (LHSI->getOpcode()) {
1555 default: return 0;
1556 case Instruction::And:
Owen Andersonbaf3c402009-07-29 18:55:55 +00001557 if (ConstantExpr::getAnd(N, Mask) == Mask) {
Chris Lattner7203e152005-09-18 07:22:02 +00001558 // If the AndRHS is a power of two minus one (0+1+), this is simple.
Zhou Sheng00f436c2007-03-24 15:34:37 +00001559 if ((Mask->getValue().countLeadingZeros() +
1560 Mask->getValue().countPopulation()) ==
1561 Mask->getValue().getBitWidth())
Chris Lattner7203e152005-09-18 07:22:02 +00001562 break;
1563
1564 // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
1565 // part, we don't need any explicit masks to take them out of A. If that
1566 // is all N is, ignore it.
Zhou Sheng4351c642007-04-02 08:20:41 +00001567 uint32_t MB = 0, ME = 0;
Chris Lattner7203e152005-09-18 07:22:02 +00001568 if (isRunOfOnes(Mask, MB, ME)) { // begin/end bit of run, inclusive
Reid Spencerb35ae032007-03-23 18:46:34 +00001569 uint32_t BitWidth = cast<IntegerType>(RHS->getType())->getBitWidth();
Zhou Sheng290bec52007-03-29 08:15:12 +00001570 APInt Mask(APInt::getLowBitsSet(BitWidth, MB-1));
Chris Lattner3bedbd92006-02-07 07:27:52 +00001571 if (MaskedValueIsZero(RHS, Mask))
Chris Lattner7203e152005-09-18 07:22:02 +00001572 break;
1573 }
1574 }
Chris Lattnerc8e77562005-09-18 04:24:45 +00001575 return 0;
1576 case Instruction::Or:
1577 case Instruction::Xor:
Chris Lattner7203e152005-09-18 07:22:02 +00001578 // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
Zhou Sheng00f436c2007-03-24 15:34:37 +00001579 if ((Mask->getValue().countLeadingZeros() +
1580 Mask->getValue().countPopulation()) == Mask->getValue().getBitWidth()
Owen Andersonbaf3c402009-07-29 18:55:55 +00001581 && ConstantExpr::getAnd(N, Mask)->isNullValue())
Chris Lattnerc8e77562005-09-18 04:24:45 +00001582 break;
1583 return 0;
1584 }
1585
Chris Lattnerc8e77562005-09-18 04:24:45 +00001586 if (isSub)
Chris Lattner74381062009-08-30 07:44:24 +00001587 return Builder->CreateSub(LHSI->getOperand(0), RHS, "fold");
1588 return Builder->CreateAdd(LHSI->getOperand(0), RHS, "fold");
Chris Lattnerc8e77562005-09-18 04:24:45 +00001589}
1590
Chris Lattner29cd5ba2008-11-16 05:06:21 +00001591/// FoldAndOfICmps - Fold (icmp)&(icmp) if possible.
1592Instruction *InstCombiner::FoldAndOfICmps(Instruction &I,
1593 ICmpInst *LHS, ICmpInst *RHS) {
Chris Lattnera317e042010-01-05 06:59:49 +00001594 ICmpInst::Predicate LHSCC = LHS->getPredicate(), RHSCC = RHS->getPredicate();
1595
1596 // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
1597 if (PredicatesFoldable(LHSCC, RHSCC)) {
1598 if (LHS->getOperand(0) == RHS->getOperand(1) &&
1599 LHS->getOperand(1) == RHS->getOperand(0))
1600 LHS->swapOperands();
1601 if (LHS->getOperand(0) == RHS->getOperand(0) &&
1602 LHS->getOperand(1) == RHS->getOperand(1)) {
1603 Value *Op0 = LHS->getOperand(0), *Op1 = LHS->getOperand(1);
1604 unsigned Code = getICmpCode(LHS) & getICmpCode(RHS);
1605 bool isSigned = LHS->isSigned() || RHS->isSigned();
1606 Value *RV = getICmpValue(isSigned, Code, Op0, Op1);
1607 if (Instruction *I = dyn_cast<Instruction>(RV))
1608 return I;
1609 // Otherwise, it's a constant boolean value.
1610 return ReplaceInstUsesWith(I, RV);
1611 }
1612 }
Chris Lattner29cd5ba2008-11-16 05:06:21 +00001613
Chris Lattnerea065fb2008-11-16 05:10:52 +00001614 // This only handles icmp of constants: (icmp1 A, C1) & (icmp2 B, C2).
Chris Lattnera317e042010-01-05 06:59:49 +00001615 Value *Val = LHS->getOperand(0), *Val2 = RHS->getOperand(0);
1616 ConstantInt *LHSCst = dyn_cast<ConstantInt>(LHS->getOperand(1));
1617 ConstantInt *RHSCst = dyn_cast<ConstantInt>(RHS->getOperand(1));
1618 if (LHSCst == 0 || RHSCst == 0) return 0;
Chris Lattnerea065fb2008-11-16 05:10:52 +00001619
Chris Lattner3f40e232009-11-29 00:51:17 +00001620 if (LHSCst == RHSCst && LHSCC == RHSCC) {
1621 // (icmp ult A, C) & (icmp ult B, C) --> (icmp ult (A|B), C)
1622 // where C is a power of 2
1623 if (LHSCC == ICmpInst::ICMP_ULT &&
1624 LHSCst->getValue().isPowerOf2()) {
1625 Value *NewOr = Builder->CreateOr(Val, Val2);
1626 return new ICmpInst(LHSCC, NewOr, LHSCst);
1627 }
1628
1629 // (icmp eq A, 0) & (icmp eq B, 0) --> (icmp eq (A|B), 0)
1630 if (LHSCC == ICmpInst::ICMP_EQ && LHSCst->isZero()) {
1631 Value *NewOr = Builder->CreateOr(Val, Val2);
1632 return new ICmpInst(LHSCC, NewOr, LHSCst);
1633 }
Chris Lattnerea065fb2008-11-16 05:10:52 +00001634 }
1635
1636 // From here on, we only handle:
1637 // (icmp1 A, C1) & (icmp2 A, C2) --> something simpler.
1638 if (Val != Val2) return 0;
1639
Chris Lattner29cd5ba2008-11-16 05:06:21 +00001640 // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
1641 if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
1642 RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
1643 LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
1644 RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
1645 return 0;
1646
1647 // We can't fold (ugt x, C) & (sgt x, C2).
1648 if (!PredicatesFoldable(LHSCC, RHSCC))
1649 return 0;
1650
1651 // Ensure that the larger constant is on the RHS.
Chris Lattneraa3e1572008-11-16 05:14:43 +00001652 bool ShouldSwap;
Nick Lewycky4a134af2009-10-25 05:20:17 +00001653 if (CmpInst::isSigned(LHSCC) ||
Chris Lattner29cd5ba2008-11-16 05:06:21 +00001654 (ICmpInst::isEquality(LHSCC) &&
Nick Lewycky4a134af2009-10-25 05:20:17 +00001655 CmpInst::isSigned(RHSCC)))
Chris Lattneraa3e1572008-11-16 05:14:43 +00001656 ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
Chris Lattner29cd5ba2008-11-16 05:06:21 +00001657 else
Chris Lattneraa3e1572008-11-16 05:14:43 +00001658 ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
1659
1660 if (ShouldSwap) {
Chris Lattner29cd5ba2008-11-16 05:06:21 +00001661 std::swap(LHS, RHS);
1662 std::swap(LHSCst, RHSCst);
1663 std::swap(LHSCC, RHSCC);
1664 }
1665
1666 // At this point, we know we have have two icmp instructions
1667 // comparing a value against two constants and and'ing the result
1668 // together. Because of the above check, we know that we only have
1669 // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know
Chris Lattnera317e042010-01-05 06:59:49 +00001670 // (from the icmp folding check above), that the two constants
Chris Lattner29cd5ba2008-11-16 05:06:21 +00001671 // are not equal and that the larger constant is on the RHS
1672 assert(LHSCst != RHSCst && "Compares not folded above?");
1673
1674 switch (LHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00001675 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00001676 case ICmpInst::ICMP_EQ:
1677 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00001678 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00001679 case ICmpInst::ICMP_EQ: // (X == 13 & X == 15) -> false
1680 case ICmpInst::ICMP_UGT: // (X == 13 & X > 15) -> false
1681 case ICmpInst::ICMP_SGT: // (X == 13 & X > 15) -> false
Chris Lattner4de84762010-01-04 07:02:48 +00001682 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getContext()));
Chris Lattner29cd5ba2008-11-16 05:06:21 +00001683 case ICmpInst::ICMP_NE: // (X == 13 & X != 15) -> X == 13
1684 case ICmpInst::ICMP_ULT: // (X == 13 & X < 15) -> X == 13
1685 case ICmpInst::ICMP_SLT: // (X == 13 & X < 15) -> X == 13
1686 return ReplaceInstUsesWith(I, LHS);
1687 }
1688 case ICmpInst::ICMP_NE:
1689 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00001690 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00001691 case ICmpInst::ICMP_ULT:
Dan Gohman186a6362009-08-12 16:04:34 +00001692 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X u< 14) -> X < 13
Dan Gohman1c8a23c2009-08-25 23:17:54 +00001693 return new ICmpInst(ICmpInst::ICMP_ULT, Val, LHSCst);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00001694 break; // (X != 13 & X u< 15) -> no change
1695 case ICmpInst::ICMP_SLT:
Dan Gohman186a6362009-08-12 16:04:34 +00001696 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X s< 14) -> X < 13
Dan Gohman1c8a23c2009-08-25 23:17:54 +00001697 return new ICmpInst(ICmpInst::ICMP_SLT, Val, LHSCst);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00001698 break; // (X != 13 & X s< 15) -> no change
1699 case ICmpInst::ICMP_EQ: // (X != 13 & X == 15) -> X == 15
1700 case ICmpInst::ICMP_UGT: // (X != 13 & X u> 15) -> X u> 15
1701 case ICmpInst::ICMP_SGT: // (X != 13 & X s> 15) -> X s> 15
1702 return ReplaceInstUsesWith(I, RHS);
1703 case ICmpInst::ICMP_NE:
Dan Gohman186a6362009-08-12 16:04:34 +00001704 if (LHSCst == SubOne(RHSCst)){// (X != 13 & X != 14) -> X-13 >u 1
Owen Andersonbaf3c402009-07-29 18:55:55 +00001705 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
Chris Lattner74381062009-08-30 07:44:24 +00001706 Value *Add = Builder->CreateAdd(Val, AddCST, Val->getName()+".off");
Dan Gohman1c8a23c2009-08-25 23:17:54 +00001707 return new ICmpInst(ICmpInst::ICMP_UGT, Add,
Owen Andersoneed707b2009-07-24 23:12:02 +00001708 ConstantInt::get(Add->getType(), 1));
Chris Lattner29cd5ba2008-11-16 05:06:21 +00001709 }
1710 break; // (X != 13 & X != 15) -> no change
1711 }
1712 break;
1713 case ICmpInst::ICMP_ULT:
1714 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00001715 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00001716 case ICmpInst::ICMP_EQ: // (X u< 13 & X == 15) -> false
1717 case ICmpInst::ICMP_UGT: // (X u< 13 & X u> 15) -> false
Chris Lattner4de84762010-01-04 07:02:48 +00001718 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getContext()));
Chris Lattner29cd5ba2008-11-16 05:06:21 +00001719 case ICmpInst::ICMP_SGT: // (X u< 13 & X s> 15) -> no change
1720 break;
1721 case ICmpInst::ICMP_NE: // (X u< 13 & X != 15) -> X u< 13
1722 case ICmpInst::ICMP_ULT: // (X u< 13 & X u< 15) -> X u< 13
1723 return ReplaceInstUsesWith(I, LHS);
1724 case ICmpInst::ICMP_SLT: // (X u< 13 & X s< 15) -> no change
1725 break;
1726 }
1727 break;
1728 case ICmpInst::ICMP_SLT:
1729 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00001730 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00001731 case ICmpInst::ICMP_EQ: // (X s< 13 & X == 15) -> false
1732 case ICmpInst::ICMP_SGT: // (X s< 13 & X s> 15) -> false
Chris Lattner4de84762010-01-04 07:02:48 +00001733 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getContext()));
Chris Lattner29cd5ba2008-11-16 05:06:21 +00001734 case ICmpInst::ICMP_UGT: // (X s< 13 & X u> 15) -> no change
1735 break;
1736 case ICmpInst::ICMP_NE: // (X s< 13 & X != 15) -> X < 13
1737 case ICmpInst::ICMP_SLT: // (X s< 13 & X s< 15) -> X < 13
1738 return ReplaceInstUsesWith(I, LHS);
1739 case ICmpInst::ICMP_ULT: // (X s< 13 & X u< 15) -> no change
1740 break;
1741 }
1742 break;
1743 case ICmpInst::ICMP_UGT:
1744 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00001745 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00001746 case ICmpInst::ICMP_EQ: // (X u> 13 & X == 15) -> X == 15
1747 case ICmpInst::ICMP_UGT: // (X u> 13 & X u> 15) -> X u> 15
1748 return ReplaceInstUsesWith(I, RHS);
1749 case ICmpInst::ICMP_SGT: // (X u> 13 & X s> 15) -> no change
1750 break;
1751 case ICmpInst::ICMP_NE:
Dan Gohman186a6362009-08-12 16:04:34 +00001752 if (RHSCst == AddOne(LHSCst)) // (X u> 13 & X != 14) -> X u> 14
Dan Gohman1c8a23c2009-08-25 23:17:54 +00001753 return new ICmpInst(LHSCC, Val, RHSCst);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00001754 break; // (X u> 13 & X != 15) -> no change
Chris Lattner69d4ced2008-11-16 05:20:07 +00001755 case ICmpInst::ICMP_ULT: // (X u> 13 & X u< 15) -> (X-14) <u 1
Dan Gohman186a6362009-08-12 16:04:34 +00001756 return InsertRangeTest(Val, AddOne(LHSCst),
Owen Andersond672ecb2009-07-03 00:17:18 +00001757 RHSCst, false, true, I);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00001758 case ICmpInst::ICMP_SLT: // (X u> 13 & X s< 15) -> no change
1759 break;
1760 }
1761 break;
1762 case ICmpInst::ICMP_SGT:
1763 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00001764 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00001765 case ICmpInst::ICMP_EQ: // (X s> 13 & X == 15) -> X == 15
1766 case ICmpInst::ICMP_SGT: // (X s> 13 & X s> 15) -> X s> 15
1767 return ReplaceInstUsesWith(I, RHS);
1768 case ICmpInst::ICMP_UGT: // (X s> 13 & X u> 15) -> no change
1769 break;
1770 case ICmpInst::ICMP_NE:
Dan Gohman186a6362009-08-12 16:04:34 +00001771 if (RHSCst == AddOne(LHSCst)) // (X s> 13 & X != 14) -> X s> 14
Dan Gohman1c8a23c2009-08-25 23:17:54 +00001772 return new ICmpInst(LHSCC, Val, RHSCst);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00001773 break; // (X s> 13 & X != 15) -> no change
Chris Lattner69d4ced2008-11-16 05:20:07 +00001774 case ICmpInst::ICMP_SLT: // (X s> 13 & X s< 15) -> (X-14) s< 1
Dan Gohman186a6362009-08-12 16:04:34 +00001775 return InsertRangeTest(Val, AddOne(LHSCst),
Owen Andersond672ecb2009-07-03 00:17:18 +00001776 RHSCst, true, true, I);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00001777 case ICmpInst::ICMP_ULT: // (X s> 13 & X u< 15) -> no change
1778 break;
1779 }
1780 break;
1781 }
Chris Lattner29cd5ba2008-11-16 05:06:21 +00001782
1783 return 0;
1784}
1785
Chris Lattner42d1be02009-07-23 05:14:02 +00001786Instruction *InstCombiner::FoldAndOfFCmps(Instruction &I, FCmpInst *LHS,
1787 FCmpInst *RHS) {
1788
1789 if (LHS->getPredicate() == FCmpInst::FCMP_ORD &&
1790 RHS->getPredicate() == FCmpInst::FCMP_ORD) {
1791 // (fcmp ord x, c) & (fcmp ord y, c) -> (fcmp ord x, y)
1792 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
1793 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
1794 // If either of the constants are nans, then the whole thing returns
1795 // false.
1796 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Chris Lattner4de84762010-01-04 07:02:48 +00001797 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getContext()));
Dan Gohman1c8a23c2009-08-25 23:17:54 +00001798 return new FCmpInst(FCmpInst::FCMP_ORD,
Chris Lattner42d1be02009-07-23 05:14:02 +00001799 LHS->getOperand(0), RHS->getOperand(0));
1800 }
Chris Lattnerf98d2532009-07-23 05:32:17 +00001801
1802 // Handle vector zeros. This occurs because the canonical form of
1803 // "fcmp ord x,x" is "fcmp ord x, 0".
1804 if (isa<ConstantAggregateZero>(LHS->getOperand(1)) &&
1805 isa<ConstantAggregateZero>(RHS->getOperand(1)))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00001806 return new FCmpInst(FCmpInst::FCMP_ORD,
Chris Lattnerf98d2532009-07-23 05:32:17 +00001807 LHS->getOperand(0), RHS->getOperand(0));
Chris Lattner42d1be02009-07-23 05:14:02 +00001808 return 0;
1809 }
1810
1811 Value *Op0LHS = LHS->getOperand(0), *Op0RHS = LHS->getOperand(1);
1812 Value *Op1LHS = RHS->getOperand(0), *Op1RHS = RHS->getOperand(1);
1813 FCmpInst::Predicate Op0CC = LHS->getPredicate(), Op1CC = RHS->getPredicate();
1814
1815
1816 if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
1817 // Swap RHS operands to match LHS.
1818 Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
1819 std::swap(Op1LHS, Op1RHS);
1820 }
1821
1822 if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
1823 // Simplify (fcmp cc0 x, y) & (fcmp cc1 x, y).
1824 if (Op0CC == Op1CC)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00001825 return new FCmpInst((FCmpInst::Predicate)Op0CC, Op0LHS, Op0RHS);
Chris Lattner42d1be02009-07-23 05:14:02 +00001826
1827 if (Op0CC == FCmpInst::FCMP_FALSE || Op1CC == FCmpInst::FCMP_FALSE)
Chris Lattner4de84762010-01-04 07:02:48 +00001828 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getContext()));
Chris Lattner42d1be02009-07-23 05:14:02 +00001829 if (Op0CC == FCmpInst::FCMP_TRUE)
1830 return ReplaceInstUsesWith(I, RHS);
1831 if (Op1CC == FCmpInst::FCMP_TRUE)
1832 return ReplaceInstUsesWith(I, LHS);
1833
1834 bool Op0Ordered;
1835 bool Op1Ordered;
1836 unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
1837 unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
1838 if (Op1Pred == 0) {
1839 std::swap(LHS, RHS);
1840 std::swap(Op0Pred, Op1Pred);
1841 std::swap(Op0Ordered, Op1Ordered);
1842 }
1843 if (Op0Pred == 0) {
1844 // uno && ueq -> uno && (uno || eq) -> ueq
1845 // ord && olt -> ord && (ord && lt) -> olt
1846 if (Op0Ordered == Op1Ordered)
1847 return ReplaceInstUsesWith(I, RHS);
1848
1849 // uno && oeq -> uno && (ord && eq) -> false
1850 // uno && ord -> false
1851 if (!Op0Ordered)
Chris Lattner4de84762010-01-04 07:02:48 +00001852 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getContext()));
Chris Lattner42d1be02009-07-23 05:14:02 +00001853 // ord && ueq -> ord && (uno || eq) -> oeq
Chris Lattner4de84762010-01-04 07:02:48 +00001854 return cast<Instruction>(getFCmpValue(true, Op1Pred, Op0LHS, Op0RHS));
Chris Lattner42d1be02009-07-23 05:14:02 +00001855 }
1856 }
1857
1858 return 0;
1859}
1860
Chris Lattner29cd5ba2008-11-16 05:06:21 +00001861
Chris Lattner7e708292002-06-25 16:13:24 +00001862Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00001863 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00001864 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00001865
Chris Lattnerd06094f2009-11-10 00:55:12 +00001866 if (Value *V = SimplifyAndInst(Op0, Op1, TD))
1867 return ReplaceInstUsesWith(I, V);
Chris Lattner3f5b8772002-05-06 16:14:14 +00001868
Chris Lattnerf8c36f52006-02-12 08:02:11 +00001869 // See if we can simplify any instructions used by the instruction whose sole
Chris Lattner9ca96412006-02-08 03:25:32 +00001870 // purpose is to compute bits we don't care about.
Dan Gohman6de29f82009-06-15 22:12:54 +00001871 if (SimplifyDemandedInstructionBits(I))
Nick Lewycky546d6312010-01-02 15:25:44 +00001872 return &I;
Dan Gohman6de29f82009-06-15 22:12:54 +00001873
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00001874 if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner7acdf1d2009-10-11 22:00:32 +00001875 const APInt &AndRHSMask = AndRHS->getValue();
Zhou Sheng3a507fd2007-04-01 17:13:37 +00001876 APInt NotAndRHS(~AndRHSMask);
Chris Lattner6e7ba452005-01-01 16:22:27 +00001877
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00001878 // Optimize a variety of ((val OP C1) & C2) combinations...
Chris Lattner7acdf1d2009-10-11 22:00:32 +00001879 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Chris Lattner6e7ba452005-01-01 16:22:27 +00001880 Value *Op0LHS = Op0I->getOperand(0);
1881 Value *Op0RHS = Op0I->getOperand(1);
1882 switch (Op0I->getOpcode()) {
Chris Lattner7acdf1d2009-10-11 22:00:32 +00001883 default: break;
Chris Lattner6e7ba452005-01-01 16:22:27 +00001884 case Instruction::Xor:
1885 case Instruction::Or:
Chris Lattnerad1e3022005-01-23 20:26:55 +00001886 // If the mask is only needed on one incoming arm, push it up.
Chris Lattner7acdf1d2009-10-11 22:00:32 +00001887 if (!Op0I->hasOneUse()) break;
1888
1889 if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
1890 // Not masking anything out for the LHS, move to RHS.
1891 Value *NewRHS = Builder->CreateAnd(Op0RHS, AndRHS,
1892 Op0RHS->getName()+".masked");
1893 return BinaryOperator::Create(Op0I->getOpcode(), Op0LHS, NewRHS);
1894 }
1895 if (!isa<Constant>(Op0RHS) &&
1896 MaskedValueIsZero(Op0RHS, NotAndRHS)) {
1897 // Not masking anything out for the RHS, move to LHS.
1898 Value *NewLHS = Builder->CreateAnd(Op0LHS, AndRHS,
1899 Op0LHS->getName()+".masked");
1900 return BinaryOperator::Create(Op0I->getOpcode(), NewLHS, Op0RHS);
Chris Lattnerad1e3022005-01-23 20:26:55 +00001901 }
1902
Chris Lattner6e7ba452005-01-01 16:22:27 +00001903 break;
Chris Lattnerc8e77562005-09-18 04:24:45 +00001904 case Instruction::Add:
Chris Lattner7203e152005-09-18 07:22:02 +00001905 // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
1906 // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
1907 // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
1908 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001909 return BinaryOperator::CreateAnd(V, AndRHS);
Chris Lattner7203e152005-09-18 07:22:02 +00001910 if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001911 return BinaryOperator::CreateAnd(V, AndRHS); // Add commutes
Chris Lattnerc8e77562005-09-18 04:24:45 +00001912 break;
1913
1914 case Instruction::Sub:
Chris Lattner7203e152005-09-18 07:22:02 +00001915 // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
1916 // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
1917 // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
1918 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001919 return BinaryOperator::CreateAnd(V, AndRHS);
Nick Lewyckyb4d1bc92008-07-09 04:32:37 +00001920
Nick Lewycky5dcc41f2008-07-10 05:51:40 +00001921 // (A - N) & AndRHS -> -N & AndRHS iff A&AndRHS==0 and AndRHS
1922 // has 1's for all bits that the subtraction with A might affect.
1923 if (Op0I->hasOneUse()) {
1924 uint32_t BitWidth = AndRHSMask.getBitWidth();
1925 uint32_t Zeros = AndRHSMask.countLeadingZeros();
1926 APInt Mask = APInt::getLowBitsSet(BitWidth, BitWidth - Zeros);
1927
Nick Lewyckyb4d1bc92008-07-09 04:32:37 +00001928 ConstantInt *A = dyn_cast<ConstantInt>(Op0LHS);
Nick Lewycky5dcc41f2008-07-10 05:51:40 +00001929 if (!(A && A->isZero()) && // avoid infinite recursion.
1930 MaskedValueIsZero(Op0LHS, Mask)) {
Chris Lattner74381062009-08-30 07:44:24 +00001931 Value *NewNeg = Builder->CreateNeg(Op0RHS);
Nick Lewyckyb4d1bc92008-07-09 04:32:37 +00001932 return BinaryOperator::CreateAnd(NewNeg, AndRHS);
1933 }
1934 }
Chris Lattnerc8e77562005-09-18 04:24:45 +00001935 break;
Nick Lewyckyd1f77bf2008-07-09 05:20:13 +00001936
1937 case Instruction::Shl:
1938 case Instruction::LShr:
1939 // (1 << x) & 1 --> zext(x == 0)
1940 // (1 >> x) & 1 --> zext(x == 0)
Nick Lewyckyd8ad4922008-07-09 07:35:26 +00001941 if (AndRHSMask == 1 && Op0LHS == AndRHS) {
Chris Lattner74381062009-08-30 07:44:24 +00001942 Value *NewICmp =
1943 Builder->CreateICmpEQ(Op0RHS, Constant::getNullValue(I.getType()));
Nick Lewyckyd1f77bf2008-07-09 05:20:13 +00001944 return new ZExtInst(NewICmp, I.getType());
1945 }
1946 break;
Chris Lattner6e7ba452005-01-01 16:22:27 +00001947 }
1948
Chris Lattner58403262003-07-23 19:25:52 +00001949 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattner6e7ba452005-01-01 16:22:27 +00001950 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00001951 return Res;
Chris Lattner6e7ba452005-01-01 16:22:27 +00001952 } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
Chris Lattner2b83af22005-08-07 07:03:10 +00001953 // If this is an integer truncation or change from signed-to-unsigned, and
1954 // if the source is an and/or with immediate, transform it. This
1955 // frequently occurs for bitfield accesses.
1956 if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
Reid Spencer3da59db2006-11-27 01:05:10 +00001957 if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
Chris Lattner2b83af22005-08-07 07:03:10 +00001958 CastOp->getNumOperands() == 2)
Chris Lattner48b59ec2009-10-26 15:40:07 +00001959 if (ConstantInt *AndCI =dyn_cast<ConstantInt>(CastOp->getOperand(1))){
Chris Lattner2b83af22005-08-07 07:03:10 +00001960 if (CastOp->getOpcode() == Instruction::And) {
1961 // Change: and (cast (and X, C1) to T), C2
Reid Spencer3da59db2006-11-27 01:05:10 +00001962 // into : and (cast X to T), trunc_or_bitcast(C1)&C2
1963 // This will fold the two constants together, which may allow
1964 // other simplifications.
Chris Lattner74381062009-08-30 07:44:24 +00001965 Value *NewCast = Builder->CreateTruncOrBitCast(
Reid Spencerd977d862006-12-12 23:36:14 +00001966 CastOp->getOperand(0), I.getType(),
1967 CastOp->getName()+".shrunk");
Reid Spencer3da59db2006-11-27 01:05:10 +00001968 // trunc_or_bitcast(C1)&C2
Chris Lattner74381062009-08-30 07:44:24 +00001969 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
Owen Andersonbaf3c402009-07-29 18:55:55 +00001970 C3 = ConstantExpr::getAnd(C3, AndRHS);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001971 return BinaryOperator::CreateAnd(NewCast, C3);
Chris Lattner2b83af22005-08-07 07:03:10 +00001972 } else if (CastOp->getOpcode() == Instruction::Or) {
1973 // Change: and (cast (or X, C1) to T), C2
1974 // into : trunc(C1)&C2 iff trunc(C1)&C2 == C2
Chris Lattner74381062009-08-30 07:44:24 +00001975 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
Owen Andersonbaf3c402009-07-29 18:55:55 +00001976 if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS)
Owen Andersond672ecb2009-07-03 00:17:18 +00001977 // trunc(C1)&C2
Chris Lattner2b83af22005-08-07 07:03:10 +00001978 return ReplaceInstUsesWith(I, AndRHS);
1979 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00001980 }
Chris Lattner2b83af22005-08-07 07:03:10 +00001981 }
Chris Lattner06782f82003-07-23 19:36:21 +00001982 }
Chris Lattner2eefe512004-04-09 19:05:30 +00001983
1984 // Try to fold constant and into select arguments.
1985 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner80f43d32010-01-04 07:53:58 +00001986 if (Instruction *R = FoldOpIntoSelect(I, SI))
Chris Lattner2eefe512004-04-09 19:05:30 +00001987 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00001988 if (isa<PHINode>(Op0))
1989 if (Instruction *NV = FoldOpIntoPhi(I))
1990 return NV;
Chris Lattnerc6a8aff2003-07-23 17:57:01 +00001991 }
1992
Chris Lattner5b62aa72004-06-18 06:07:51 +00001993
Misha Brukmancb6267b2004-07-30 12:50:08 +00001994 // (~A & ~B) == (~(A | B)) - De Morgan's Law
Chris Lattnerd06094f2009-11-10 00:55:12 +00001995 if (Value *Op0NotVal = dyn_castNotVal(Op0))
1996 if (Value *Op1NotVal = dyn_castNotVal(Op1))
1997 if (Op0->hasOneUse() && Op1->hasOneUse()) {
1998 Value *Or = Builder->CreateOr(Op0NotVal, Op1NotVal,
1999 I.getName()+".demorgan");
2000 return BinaryOperator::CreateNot(Or);
2001 }
2002
Chris Lattner2082ad92006-02-13 23:07:23 +00002003 {
Chris Lattner003b6202007-06-15 05:58:24 +00002004 Value *A = 0, *B = 0, *C = 0, *D = 0;
Chris Lattnerd06094f2009-11-10 00:55:12 +00002005 // (A|B) & ~(A&B) -> A^B
2006 if (match(Op0, m_Or(m_Value(A), m_Value(B))) &&
2007 match(Op1, m_Not(m_And(m_Value(C), m_Value(D)))) &&
2008 ((A == C && B == D) || (A == D && B == C)))
2009 return BinaryOperator::CreateXor(A, B);
Chris Lattner003b6202007-06-15 05:58:24 +00002010
Chris Lattnerd06094f2009-11-10 00:55:12 +00002011 // ~(A&B) & (A|B) -> A^B
2012 if (match(Op1, m_Or(m_Value(A), m_Value(B))) &&
2013 match(Op0, m_Not(m_And(m_Value(C), m_Value(D)))) &&
2014 ((A == C && B == D) || (A == D && B == C)))
2015 return BinaryOperator::CreateXor(A, B);
Chris Lattner64daab52006-04-01 08:03:55 +00002016
2017 if (Op0->hasOneUse() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00002018 match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
Chris Lattner64daab52006-04-01 08:03:55 +00002019 if (A == Op1) { // (A^B)&A -> A&(A^B)
2020 I.swapOperands(); // Simplify below
2021 std::swap(Op0, Op1);
2022 } else if (B == Op1) { // (A^B)&B -> B&(B^A)
2023 cast<BinaryOperator>(Op0)->swapOperands();
2024 I.swapOperands(); // Simplify below
2025 std::swap(Op0, Op1);
2026 }
2027 }
Bill Wendling7f0ef6b2008-11-30 13:08:13 +00002028
Chris Lattner64daab52006-04-01 08:03:55 +00002029 if (Op1->hasOneUse() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00002030 match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
Chris Lattner64daab52006-04-01 08:03:55 +00002031 if (B == Op0) { // B&(A^B) -> B&(B^A)
2032 cast<BinaryOperator>(Op1)->swapOperands();
2033 std::swap(A, B);
2034 }
Chris Lattner74381062009-08-30 07:44:24 +00002035 if (A == Op0) // A&(A^B) -> A & ~B
2036 return BinaryOperator::CreateAnd(A, Builder->CreateNot(B, "tmp"));
Chris Lattner64daab52006-04-01 08:03:55 +00002037 }
Bill Wendling7f0ef6b2008-11-30 13:08:13 +00002038
2039 // (A&((~A)|B)) -> A&B
Dan Gohman4ae51262009-08-12 16:23:25 +00002040 if (match(Op0, m_Or(m_Not(m_Specific(Op1)), m_Value(A))) ||
2041 match(Op0, m_Or(m_Value(A), m_Not(m_Specific(Op1)))))
Chris Lattnerd8aafcb2008-12-01 05:16:26 +00002042 return BinaryOperator::CreateAnd(A, Op1);
Dan Gohman4ae51262009-08-12 16:23:25 +00002043 if (match(Op1, m_Or(m_Not(m_Specific(Op0)), m_Value(A))) ||
2044 match(Op1, m_Or(m_Value(A), m_Not(m_Specific(Op0)))))
Chris Lattnerd8aafcb2008-12-01 05:16:26 +00002045 return BinaryOperator::CreateAnd(A, Op0);
Chris Lattner2082ad92006-02-13 23:07:23 +00002046 }
2047
Chris Lattnera317e042010-01-05 06:59:49 +00002048 if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1))
Chris Lattner29cd5ba2008-11-16 05:06:21 +00002049 if (ICmpInst *LHS = dyn_cast<ICmpInst>(Op0))
2050 if (Instruction *Res = FoldAndOfICmps(I, LHS, RHS))
2051 return Res;
Chris Lattner955f3312004-09-28 21:48:02 +00002052
Chris Lattner6fc205f2006-05-05 06:39:07 +00002053 // fold (and (cast A), (cast B)) -> (cast (and A, B))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00002054 if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
2055 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
2056 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind ?
2057 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattnerf98d2532009-07-23 05:32:17 +00002058 if (SrcTy == Op1C->getOperand(0)->getType() &&
2059 SrcTy->isIntOrIntVector() &&
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00002060 // Only do this if the casts both really cause code to be generated.
Chris Lattner80f43d32010-01-04 07:53:58 +00002061 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
2062 I.getType()) &&
Reid Spencere4d87aa2006-12-23 06:05:41 +00002063 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
Chris Lattner80f43d32010-01-04 07:53:58 +00002064 I.getType())) {
Chris Lattner74381062009-08-30 07:44:24 +00002065 Value *NewOp = Builder->CreateAnd(Op0C->getOperand(0),
2066 Op1C->getOperand(0), I.getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002067 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00002068 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00002069 }
Chris Lattnere511b742006-11-14 07:46:50 +00002070
2071 // (X >> Z) & (Y >> Z) -> (X&Y) >> Z for all shifts.
Reid Spencer832254e2007-02-02 02:16:23 +00002072 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
2073 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
2074 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
Chris Lattnere511b742006-11-14 07:46:50 +00002075 SI0->getOperand(1) == SI1->getOperand(1) &&
2076 (SI0->hasOneUse() || SI1->hasOneUse())) {
Chris Lattner74381062009-08-30 07:44:24 +00002077 Value *NewOp =
2078 Builder->CreateAnd(SI0->getOperand(0), SI1->getOperand(0),
2079 SI0->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002080 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
Reid Spencer832254e2007-02-02 02:16:23 +00002081 SI1->getOperand(1));
Chris Lattnere511b742006-11-14 07:46:50 +00002082 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00002083 }
2084
Evan Cheng8db90722008-10-14 17:15:11 +00002085 // If and'ing two fcmp, try combine them into one.
Chris Lattner99c65742007-10-24 05:38:08 +00002086 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
Chris Lattner42d1be02009-07-23 05:14:02 +00002087 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
2088 if (Instruction *Res = FoldAndOfFCmps(I, LHS, RHS))
2089 return Res;
Chris Lattner99c65742007-10-24 05:38:08 +00002090 }
Nick Lewyckyb4d1bc92008-07-09 04:32:37 +00002091
Chris Lattner7e708292002-06-25 16:13:24 +00002092 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00002093}
2094
Chris Lattner8c34cd22008-10-05 02:13:19 +00002095/// CollectBSwapParts - Analyze the specified subexpression and see if it is
2096/// capable of providing pieces of a bswap. The subexpression provides pieces
2097/// of a bswap if it is proven that each of the non-zero bytes in the output of
2098/// the expression came from the corresponding "byte swapped" byte in some other
2099/// value. For example, if the current subexpression is "(shl i32 %X, 24)" then
2100/// we know that the expression deposits the low byte of %X into the high byte
2101/// of the bswap result and that all other bytes are zero. This expression is
2102/// accepted, the high byte of ByteValues is set to X to indicate a correct
2103/// match.
2104///
2105/// This function returns true if the match was unsuccessful and false if so.
2106/// On entry to the function the "OverallLeftShift" is a signed integer value
2107/// indicating the number of bytes that the subexpression is later shifted. For
2108/// example, if the expression is later right shifted by 16 bits, the
2109/// OverallLeftShift value would be -2 on entry. This is used to specify which
2110/// byte of ByteValues is actually being set.
2111///
2112/// Similarly, ByteMask is a bitmask where a bit is clear if its corresponding
2113/// byte is masked to zero by a user. For example, in (X & 255), X will be
2114/// processed with a bytemask of 1. Because bytemask is 32-bits, this limits
2115/// this function to working on up to 32-byte (256 bit) values. ByteMask is
2116/// always in the local (OverallLeftShift) coordinate space.
2117///
2118static bool CollectBSwapParts(Value *V, int OverallLeftShift, uint32_t ByteMask,
2119 SmallVector<Value*, 8> &ByteValues) {
2120 if (Instruction *I = dyn_cast<Instruction>(V)) {
2121 // If this is an or instruction, it may be an inner node of the bswap.
2122 if (I->getOpcode() == Instruction::Or) {
2123 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
2124 ByteValues) ||
2125 CollectBSwapParts(I->getOperand(1), OverallLeftShift, ByteMask,
2126 ByteValues);
Chris Lattnerafe91a52006-06-15 19:07:26 +00002127 }
Chris Lattner8c34cd22008-10-05 02:13:19 +00002128
2129 // If this is a logical shift by a constant multiple of 8, recurse with
2130 // OverallLeftShift and ByteMask adjusted.
2131 if (I->isLogicalShift() && isa<ConstantInt>(I->getOperand(1))) {
2132 unsigned ShAmt =
2133 cast<ConstantInt>(I->getOperand(1))->getLimitedValue(~0U);
2134 // Ensure the shift amount is defined and of a byte value.
2135 if ((ShAmt & 7) || (ShAmt > 8*ByteValues.size()))
2136 return true;
2137
2138 unsigned ByteShift = ShAmt >> 3;
2139 if (I->getOpcode() == Instruction::Shl) {
2140 // X << 2 -> collect(X, +2)
2141 OverallLeftShift += ByteShift;
2142 ByteMask >>= ByteShift;
2143 } else {
2144 // X >>u 2 -> collect(X, -2)
2145 OverallLeftShift -= ByteShift;
2146 ByteMask <<= ByteShift;
Chris Lattnerde17ddc2008-10-08 06:42:28 +00002147 ByteMask &= (~0U >> (32-ByteValues.size()));
Chris Lattner8c34cd22008-10-05 02:13:19 +00002148 }
2149
2150 if (OverallLeftShift >= (int)ByteValues.size()) return true;
2151 if (OverallLeftShift <= -(int)ByteValues.size()) return true;
2152
2153 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
2154 ByteValues);
2155 }
2156
2157 // If this is a logical 'and' with a mask that clears bytes, clear the
2158 // corresponding bytes in ByteMask.
2159 if (I->getOpcode() == Instruction::And &&
2160 isa<ConstantInt>(I->getOperand(1))) {
2161 // Scan every byte of the and mask, seeing if the byte is either 0 or 255.
2162 unsigned NumBytes = ByteValues.size();
2163 APInt Byte(I->getType()->getPrimitiveSizeInBits(), 255);
2164 const APInt &AndMask = cast<ConstantInt>(I->getOperand(1))->getValue();
2165
2166 for (unsigned i = 0; i != NumBytes; ++i, Byte <<= 8) {
2167 // If this byte is masked out by a later operation, we don't care what
2168 // the and mask is.
2169 if ((ByteMask & (1 << i)) == 0)
2170 continue;
2171
2172 // If the AndMask is all zeros for this byte, clear the bit.
2173 APInt MaskB = AndMask & Byte;
2174 if (MaskB == 0) {
2175 ByteMask &= ~(1U << i);
2176 continue;
2177 }
2178
2179 // If the AndMask is not all ones for this byte, it's not a bytezap.
2180 if (MaskB != Byte)
2181 return true;
2182
2183 // Otherwise, this byte is kept.
2184 }
2185
2186 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
2187 ByteValues);
2188 }
Chris Lattnerafe91a52006-06-15 19:07:26 +00002189 }
2190
Chris Lattner8c34cd22008-10-05 02:13:19 +00002191 // Okay, we got to something that isn't a shift, 'or' or 'and'. This must be
2192 // the input value to the bswap. Some observations: 1) if more than one byte
2193 // is demanded from this input, then it could not be successfully assembled
2194 // into a byteswap. At least one of the two bytes would not be aligned with
2195 // their ultimate destination.
2196 if (!isPowerOf2_32(ByteMask)) return true;
2197 unsigned InputByteNo = CountTrailingZeros_32(ByteMask);
Chris Lattnerafe91a52006-06-15 19:07:26 +00002198
Chris Lattner8c34cd22008-10-05 02:13:19 +00002199 // 2) The input and ultimate destinations must line up: if byte 3 of an i32
2200 // is demanded, it needs to go into byte 0 of the result. This means that the
2201 // byte needs to be shifted until it lands in the right byte bucket. The
2202 // shift amount depends on the position: if the byte is coming from the high
2203 // part of the value (e.g. byte 3) then it must be shifted right. If from the
2204 // low part, it must be shifted left.
2205 unsigned DestByteNo = InputByteNo + OverallLeftShift;
2206 if (InputByteNo < ByteValues.size()/2) {
2207 if (ByteValues.size()-1-DestByteNo != InputByteNo)
2208 return true;
2209 } else {
2210 if (ByteValues.size()-1-DestByteNo != InputByteNo)
2211 return true;
2212 }
Chris Lattnerafe91a52006-06-15 19:07:26 +00002213
2214 // If the destination byte value is already defined, the values are or'd
2215 // together, which isn't a bswap (unless it's an or of the same bits).
Chris Lattner8c34cd22008-10-05 02:13:19 +00002216 if (ByteValues[DestByteNo] && ByteValues[DestByteNo] != V)
Chris Lattnerafe91a52006-06-15 19:07:26 +00002217 return true;
Chris Lattner8c34cd22008-10-05 02:13:19 +00002218 ByteValues[DestByteNo] = V;
Chris Lattnerafe91a52006-06-15 19:07:26 +00002219 return false;
2220}
2221
2222/// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
2223/// If so, insert the new bswap intrinsic and return it.
2224Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
Chris Lattner55fc8c42007-04-01 20:57:36 +00002225 const IntegerType *ITy = dyn_cast<IntegerType>(I.getType());
Chris Lattner8c34cd22008-10-05 02:13:19 +00002226 if (!ITy || ITy->getBitWidth() % 16 ||
2227 // ByteMask only allows up to 32-byte values.
2228 ITy->getBitWidth() > 32*8)
Chris Lattner55fc8c42007-04-01 20:57:36 +00002229 return 0; // Can only bswap pairs of bytes. Can't do vectors.
Chris Lattnerafe91a52006-06-15 19:07:26 +00002230
2231 /// ByteValues - For each byte of the result, we keep track of which value
2232 /// defines each byte.
Chris Lattner535014f2007-02-15 22:52:10 +00002233 SmallVector<Value*, 8> ByteValues;
Chris Lattner55fc8c42007-04-01 20:57:36 +00002234 ByteValues.resize(ITy->getBitWidth()/8);
Chris Lattnerafe91a52006-06-15 19:07:26 +00002235
2236 // Try to find all the pieces corresponding to the bswap.
Chris Lattner8c34cd22008-10-05 02:13:19 +00002237 uint32_t ByteMask = ~0U >> (32-ByteValues.size());
2238 if (CollectBSwapParts(&I, 0, ByteMask, ByteValues))
Chris Lattnerafe91a52006-06-15 19:07:26 +00002239 return 0;
2240
2241 // Check to see if all of the bytes come from the same value.
2242 Value *V = ByteValues[0];
2243 if (V == 0) return 0; // Didn't find a byte? Must be zero.
2244
2245 // Check to make sure that all of the bytes come from the same value.
2246 for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
2247 if (ByteValues[i] != V)
2248 return 0;
Chandler Carruth69940402007-08-04 01:51:18 +00002249 const Type *Tys[] = { ITy };
Chris Lattnerafe91a52006-06-15 19:07:26 +00002250 Module *M = I.getParent()->getParent()->getParent();
Chandler Carruth69940402007-08-04 01:51:18 +00002251 Function *F = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 1);
Gabor Greif051a9502008-04-06 20:25:17 +00002252 return CallInst::Create(F, V);
Chris Lattnerafe91a52006-06-15 19:07:26 +00002253}
2254
Chris Lattnerfaaf9512008-11-16 04:24:12 +00002255/// MatchSelectFromAndOr - We have an expression of the form (A&C)|(B&D). Check
2256/// If A is (cond?-1:0) and either B or D is ~(cond?-1,0) or (cond?0,-1), then
2257/// we can simplify this expression to "cond ? C : D or B".
2258static Instruction *MatchSelectFromAndOr(Value *A, Value *B,
Chris Lattner4de84762010-01-04 07:02:48 +00002259 Value *C, Value *D) {
Chris Lattnera6a474d2008-11-16 04:26:55 +00002260 // If A is not a select of -1/0, this cannot match.
Chris Lattner6046fb72008-11-16 04:46:19 +00002261 Value *Cond = 0;
Dan Gohman4ae51262009-08-12 16:23:25 +00002262 if (!match(A, m_SelectCst<-1, 0>(m_Value(Cond))))
Chris Lattnerfaaf9512008-11-16 04:24:12 +00002263 return 0;
2264
Chris Lattnera6a474d2008-11-16 04:26:55 +00002265 // ((cond?-1:0)&C) | (B&(cond?0:-1)) -> cond ? C : B.
Dan Gohman4ae51262009-08-12 16:23:25 +00002266 if (match(D, m_SelectCst<0, -1>(m_Specific(Cond))))
Chris Lattnera6a474d2008-11-16 04:26:55 +00002267 return SelectInst::Create(Cond, C, B);
Dan Gohman4ae51262009-08-12 16:23:25 +00002268 if (match(D, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond)))))
Chris Lattnera6a474d2008-11-16 04:26:55 +00002269 return SelectInst::Create(Cond, C, B);
2270 // ((cond?-1:0)&C) | ((cond?0:-1)&D) -> cond ? C : D.
Dan Gohman4ae51262009-08-12 16:23:25 +00002271 if (match(B, m_SelectCst<0, -1>(m_Specific(Cond))))
Chris Lattnera6a474d2008-11-16 04:26:55 +00002272 return SelectInst::Create(Cond, C, D);
Dan Gohman4ae51262009-08-12 16:23:25 +00002273 if (match(B, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond)))))
Chris Lattnera6a474d2008-11-16 04:26:55 +00002274 return SelectInst::Create(Cond, C, D);
Chris Lattnerfaaf9512008-11-16 04:24:12 +00002275 return 0;
2276}
Chris Lattnerafe91a52006-06-15 19:07:26 +00002277
Chris Lattner69d4ced2008-11-16 05:20:07 +00002278/// FoldOrOfICmps - Fold (icmp)|(icmp) if possible.
2279Instruction *InstCombiner::FoldOrOfICmps(Instruction &I,
2280 ICmpInst *LHS, ICmpInst *RHS) {
Chris Lattnera317e042010-01-05 06:59:49 +00002281 ICmpInst::Predicate LHSCC = LHS->getPredicate(), RHSCC = RHS->getPredicate();
2282
2283 // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
2284 if (PredicatesFoldable(LHSCC, RHSCC)) {
2285 if (LHS->getOperand(0) == RHS->getOperand(1) &&
2286 LHS->getOperand(1) == RHS->getOperand(0))
2287 LHS->swapOperands();
2288 if (LHS->getOperand(0) == RHS->getOperand(0) &&
2289 LHS->getOperand(1) == RHS->getOperand(1)) {
2290 Value *Op0 = LHS->getOperand(0), *Op1 = LHS->getOperand(1);
2291 unsigned Code = getICmpCode(LHS) | getICmpCode(RHS);
2292 bool isSigned = LHS->isSigned() || RHS->isSigned();
2293 Value *RV = getICmpValue(isSigned, Code, Op0, Op1);
2294 if (Instruction *I = dyn_cast<Instruction>(RV))
2295 return I;
2296 // Otherwise, it's a constant boolean value.
2297 return ReplaceInstUsesWith(I, RV);
2298 }
2299 }
Chris Lattner69d4ced2008-11-16 05:20:07 +00002300
2301 // This only handles icmp of constants: (icmp1 A, C1) | (icmp2 B, C2).
Chris Lattnera317e042010-01-05 06:59:49 +00002302 Value *Val = LHS->getOperand(0), *Val2 = RHS->getOperand(0);
2303 ConstantInt *LHSCst = dyn_cast<ConstantInt>(LHS->getOperand(1));
2304 ConstantInt *RHSCst = dyn_cast<ConstantInt>(RHS->getOperand(1));
2305 if (LHSCst == 0 || RHSCst == 0) return 0;
Chris Lattner3f40e232009-11-29 00:51:17 +00002306
Chris Lattner3f40e232009-11-29 00:51:17 +00002307 // (icmp ne A, 0) | (icmp ne B, 0) --> (icmp ne (A|B), 0)
2308 if (LHSCst == RHSCst && LHSCC == RHSCC &&
2309 LHSCC == ICmpInst::ICMP_NE && LHSCst->isZero()) {
2310 Value *NewOr = Builder->CreateOr(Val, Val2);
2311 return new ICmpInst(LHSCC, NewOr, LHSCst);
2312 }
Chris Lattner69d4ced2008-11-16 05:20:07 +00002313
2314 // From here on, we only handle:
2315 // (icmp1 A, C1) | (icmp2 A, C2) --> something simpler.
2316 if (Val != Val2) return 0;
2317
2318 // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
2319 if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
2320 RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
2321 LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
2322 RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
2323 return 0;
2324
2325 // We can't fold (ugt x, C) | (sgt x, C2).
2326 if (!PredicatesFoldable(LHSCC, RHSCC))
2327 return 0;
2328
2329 // Ensure that the larger constant is on the RHS.
2330 bool ShouldSwap;
Nick Lewycky4a134af2009-10-25 05:20:17 +00002331 if (CmpInst::isSigned(LHSCC) ||
Chris Lattner69d4ced2008-11-16 05:20:07 +00002332 (ICmpInst::isEquality(LHSCC) &&
Nick Lewycky4a134af2009-10-25 05:20:17 +00002333 CmpInst::isSigned(RHSCC)))
Chris Lattner69d4ced2008-11-16 05:20:07 +00002334 ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
2335 else
2336 ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
2337
2338 if (ShouldSwap) {
2339 std::swap(LHS, RHS);
2340 std::swap(LHSCst, RHSCst);
2341 std::swap(LHSCC, RHSCC);
2342 }
2343
2344 // At this point, we know we have have two icmp instructions
2345 // comparing a value against two constants and or'ing the result
2346 // together. Because of the above check, we know that we only have
2347 // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
Chris Lattnera317e042010-01-05 06:59:49 +00002348 // icmp folding check above), that the two constants are not
Chris Lattner69d4ced2008-11-16 05:20:07 +00002349 // equal.
2350 assert(LHSCst != RHSCst && "Compares not folded above?");
2351
2352 switch (LHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00002353 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00002354 case ICmpInst::ICMP_EQ:
2355 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00002356 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00002357 case ICmpInst::ICMP_EQ:
Dan Gohman186a6362009-08-12 16:04:34 +00002358 if (LHSCst == SubOne(RHSCst)) {
Owen Andersond672ecb2009-07-03 00:17:18 +00002359 // (X == 13 | X == 14) -> X-13 <u 2
Owen Andersonbaf3c402009-07-29 18:55:55 +00002360 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
Chris Lattner74381062009-08-30 07:44:24 +00002361 Value *Add = Builder->CreateAdd(Val, AddCST, Val->getName()+".off");
Dan Gohman186a6362009-08-12 16:04:34 +00002362 AddCST = ConstantExpr::getSub(AddOne(RHSCst), LHSCst);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00002363 return new ICmpInst(ICmpInst::ICMP_ULT, Add, AddCST);
Chris Lattner69d4ced2008-11-16 05:20:07 +00002364 }
2365 break; // (X == 13 | X == 15) -> no change
2366 case ICmpInst::ICMP_UGT: // (X == 13 | X u> 14) -> no change
2367 case ICmpInst::ICMP_SGT: // (X == 13 | X s> 14) -> no change
2368 break;
2369 case ICmpInst::ICMP_NE: // (X == 13 | X != 15) -> X != 15
2370 case ICmpInst::ICMP_ULT: // (X == 13 | X u< 15) -> X u< 15
2371 case ICmpInst::ICMP_SLT: // (X == 13 | X s< 15) -> X s< 15
2372 return ReplaceInstUsesWith(I, RHS);
2373 }
2374 break;
2375 case ICmpInst::ICMP_NE:
2376 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00002377 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00002378 case ICmpInst::ICMP_EQ: // (X != 13 | X == 15) -> X != 13
2379 case ICmpInst::ICMP_UGT: // (X != 13 | X u> 15) -> X != 13
2380 case ICmpInst::ICMP_SGT: // (X != 13 | X s> 15) -> X != 13
2381 return ReplaceInstUsesWith(I, LHS);
2382 case ICmpInst::ICMP_NE: // (X != 13 | X != 15) -> true
2383 case ICmpInst::ICMP_ULT: // (X != 13 | X u< 15) -> true
2384 case ICmpInst::ICMP_SLT: // (X != 13 | X s< 15) -> true
Chris Lattner4de84762010-01-04 07:02:48 +00002385 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getContext()));
Chris Lattner69d4ced2008-11-16 05:20:07 +00002386 }
2387 break;
2388 case ICmpInst::ICMP_ULT:
2389 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00002390 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00002391 case ICmpInst::ICMP_EQ: // (X u< 13 | X == 14) -> no change
2392 break;
2393 case ICmpInst::ICMP_UGT: // (X u< 13 | X u> 15) -> (X-13) u> 2
2394 // If RHSCst is [us]MAXINT, it is always false. Not handling
2395 // this can cause overflow.
2396 if (RHSCst->isMaxValue(false))
2397 return ReplaceInstUsesWith(I, LHS);
Dan Gohman186a6362009-08-12 16:04:34 +00002398 return InsertRangeTest(Val, LHSCst, AddOne(RHSCst),
Owen Andersond672ecb2009-07-03 00:17:18 +00002399 false, false, I);
Chris Lattner69d4ced2008-11-16 05:20:07 +00002400 case ICmpInst::ICMP_SGT: // (X u< 13 | X s> 15) -> no change
2401 break;
2402 case ICmpInst::ICMP_NE: // (X u< 13 | X != 15) -> X != 15
2403 case ICmpInst::ICMP_ULT: // (X u< 13 | X u< 15) -> X u< 15
2404 return ReplaceInstUsesWith(I, RHS);
2405 case ICmpInst::ICMP_SLT: // (X u< 13 | X s< 15) -> no change
2406 break;
2407 }
2408 break;
2409 case ICmpInst::ICMP_SLT:
2410 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00002411 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00002412 case ICmpInst::ICMP_EQ: // (X s< 13 | X == 14) -> no change
2413 break;
2414 case ICmpInst::ICMP_SGT: // (X s< 13 | X s> 15) -> (X-13) s> 2
2415 // If RHSCst is [us]MAXINT, it is always false. Not handling
2416 // this can cause overflow.
2417 if (RHSCst->isMaxValue(true))
2418 return ReplaceInstUsesWith(I, LHS);
Dan Gohman186a6362009-08-12 16:04:34 +00002419 return InsertRangeTest(Val, LHSCst, AddOne(RHSCst),
Owen Andersond672ecb2009-07-03 00:17:18 +00002420 true, false, I);
Chris Lattner69d4ced2008-11-16 05:20:07 +00002421 case ICmpInst::ICMP_UGT: // (X s< 13 | X u> 15) -> no change
2422 break;
2423 case ICmpInst::ICMP_NE: // (X s< 13 | X != 15) -> X != 15
2424 case ICmpInst::ICMP_SLT: // (X s< 13 | X s< 15) -> X s< 15
2425 return ReplaceInstUsesWith(I, RHS);
2426 case ICmpInst::ICMP_ULT: // (X s< 13 | X u< 15) -> no change
2427 break;
2428 }
2429 break;
2430 case ICmpInst::ICMP_UGT:
2431 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00002432 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00002433 case ICmpInst::ICMP_EQ: // (X u> 13 | X == 15) -> X u> 13
2434 case ICmpInst::ICMP_UGT: // (X u> 13 | X u> 15) -> X u> 13
2435 return ReplaceInstUsesWith(I, LHS);
2436 case ICmpInst::ICMP_SGT: // (X u> 13 | X s> 15) -> no change
2437 break;
2438 case ICmpInst::ICMP_NE: // (X u> 13 | X != 15) -> true
2439 case ICmpInst::ICMP_ULT: // (X u> 13 | X u< 15) -> true
Chris Lattner4de84762010-01-04 07:02:48 +00002440 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getContext()));
Chris Lattner69d4ced2008-11-16 05:20:07 +00002441 case ICmpInst::ICMP_SLT: // (X u> 13 | X s< 15) -> no change
2442 break;
2443 }
2444 break;
2445 case ICmpInst::ICMP_SGT:
2446 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00002447 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00002448 case ICmpInst::ICMP_EQ: // (X s> 13 | X == 15) -> X > 13
2449 case ICmpInst::ICMP_SGT: // (X s> 13 | X s> 15) -> X > 13
2450 return ReplaceInstUsesWith(I, LHS);
2451 case ICmpInst::ICMP_UGT: // (X s> 13 | X u> 15) -> no change
2452 break;
2453 case ICmpInst::ICMP_NE: // (X s> 13 | X != 15) -> true
2454 case ICmpInst::ICMP_SLT: // (X s> 13 | X s< 15) -> true
Chris Lattner4de84762010-01-04 07:02:48 +00002455 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getContext()));
Chris Lattner69d4ced2008-11-16 05:20:07 +00002456 case ICmpInst::ICMP_ULT: // (X s> 13 | X u< 15) -> no change
2457 break;
2458 }
2459 break;
2460 }
2461 return 0;
2462}
2463
Chris Lattner5414cc52009-07-23 05:46:22 +00002464Instruction *InstCombiner::FoldOrOfFCmps(Instruction &I, FCmpInst *LHS,
2465 FCmpInst *RHS) {
2466 if (LHS->getPredicate() == FCmpInst::FCMP_UNO &&
2467 RHS->getPredicate() == FCmpInst::FCMP_UNO &&
2468 LHS->getOperand(0)->getType() == RHS->getOperand(0)->getType()) {
2469 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
2470 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
2471 // If either of the constants are nans, then the whole thing returns
2472 // true.
2473 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Chris Lattner4de84762010-01-04 07:02:48 +00002474 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getContext()));
Chris Lattner5414cc52009-07-23 05:46:22 +00002475
2476 // Otherwise, no need to compare the two constants, compare the
2477 // rest.
Dan Gohman1c8a23c2009-08-25 23:17:54 +00002478 return new FCmpInst(FCmpInst::FCMP_UNO,
Chris Lattner5414cc52009-07-23 05:46:22 +00002479 LHS->getOperand(0), RHS->getOperand(0));
2480 }
2481
2482 // Handle vector zeros. This occurs because the canonical form of
2483 // "fcmp uno x,x" is "fcmp uno x, 0".
2484 if (isa<ConstantAggregateZero>(LHS->getOperand(1)) &&
2485 isa<ConstantAggregateZero>(RHS->getOperand(1)))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00002486 return new FCmpInst(FCmpInst::FCMP_UNO,
Chris Lattner5414cc52009-07-23 05:46:22 +00002487 LHS->getOperand(0), RHS->getOperand(0));
2488
2489 return 0;
2490 }
2491
2492 Value *Op0LHS = LHS->getOperand(0), *Op0RHS = LHS->getOperand(1);
2493 Value *Op1LHS = RHS->getOperand(0), *Op1RHS = RHS->getOperand(1);
2494 FCmpInst::Predicate Op0CC = LHS->getPredicate(), Op1CC = RHS->getPredicate();
2495
2496 if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
2497 // Swap RHS operands to match LHS.
2498 Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
2499 std::swap(Op1LHS, Op1RHS);
2500 }
2501 if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
2502 // Simplify (fcmp cc0 x, y) | (fcmp cc1 x, y).
2503 if (Op0CC == Op1CC)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00002504 return new FCmpInst((FCmpInst::Predicate)Op0CC,
Chris Lattner5414cc52009-07-23 05:46:22 +00002505 Op0LHS, Op0RHS);
2506 if (Op0CC == FCmpInst::FCMP_TRUE || Op1CC == FCmpInst::FCMP_TRUE)
Chris Lattner4de84762010-01-04 07:02:48 +00002507 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getContext()));
Chris Lattner5414cc52009-07-23 05:46:22 +00002508 if (Op0CC == FCmpInst::FCMP_FALSE)
2509 return ReplaceInstUsesWith(I, RHS);
2510 if (Op1CC == FCmpInst::FCMP_FALSE)
2511 return ReplaceInstUsesWith(I, LHS);
2512 bool Op0Ordered;
2513 bool Op1Ordered;
2514 unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
2515 unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
2516 if (Op0Ordered == Op1Ordered) {
2517 // If both are ordered or unordered, return a new fcmp with
2518 // or'ed predicates.
Chris Lattner4de84762010-01-04 07:02:48 +00002519 Value *RV = getFCmpValue(Op0Ordered, Op0Pred|Op1Pred, Op0LHS, Op0RHS);
Chris Lattner5414cc52009-07-23 05:46:22 +00002520 if (Instruction *I = dyn_cast<Instruction>(RV))
2521 return I;
2522 // Otherwise, it's a constant boolean value...
2523 return ReplaceInstUsesWith(I, RV);
2524 }
2525 }
2526 return 0;
2527}
2528
Bill Wendlinga698a472008-12-01 08:23:25 +00002529/// FoldOrWithConstants - This helper function folds:
2530///
Bill Wendlinga8bb13f2008-12-02 05:09:00 +00002531/// ((A | B) & C1) | (B & C2)
Bill Wendlinga698a472008-12-01 08:23:25 +00002532///
2533/// into:
2534///
Bill Wendlinga8bb13f2008-12-02 05:09:00 +00002535/// (A & C1) | B
Bill Wendlingd54d8602008-12-01 08:32:40 +00002536///
Bill Wendlinga8bb13f2008-12-02 05:09:00 +00002537/// when the XOR of the two constants is "all ones" (-1).
Bill Wendlingd54d8602008-12-01 08:32:40 +00002538Instruction *InstCombiner::FoldOrWithConstants(BinaryOperator &I, Value *Op,
Bill Wendlinga698a472008-12-01 08:23:25 +00002539 Value *A, Value *B, Value *C) {
Bill Wendlingdda74e02008-12-02 05:06:43 +00002540 ConstantInt *CI1 = dyn_cast<ConstantInt>(C);
2541 if (!CI1) return 0;
Bill Wendlinga698a472008-12-01 08:23:25 +00002542
Bill Wendling286a0542008-12-02 06:24:20 +00002543 Value *V1 = 0;
2544 ConstantInt *CI2 = 0;
Dan Gohman4ae51262009-08-12 16:23:25 +00002545 if (!match(Op, m_And(m_Value(V1), m_ConstantInt(CI2)))) return 0;
Bill Wendlinga698a472008-12-01 08:23:25 +00002546
Bill Wendling29976b92008-12-02 06:18:11 +00002547 APInt Xor = CI1->getValue() ^ CI2->getValue();
2548 if (!Xor.isAllOnesValue()) return 0;
2549
Bill Wendling286a0542008-12-02 06:24:20 +00002550 if (V1 == A || V1 == B) {
Chris Lattner74381062009-08-30 07:44:24 +00002551 Value *NewOp = Builder->CreateAnd((V1 == A) ? B : A, CI1);
Bill Wendlingd16c6e92008-12-02 06:22:04 +00002552 return BinaryOperator::CreateOr(NewOp, V1);
Bill Wendlinga698a472008-12-01 08:23:25 +00002553 }
2554
2555 return 0;
2556}
2557
Chris Lattner7e708292002-06-25 16:13:24 +00002558Instruction *InstCombiner::visitOr(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00002559 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00002560 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00002561
Chris Lattnerd06094f2009-11-10 00:55:12 +00002562 if (Value *V = SimplifyOrInst(Op0, Op1, TD))
2563 return ReplaceInstUsesWith(I, V);
2564
2565
Chris Lattnerf8c36f52006-02-12 08:02:11 +00002566 // See if we can simplify any instructions used by the instruction whose sole
2567 // purpose is to compute bits we don't care about.
Dan Gohman6de29f82009-06-15 22:12:54 +00002568 if (SimplifyDemandedInstructionBits(I))
2569 return &I;
Chris Lattner041a6c92007-06-15 05:26:55 +00002570
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002571 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner4f637d42006-01-06 17:59:59 +00002572 ConstantInt *C1 = 0; Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002573 // (X & C1) | C2 --> (X | C2) & (C1|C2)
Dan Gohman4ae51262009-08-12 16:23:25 +00002574 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00002575 isOnlyUse(Op0)) {
Chris Lattner74381062009-08-30 07:44:24 +00002576 Value *Or = Builder->CreateOr(X, RHS);
Chris Lattner6934a042007-02-11 01:23:03 +00002577 Or->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002578 return BinaryOperator::CreateAnd(Or,
Chris Lattner4de84762010-01-04 07:02:48 +00002579 ConstantInt::get(I.getContext(),
2580 RHS->getValue() | C1->getValue()));
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002581 }
Chris Lattnerad44ebf2003-07-23 18:29:44 +00002582
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002583 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
Dan Gohman4ae51262009-08-12 16:23:25 +00002584 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00002585 isOnlyUse(Op0)) {
Chris Lattner74381062009-08-30 07:44:24 +00002586 Value *Or = Builder->CreateOr(X, RHS);
Chris Lattner6934a042007-02-11 01:23:03 +00002587 Or->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002588 return BinaryOperator::CreateXor(Or,
Chris Lattner4de84762010-01-04 07:02:48 +00002589 ConstantInt::get(I.getContext(),
2590 C1->getValue() & ~RHS->getValue()));
Chris Lattnerad44ebf2003-07-23 18:29:44 +00002591 }
Chris Lattner2eefe512004-04-09 19:05:30 +00002592
2593 // Try to fold constant and into select arguments.
2594 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner80f43d32010-01-04 07:53:58 +00002595 if (Instruction *R = FoldOpIntoSelect(I, SI))
Chris Lattner2eefe512004-04-09 19:05:30 +00002596 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00002597 if (isa<PHINode>(Op0))
2598 if (Instruction *NV = FoldOpIntoPhi(I))
2599 return NV;
Chris Lattnerad44ebf2003-07-23 18:29:44 +00002600 }
2601
Chris Lattner4f637d42006-01-06 17:59:59 +00002602 Value *A = 0, *B = 0;
2603 ConstantInt *C1 = 0, *C2 = 0;
Chris Lattnerf4d4c872005-05-07 23:49:08 +00002604
Chris Lattner6423d4c2006-07-10 20:25:24 +00002605 // (A | B) | C and A | (B | C) -> bswap if possible.
2606 // (A >> B) | (C << D) and (A << B) | (B >> C) -> bswap if possible.
Dan Gohman4ae51262009-08-12 16:23:25 +00002607 if (match(Op0, m_Or(m_Value(), m_Value())) ||
2608 match(Op1, m_Or(m_Value(), m_Value())) ||
2609 (match(Op0, m_Shift(m_Value(), m_Value())) &&
2610 match(Op1, m_Shift(m_Value(), m_Value())))) {
Chris Lattnerafe91a52006-06-15 19:07:26 +00002611 if (Instruction *BSwap = MatchBSwap(I))
2612 return BSwap;
2613 }
2614
Chris Lattner6e4c6492005-05-09 04:58:36 +00002615 // (X^C)|Y -> (X|Y)^C iff Y&C == 0
Owen Andersonc7d2ce72009-07-10 17:35:01 +00002616 if (Op0->hasOneUse() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00002617 match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Reid Spencera03d45f2007-03-22 22:19:58 +00002618 MaskedValueIsZero(Op1, C1->getValue())) {
Chris Lattner74381062009-08-30 07:44:24 +00002619 Value *NOr = Builder->CreateOr(A, Op1);
Chris Lattner6934a042007-02-11 01:23:03 +00002620 NOr->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002621 return BinaryOperator::CreateXor(NOr, C1);
Chris Lattner6e4c6492005-05-09 04:58:36 +00002622 }
2623
2624 // Y|(X^C) -> (X|Y)^C iff Y&C == 0
Owen Andersonc7d2ce72009-07-10 17:35:01 +00002625 if (Op1->hasOneUse() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00002626 match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Reid Spencera03d45f2007-03-22 22:19:58 +00002627 MaskedValueIsZero(Op0, C1->getValue())) {
Chris Lattner74381062009-08-30 07:44:24 +00002628 Value *NOr = Builder->CreateOr(A, Op0);
Chris Lattner6934a042007-02-11 01:23:03 +00002629 NOr->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002630 return BinaryOperator::CreateXor(NOr, C1);
Chris Lattner6e4c6492005-05-09 04:58:36 +00002631 }
2632
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00002633 // (A & C)|(B & D)
Chris Lattner2384d7b2007-06-19 05:43:49 +00002634 Value *C = 0, *D = 0;
Dan Gohman4ae51262009-08-12 16:23:25 +00002635 if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
2636 match(Op1, m_And(m_Value(B), m_Value(D)))) {
Chris Lattner6cae0e02007-04-08 07:55:22 +00002637 Value *V1 = 0, *V2 = 0, *V3 = 0;
2638 C1 = dyn_cast<ConstantInt>(C);
2639 C2 = dyn_cast<ConstantInt>(D);
2640 if (C1 && C2) { // (A & C1)|(B & C2)
2641 // If we have: ((V + N) & C1) | (V & C2)
2642 // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
2643 // replace with V+N.
2644 if (C1->getValue() == ~C2->getValue()) {
2645 if ((C2->getValue() & (C2->getValue()+1)) == 0 && // C2 == 0+1+
Dan Gohman4ae51262009-08-12 16:23:25 +00002646 match(A, m_Add(m_Value(V1), m_Value(V2)))) {
Chris Lattner6cae0e02007-04-08 07:55:22 +00002647 // Add commutes, try both ways.
2648 if (V1 == B && MaskedValueIsZero(V2, C2->getValue()))
2649 return ReplaceInstUsesWith(I, A);
2650 if (V2 == B && MaskedValueIsZero(V1, C2->getValue()))
2651 return ReplaceInstUsesWith(I, A);
2652 }
2653 // Or commutes, try both ways.
2654 if ((C1->getValue() & (C1->getValue()+1)) == 0 &&
Dan Gohman4ae51262009-08-12 16:23:25 +00002655 match(B, m_Add(m_Value(V1), m_Value(V2)))) {
Chris Lattner6cae0e02007-04-08 07:55:22 +00002656 // Add commutes, try both ways.
2657 if (V1 == A && MaskedValueIsZero(V2, C1->getValue()))
2658 return ReplaceInstUsesWith(I, B);
2659 if (V2 == A && MaskedValueIsZero(V1, C1->getValue()))
2660 return ReplaceInstUsesWith(I, B);
2661 }
2662 }
Chris Lattnere4412c12010-01-04 06:03:59 +00002663
2664 // ((V | N) & C1) | (V & C2) --> (V|N) & (C1|C2)
2665 // iff (C1&C2) == 0 and (N&~C1) == 0
2666 if ((C1->getValue() & C2->getValue()) == 0) {
2667 if (match(A, m_Or(m_Value(V1), m_Value(V2))) &&
2668 ((V1 == B && MaskedValueIsZero(V2, ~C1->getValue())) || // (V|N)
2669 (V2 == B && MaskedValueIsZero(V1, ~C1->getValue())))) // (N|V)
2670 return BinaryOperator::CreateAnd(A,
2671 ConstantInt::get(A->getContext(),
2672 C1->getValue()|C2->getValue()));
2673 // Or commutes, try both ways.
2674 if (match(B, m_Or(m_Value(V1), m_Value(V2))) &&
2675 ((V1 == A && MaskedValueIsZero(V2, ~C2->getValue())) || // (V|N)
2676 (V2 == A && MaskedValueIsZero(V1, ~C2->getValue())))) // (N|V)
2677 return BinaryOperator::CreateAnd(B,
2678 ConstantInt::get(B->getContext(),
2679 C1->getValue()|C2->getValue()));
2680 }
Chris Lattner6cae0e02007-04-08 07:55:22 +00002681 }
2682
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00002683 // Check to see if we have any common things being and'ed. If so, find the
2684 // terms for V1 & (V2|V3).
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00002685 if (isOnlyUse(Op0) || isOnlyUse(Op1)) {
Chris Lattnere4412c12010-01-04 06:03:59 +00002686 V1 = 0;
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00002687 if (A == B) // (A & C)|(A & D) == A & (C|D)
2688 V1 = A, V2 = C, V3 = D;
2689 else if (A == D) // (A & C)|(B & A) == A & (B|C)
2690 V1 = A, V2 = B, V3 = C;
2691 else if (C == B) // (A & C)|(C & D) == C & (A|D)
2692 V1 = C, V2 = A, V3 = D;
2693 else if (C == D) // (A & C)|(B & C) == C & (A|B)
2694 V1 = C, V2 = A, V3 = B;
2695
2696 if (V1) {
Chris Lattner74381062009-08-30 07:44:24 +00002697 Value *Or = Builder->CreateOr(V2, V3, "tmp");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002698 return BinaryOperator::CreateAnd(V1, Or);
Chris Lattner0b7c0bf2005-09-18 06:02:59 +00002699 }
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00002700 }
Dan Gohmanb493b272008-10-28 22:38:57 +00002701
Dan Gohman1975d032008-10-30 20:40:10 +00002702 // (A & (C0?-1:0)) | (B & ~(C0?-1:0)) -> C0 ? A : B, and commuted variants
Chris Lattner4de84762010-01-04 07:02:48 +00002703 if (Instruction *Match = MatchSelectFromAndOr(A, B, C, D))
Chris Lattnerfaaf9512008-11-16 04:24:12 +00002704 return Match;
Chris Lattner4de84762010-01-04 07:02:48 +00002705 if (Instruction *Match = MatchSelectFromAndOr(B, A, D, C))
Chris Lattnerfaaf9512008-11-16 04:24:12 +00002706 return Match;
Chris Lattner4de84762010-01-04 07:02:48 +00002707 if (Instruction *Match = MatchSelectFromAndOr(C, B, A, D))
Chris Lattnerfaaf9512008-11-16 04:24:12 +00002708 return Match;
Chris Lattner4de84762010-01-04 07:02:48 +00002709 if (Instruction *Match = MatchSelectFromAndOr(D, A, B, C))
Chris Lattnerfaaf9512008-11-16 04:24:12 +00002710 return Match;
Bill Wendlingb01865c2008-11-30 13:52:49 +00002711
Bill Wendlingb01865c2008-11-30 13:52:49 +00002712 // ((A&~B)|(~A&B)) -> A^B
Dan Gohman4ae51262009-08-12 16:23:25 +00002713 if ((match(C, m_Not(m_Specific(D))) &&
2714 match(B, m_Not(m_Specific(A)))))
Bill Wendling03aae5f2008-12-01 08:09:47 +00002715 return BinaryOperator::CreateXor(A, D);
Bill Wendlingb01865c2008-11-30 13:52:49 +00002716 // ((~B&A)|(~A&B)) -> A^B
Dan Gohman4ae51262009-08-12 16:23:25 +00002717 if ((match(A, m_Not(m_Specific(D))) &&
2718 match(B, m_Not(m_Specific(C)))))
Bill Wendling03aae5f2008-12-01 08:09:47 +00002719 return BinaryOperator::CreateXor(C, D);
Bill Wendlingb01865c2008-11-30 13:52:49 +00002720 // ((A&~B)|(B&~A)) -> A^B
Dan Gohman4ae51262009-08-12 16:23:25 +00002721 if ((match(C, m_Not(m_Specific(B))) &&
2722 match(D, m_Not(m_Specific(A)))))
Bill Wendling03aae5f2008-12-01 08:09:47 +00002723 return BinaryOperator::CreateXor(A, B);
Bill Wendlingb01865c2008-11-30 13:52:49 +00002724 // ((~B&A)|(B&~A)) -> A^B
Dan Gohman4ae51262009-08-12 16:23:25 +00002725 if ((match(A, m_Not(m_Specific(B))) &&
2726 match(D, m_Not(m_Specific(C)))))
Bill Wendling03aae5f2008-12-01 08:09:47 +00002727 return BinaryOperator::CreateXor(C, B);
Chris Lattnere9bed7d2005-09-18 03:42:07 +00002728 }
Chris Lattnere511b742006-11-14 07:46:50 +00002729
2730 // (X >> Z) | (Y >> Z) -> (X|Y) >> Z for all shifts.
Reid Spencer832254e2007-02-02 02:16:23 +00002731 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
2732 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
2733 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
Chris Lattnere511b742006-11-14 07:46:50 +00002734 SI0->getOperand(1) == SI1->getOperand(1) &&
2735 (SI0->hasOneUse() || SI1->hasOneUse())) {
Chris Lattner74381062009-08-30 07:44:24 +00002736 Value *NewOp = Builder->CreateOr(SI0->getOperand(0), SI1->getOperand(0),
2737 SI0->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002738 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
Reid Spencer832254e2007-02-02 02:16:23 +00002739 SI1->getOperand(1));
Chris Lattnere511b742006-11-14 07:46:50 +00002740 }
2741 }
Chris Lattner67ca7682003-08-12 19:11:07 +00002742
Bill Wendlingb3833d12008-12-01 01:07:11 +00002743 // ((A|B)&1)|(B&-2) -> (A&1) | B
Dan Gohman4ae51262009-08-12 16:23:25 +00002744 if (match(Op0, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C))) ||
2745 match(Op0, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))))) {
Bill Wendlingd54d8602008-12-01 08:32:40 +00002746 Instruction *Ret = FoldOrWithConstants(I, Op1, A, B, C);
Bill Wendlinga698a472008-12-01 08:23:25 +00002747 if (Ret) return Ret;
Bill Wendlingb3833d12008-12-01 01:07:11 +00002748 }
2749 // (B&-2)|((A|B)&1) -> (A&1) | B
Dan Gohman4ae51262009-08-12 16:23:25 +00002750 if (match(Op1, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C))) ||
2751 match(Op1, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))))) {
Bill Wendlingd54d8602008-12-01 08:32:40 +00002752 Instruction *Ret = FoldOrWithConstants(I, Op0, A, B, C);
Bill Wendlinga698a472008-12-01 08:23:25 +00002753 if (Ret) return Ret;
Bill Wendlingb3833d12008-12-01 01:07:11 +00002754 }
2755
Chris Lattnerd06094f2009-11-10 00:55:12 +00002756 // (~A | ~B) == (~(A & B)) - De Morgan's Law
2757 if (Value *Op0NotVal = dyn_castNotVal(Op0))
2758 if (Value *Op1NotVal = dyn_castNotVal(Op1))
2759 if (Op0->hasOneUse() && Op1->hasOneUse()) {
2760 Value *And = Builder->CreateAnd(Op0NotVal, Op1NotVal,
2761 I.getName()+".demorgan");
2762 return BinaryOperator::CreateNot(And);
2763 }
Chris Lattnera2881962003-02-18 19:28:33 +00002764
Chris Lattnera317e042010-01-05 06:59:49 +00002765 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
Chris Lattner69d4ced2008-11-16 05:20:07 +00002766 if (ICmpInst *LHS = dyn_cast<ICmpInst>(I.getOperand(0)))
2767 if (Instruction *Res = FoldOrOfICmps(I, LHS, RHS))
2768 return Res;
Chris Lattner6fc205f2006-05-05 06:39:07 +00002769
2770 // fold (or (cast A), (cast B)) -> (cast (or A, B))
Chris Lattner99c65742007-10-24 05:38:08 +00002771 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Chris Lattner6fc205f2006-05-05 06:39:07 +00002772 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00002773 if (Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
Evan Chengb98a10e2008-03-24 00:21:34 +00002774 if (!isa<ICmpInst>(Op0C->getOperand(0)) ||
2775 !isa<ICmpInst>(Op1C->getOperand(0))) {
2776 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattnerf98d2532009-07-23 05:32:17 +00002777 if (SrcTy == Op1C->getOperand(0)->getType() &&
2778 SrcTy->isIntOrIntVector() &&
Evan Chengb98a10e2008-03-24 00:21:34 +00002779 // Only do this if the casts both really cause code to be
2780 // generated.
2781 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
Chris Lattner80f43d32010-01-04 07:53:58 +00002782 I.getType()) &&
Evan Chengb98a10e2008-03-24 00:21:34 +00002783 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
Chris Lattner80f43d32010-01-04 07:53:58 +00002784 I.getType())) {
Chris Lattner74381062009-08-30 07:44:24 +00002785 Value *NewOp = Builder->CreateOr(Op0C->getOperand(0),
2786 Op1C->getOperand(0), I.getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002787 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Evan Chengb98a10e2008-03-24 00:21:34 +00002788 }
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00002789 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00002790 }
Chris Lattner99c65742007-10-24 05:38:08 +00002791 }
2792
2793
2794 // (fcmp uno x, c) | (fcmp uno y, c) -> (fcmp uno x, y)
2795 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
Chris Lattner5414cc52009-07-23 05:46:22 +00002796 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
2797 if (Instruction *Res = FoldOrOfFCmps(I, LHS, RHS))
2798 return Res;
Chris Lattner99c65742007-10-24 05:38:08 +00002799 }
Chris Lattnere9bed7d2005-09-18 03:42:07 +00002800
Chris Lattner7e708292002-06-25 16:13:24 +00002801 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00002802}
2803
Dan Gohman844731a2008-05-13 00:00:25 +00002804namespace {
2805
Chris Lattnerc317d392004-02-16 01:20:27 +00002806// XorSelf - Implements: X ^ X --> 0
2807struct XorSelf {
2808 Value *RHS;
2809 XorSelf(Value *rhs) : RHS(rhs) {}
2810 bool shouldApply(Value *LHS) const { return LHS == RHS; }
2811 Instruction *apply(BinaryOperator &Xor) const {
2812 return &Xor;
2813 }
2814};
Chris Lattner3f5b8772002-05-06 16:14:14 +00002815
Dan Gohman844731a2008-05-13 00:00:25 +00002816}
Chris Lattner3f5b8772002-05-06 16:14:14 +00002817
Chris Lattner7e708292002-06-25 16:13:24 +00002818Instruction *InstCombiner::visitXor(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00002819 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00002820 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00002821
Evan Chengd34af782008-03-25 20:07:13 +00002822 if (isa<UndefValue>(Op1)) {
2823 if (isa<UndefValue>(Op0))
2824 // Handle undef ^ undef -> 0 special case. This is a common
2825 // idiom (misuse).
Owen Andersona7235ea2009-07-31 20:28:14 +00002826 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00002827 return ReplaceInstUsesWith(I, Op1); // X ^ undef -> undef
Evan Chengd34af782008-03-25 20:07:13 +00002828 }
Chris Lattnere87597f2004-10-16 18:11:37 +00002829
Chris Lattnerc317d392004-02-16 01:20:27 +00002830 // xor X, X = 0, even if X is nested in a sequence of Xor's.
Dan Gohman186a6362009-08-12 16:04:34 +00002831 if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
Chris Lattnera9ff5eb2007-08-05 08:47:58 +00002832 assert(Result == &I && "AssociativeOpt didn't work?"); Result=Result;
Owen Andersona7235ea2009-07-31 20:28:14 +00002833 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerc317d392004-02-16 01:20:27 +00002834 }
Chris Lattnerf8c36f52006-02-12 08:02:11 +00002835
2836 // See if we can simplify any instructions used by the instruction whose sole
2837 // purpose is to compute bits we don't care about.
Dan Gohman6de29f82009-06-15 22:12:54 +00002838 if (SimplifyDemandedInstructionBits(I))
2839 return &I;
2840 if (isa<VectorType>(I.getType()))
2841 if (isa<ConstantAggregateZero>(Op1))
2842 return ReplaceInstUsesWith(I, Op0); // X ^ <0,0> -> X
Chris Lattner3f5b8772002-05-06 16:14:14 +00002843
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00002844 // Is this a ~ operation?
Dan Gohman186a6362009-08-12 16:04:34 +00002845 if (Value *NotOp = dyn_castNotVal(&I)) {
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00002846 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(NotOp)) {
2847 if (Op0I->getOpcode() == Instruction::And ||
2848 Op0I->getOpcode() == Instruction::Or) {
Chris Lattner48b59ec2009-10-26 15:40:07 +00002849 // ~(~X & Y) --> (X | ~Y) - De Morgan's Law
2850 // ~(~X | Y) === (X & ~Y) - De Morgan's Law
2851 if (dyn_castNotVal(Op0I->getOperand(1)))
2852 Op0I->swapOperands();
Dan Gohman186a6362009-08-12 16:04:34 +00002853 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
Chris Lattner74381062009-08-30 07:44:24 +00002854 Value *NotY =
2855 Builder->CreateNot(Op0I->getOperand(1),
2856 Op0I->getOperand(1)->getName()+".not");
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00002857 if (Op0I->getOpcode() == Instruction::And)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002858 return BinaryOperator::CreateOr(Op0NotVal, NotY);
Chris Lattner74381062009-08-30 07:44:24 +00002859 return BinaryOperator::CreateAnd(Op0NotVal, NotY);
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00002860 }
Chris Lattner48b59ec2009-10-26 15:40:07 +00002861
2862 // ~(X & Y) --> (~X | ~Y) - De Morgan's Law
2863 // ~(X | Y) === (~X & ~Y) - De Morgan's Law
2864 if (isFreeToInvert(Op0I->getOperand(0)) &&
2865 isFreeToInvert(Op0I->getOperand(1))) {
2866 Value *NotX =
2867 Builder->CreateNot(Op0I->getOperand(0), "notlhs");
2868 Value *NotY =
2869 Builder->CreateNot(Op0I->getOperand(1), "notrhs");
2870 if (Op0I->getOpcode() == Instruction::And)
2871 return BinaryOperator::CreateOr(NotX, NotY);
2872 return BinaryOperator::CreateAnd(NotX, NotY);
2873 }
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00002874 }
2875 }
2876 }
2877
2878
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002879 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner7acdf1d2009-10-11 22:00:32 +00002880 if (RHS->isOne() && Op0->hasOneUse()) {
Bill Wendling3479be92009-01-01 01:18:23 +00002881 // xor (cmp A, B), true = not (cmp A, B) = !cmp A, B
Nick Lewyckyf947b3e2007-08-06 20:04:16 +00002882 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Op0))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00002883 return new ICmpInst(ICI->getInversePredicate(),
Reid Spencere4d87aa2006-12-23 06:05:41 +00002884 ICI->getOperand(0), ICI->getOperand(1));
Chris Lattnerad5b4fb2003-11-04 23:50:51 +00002885
Nick Lewyckyf947b3e2007-08-06 20:04:16 +00002886 if (FCmpInst *FCI = dyn_cast<FCmpInst>(Op0))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00002887 return new FCmpInst(FCI->getInversePredicate(),
Nick Lewyckyf947b3e2007-08-06 20:04:16 +00002888 FCI->getOperand(0), FCI->getOperand(1));
2889 }
2890
Nick Lewycky517e1f52008-05-31 19:01:33 +00002891 // fold (xor(zext(cmp)), 1) and (xor(sext(cmp)), -1) to ext(!cmp).
2892 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
2893 if (CmpInst *CI = dyn_cast<CmpInst>(Op0C->getOperand(0))) {
2894 if (CI->hasOneUse() && Op0C->hasOneUse()) {
2895 Instruction::CastOps Opcode = Op0C->getOpcode();
Chris Lattner74381062009-08-30 07:44:24 +00002896 if ((Opcode == Instruction::ZExt || Opcode == Instruction::SExt) &&
2897 (RHS == ConstantExpr::getCast(Opcode,
Chris Lattner4de84762010-01-04 07:02:48 +00002898 ConstantInt::getTrue(I.getContext()),
Chris Lattner74381062009-08-30 07:44:24 +00002899 Op0C->getDestTy()))) {
2900 CI->setPredicate(CI->getInversePredicate());
2901 return CastInst::Create(Opcode, CI, Op0C->getType());
Nick Lewycky517e1f52008-05-31 19:01:33 +00002902 }
2903 }
2904 }
2905 }
2906
Reid Spencere4d87aa2006-12-23 06:05:41 +00002907 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Chris Lattnerd65460f2003-11-05 01:06:05 +00002908 // ~(c-X) == X-c-1 == X+(-c-1)
Chris Lattner7c4049c2004-01-12 19:35:11 +00002909 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
2910 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00002911 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
2912 Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
Owen Andersoneed707b2009-07-24 23:12:02 +00002913 ConstantInt::get(I.getType(), 1));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002914 return BinaryOperator::CreateAdd(Op0I->getOperand(1), ConstantRHS);
Chris Lattner7c4049c2004-01-12 19:35:11 +00002915 }
Chris Lattner5c6e2db2007-04-02 05:36:22 +00002916
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00002917 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
Chris Lattnerf8c36f52006-02-12 08:02:11 +00002918 if (Op0I->getOpcode() == Instruction::Add) {
Chris Lattner689d24b2003-11-04 23:37:10 +00002919 // ~(X-c) --> (-c-1)-X
Chris Lattner7c4049c2004-01-12 19:35:11 +00002920 if (RHS->isAllOnesValue()) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00002921 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002922 return BinaryOperator::CreateSub(
Owen Andersonbaf3c402009-07-29 18:55:55 +00002923 ConstantExpr::getSub(NegOp0CI,
Owen Andersoneed707b2009-07-24 23:12:02 +00002924 ConstantInt::get(I.getType(), 1)),
Owen Andersond672ecb2009-07-03 00:17:18 +00002925 Op0I->getOperand(0));
Chris Lattneracf4e072007-04-02 05:42:22 +00002926 } else if (RHS->getValue().isSignBit()) {
Chris Lattner5c6e2db2007-04-02 05:36:22 +00002927 // (X + C) ^ signbit -> (X + C + signbit)
Chris Lattner4de84762010-01-04 07:02:48 +00002928 Constant *C = ConstantInt::get(I.getContext(),
Owen Andersoneed707b2009-07-24 23:12:02 +00002929 RHS->getValue() + Op0CI->getValue());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002930 return BinaryOperator::CreateAdd(Op0I->getOperand(0), C);
Chris Lattnercd1d6d52007-04-02 05:48:58 +00002931
Chris Lattner7c4049c2004-01-12 19:35:11 +00002932 }
Chris Lattner02bd1b32006-02-26 19:57:54 +00002933 } else if (Op0I->getOpcode() == Instruction::Or) {
2934 // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
Reid Spencera03d45f2007-03-22 22:19:58 +00002935 if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue())) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00002936 Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
Chris Lattner02bd1b32006-02-26 19:57:54 +00002937 // Anything in both C1 and C2 is known to be zero, remove it from
2938 // NewRHS.
Owen Andersonbaf3c402009-07-29 18:55:55 +00002939 Constant *CommonBits = ConstantExpr::getAnd(Op0CI, RHS);
2940 NewRHS = ConstantExpr::getAnd(NewRHS,
2941 ConstantExpr::getNot(CommonBits));
Chris Lattner7a1e9242009-08-30 06:13:40 +00002942 Worklist.Add(Op0I);
Chris Lattner02bd1b32006-02-26 19:57:54 +00002943 I.setOperand(0, Op0I->getOperand(0));
2944 I.setOperand(1, NewRHS);
2945 return &I;
2946 }
Chris Lattnereca0c5c2003-07-23 21:37:07 +00002947 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00002948 }
Chris Lattner05bd1b22002-08-20 18:24:26 +00002949 }
Chris Lattner2eefe512004-04-09 19:05:30 +00002950
2951 // Try to fold constant and into select arguments.
2952 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner80f43d32010-01-04 07:53:58 +00002953 if (Instruction *R = FoldOpIntoSelect(I, SI))
Chris Lattner2eefe512004-04-09 19:05:30 +00002954 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00002955 if (isa<PHINode>(Op0))
2956 if (Instruction *NV = FoldOpIntoPhi(I))
2957 return NV;
Chris Lattner3f5b8772002-05-06 16:14:14 +00002958 }
2959
Dan Gohman186a6362009-08-12 16:04:34 +00002960 if (Value *X = dyn_castNotVal(Op0)) // ~A ^ A == -1
Chris Lattnera2881962003-02-18 19:28:33 +00002961 if (X == Op1)
Owen Andersona7235ea2009-07-31 20:28:14 +00002962 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00002963
Dan Gohman186a6362009-08-12 16:04:34 +00002964 if (Value *X = dyn_castNotVal(Op1)) // A ^ ~A == -1
Chris Lattnera2881962003-02-18 19:28:33 +00002965 if (X == Op0)
Owen Andersona7235ea2009-07-31 20:28:14 +00002966 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00002967
Chris Lattner318bf792007-03-18 22:51:34 +00002968
2969 BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1);
2970 if (Op1I) {
2971 Value *A, *B;
Dan Gohman4ae51262009-08-12 16:23:25 +00002972 if (match(Op1I, m_Or(m_Value(A), m_Value(B)))) {
Chris Lattner318bf792007-03-18 22:51:34 +00002973 if (A == Op0) { // B^(B|A) == (A|B)^B
Chris Lattner64daab52006-04-01 08:03:55 +00002974 Op1I->swapOperands();
Chris Lattnercb40a372003-03-10 18:24:17 +00002975 I.swapOperands();
2976 std::swap(Op0, Op1);
Chris Lattner318bf792007-03-18 22:51:34 +00002977 } else if (B == Op0) { // B^(A|B) == (A|B)^B
Chris Lattner64daab52006-04-01 08:03:55 +00002978 I.swapOperands(); // Simplified below.
Chris Lattnercb40a372003-03-10 18:24:17 +00002979 std::swap(Op0, Op1);
Misha Brukmanfd939082005-04-21 23:48:37 +00002980 }
Dan Gohman4ae51262009-08-12 16:23:25 +00002981 } else if (match(Op1I, m_Xor(m_Specific(Op0), m_Value(B)))) {
Chris Lattnercb504b92008-11-16 05:38:51 +00002982 return ReplaceInstUsesWith(I, B); // A^(A^B) == B
Dan Gohman4ae51262009-08-12 16:23:25 +00002983 } else if (match(Op1I, m_Xor(m_Value(A), m_Specific(Op0)))) {
Chris Lattnercb504b92008-11-16 05:38:51 +00002984 return ReplaceInstUsesWith(I, A); // A^(B^A) == B
Dan Gohman4ae51262009-08-12 16:23:25 +00002985 } else if (match(Op1I, m_And(m_Value(A), m_Value(B))) &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00002986 Op1I->hasOneUse()){
Chris Lattner6abbdf92007-04-01 05:36:37 +00002987 if (A == Op0) { // A^(A&B) -> A^(B&A)
Chris Lattner64daab52006-04-01 08:03:55 +00002988 Op1I->swapOperands();
Chris Lattner6abbdf92007-04-01 05:36:37 +00002989 std::swap(A, B);
2990 }
Chris Lattner318bf792007-03-18 22:51:34 +00002991 if (B == Op0) { // A^(B&A) -> (B&A)^A
Chris Lattner64daab52006-04-01 08:03:55 +00002992 I.swapOperands(); // Simplified below.
2993 std::swap(Op0, Op1);
2994 }
Chris Lattner26ca7e12004-02-16 03:54:20 +00002995 }
Chris Lattner318bf792007-03-18 22:51:34 +00002996 }
2997
2998 BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0);
2999 if (Op0I) {
3000 Value *A, *B;
Dan Gohman4ae51262009-08-12 16:23:25 +00003001 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00003002 Op0I->hasOneUse()) {
Chris Lattner318bf792007-03-18 22:51:34 +00003003 if (A == Op1) // (B|A)^B == (A|B)^B
3004 std::swap(A, B);
Chris Lattner74381062009-08-30 07:44:24 +00003005 if (B == Op1) // (A|B)^B == A & ~B
3006 return BinaryOperator::CreateAnd(A, Builder->CreateNot(Op1, "tmp"));
Dan Gohman4ae51262009-08-12 16:23:25 +00003007 } else if (match(Op0I, m_Xor(m_Specific(Op1), m_Value(B)))) {
Chris Lattnercb504b92008-11-16 05:38:51 +00003008 return ReplaceInstUsesWith(I, B); // (A^B)^A == B
Dan Gohman4ae51262009-08-12 16:23:25 +00003009 } else if (match(Op0I, m_Xor(m_Value(A), m_Specific(Op1)))) {
Chris Lattnercb504b92008-11-16 05:38:51 +00003010 return ReplaceInstUsesWith(I, A); // (B^A)^A == B
Dan Gohman4ae51262009-08-12 16:23:25 +00003011 } else if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00003012 Op0I->hasOneUse()){
Chris Lattner318bf792007-03-18 22:51:34 +00003013 if (A == Op1) // (A&B)^A -> (B&A)^A
3014 std::swap(A, B);
3015 if (B == Op1 && // (B&A)^A == ~B & A
Chris Lattnerae1ab392006-04-01 22:05:01 +00003016 !isa<ConstantInt>(Op1)) { // Canonical form is (B&C)^C
Chris Lattner74381062009-08-30 07:44:24 +00003017 return BinaryOperator::CreateAnd(Builder->CreateNot(A, "tmp"), Op1);
Chris Lattner64daab52006-04-01 08:03:55 +00003018 }
Chris Lattnercb40a372003-03-10 18:24:17 +00003019 }
Chris Lattner318bf792007-03-18 22:51:34 +00003020 }
3021
3022 // (X >> Z) ^ (Y >> Z) -> (X^Y) >> Z for all shifts.
3023 if (Op0I && Op1I && Op0I->isShift() &&
3024 Op0I->getOpcode() == Op1I->getOpcode() &&
3025 Op0I->getOperand(1) == Op1I->getOperand(1) &&
3026 (Op1I->hasOneUse() || Op1I->hasOneUse())) {
Chris Lattner74381062009-08-30 07:44:24 +00003027 Value *NewOp =
3028 Builder->CreateXor(Op0I->getOperand(0), Op1I->getOperand(0),
3029 Op0I->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003030 return BinaryOperator::Create(Op1I->getOpcode(), NewOp,
Chris Lattner318bf792007-03-18 22:51:34 +00003031 Op1I->getOperand(1));
3032 }
3033
3034 if (Op0I && Op1I) {
3035 Value *A, *B, *C, *D;
3036 // (A & B)^(A | B) -> A ^ B
Dan Gohman4ae51262009-08-12 16:23:25 +00003037 if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
3038 match(Op1I, m_Or(m_Value(C), m_Value(D)))) {
Chris Lattner318bf792007-03-18 22:51:34 +00003039 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003040 return BinaryOperator::CreateXor(A, B);
Chris Lattner318bf792007-03-18 22:51:34 +00003041 }
3042 // (A | B)^(A & B) -> A ^ B
Dan Gohman4ae51262009-08-12 16:23:25 +00003043 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
3044 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
Chris Lattner318bf792007-03-18 22:51:34 +00003045 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003046 return BinaryOperator::CreateXor(A, B);
Chris Lattner318bf792007-03-18 22:51:34 +00003047 }
3048
3049 // (A & B)^(C & D)
3050 if ((Op0I->hasOneUse() || Op1I->hasOneUse()) &&
Dan Gohman4ae51262009-08-12 16:23:25 +00003051 match(Op0I, m_And(m_Value(A), m_Value(B))) &&
3052 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
Chris Lattner318bf792007-03-18 22:51:34 +00003053 // (X & Y)^(X & Y) -> (Y^Z) & X
3054 Value *X = 0, *Y = 0, *Z = 0;
3055 if (A == C)
3056 X = A, Y = B, Z = D;
3057 else if (A == D)
3058 X = A, Y = B, Z = C;
3059 else if (B == C)
3060 X = B, Y = A, Z = D;
3061 else if (B == D)
3062 X = B, Y = A, Z = C;
3063
3064 if (X) {
Chris Lattner74381062009-08-30 07:44:24 +00003065 Value *NewOp = Builder->CreateXor(Y, Z, Op0->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003066 return BinaryOperator::CreateAnd(NewOp, X);
Chris Lattner318bf792007-03-18 22:51:34 +00003067 }
3068 }
3069 }
3070
Reid Spencere4d87aa2006-12-23 06:05:41 +00003071 // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
3072 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
Chris Lattnera317e042010-01-05 06:59:49 +00003073 if (ICmpInst *LHS = dyn_cast<ICmpInst>(I.getOperand(0)))
3074 if (PredicatesFoldable(LHS->getPredicate(), RHS->getPredicate())) {
3075 if (LHS->getOperand(0) == RHS->getOperand(1) &&
3076 LHS->getOperand(1) == RHS->getOperand(0))
3077 LHS->swapOperands();
3078 if (LHS->getOperand(0) == RHS->getOperand(0) &&
3079 LHS->getOperand(1) == RHS->getOperand(1)) {
3080 Value *Op0 = LHS->getOperand(0), *Op1 = LHS->getOperand(1);
3081 unsigned Code = getICmpCode(LHS) ^ getICmpCode(RHS);
3082 bool isSigned = LHS->isSigned() || RHS->isSigned();
3083 Value *RV = getICmpValue(isSigned, Code, Op0, Op1);
3084 if (Instruction *I = dyn_cast<Instruction>(RV))
3085 return I;
3086 // Otherwise, it's a constant boolean value.
3087 return ReplaceInstUsesWith(I, RV);
3088 }
3089 }
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003090
Chris Lattner6fc205f2006-05-05 06:39:07 +00003091 // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
Chris Lattner99c65742007-10-24 05:38:08 +00003092 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Chris Lattner6fc205f2006-05-05 06:39:07 +00003093 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00003094 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
3095 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner42a75512007-01-15 02:27:26 +00003096 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00003097 // Only do this if the casts both really cause code to be generated.
Reid Spencere4d87aa2006-12-23 06:05:41 +00003098 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
Chris Lattner80f43d32010-01-04 07:53:58 +00003099 I.getType()) &&
Reid Spencere4d87aa2006-12-23 06:05:41 +00003100 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
Chris Lattner80f43d32010-01-04 07:53:58 +00003101 I.getType())) {
Chris Lattner74381062009-08-30 07:44:24 +00003102 Value *NewOp = Builder->CreateXor(Op0C->getOperand(0),
3103 Op1C->getOperand(0), I.getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003104 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00003105 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00003106 }
Chris Lattner99c65742007-10-24 05:38:08 +00003107 }
Nick Lewycky517e1f52008-05-31 19:01:33 +00003108
Chris Lattner7e708292002-06-25 16:13:24 +00003109 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00003110}
3111
Chris Lattner3f5b8772002-05-06 16:14:14 +00003112
Reid Spencer832254e2007-02-02 02:16:23 +00003113Instruction *InstCombiner::visitShl(BinaryOperator &I) {
3114 return commonShiftTransforms(I);
3115}
3116
3117Instruction *InstCombiner::visitLShr(BinaryOperator &I) {
3118 return commonShiftTransforms(I);
3119}
3120
3121Instruction *InstCombiner::visitAShr(BinaryOperator &I) {
Chris Lattner348f6652007-12-06 01:59:46 +00003122 if (Instruction *R = commonShiftTransforms(I))
3123 return R;
3124
3125 Value *Op0 = I.getOperand(0);
3126
3127 // ashr int -1, X = -1 (for any arithmetic shift rights of ~0)
3128 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
3129 if (CSI->isAllOnesValue())
3130 return ReplaceInstUsesWith(I, CSI);
Dan Gohman0001e562009-02-24 02:00:40 +00003131
Dan Gohmanc6ac3222009-06-16 19:55:29 +00003132 // See if we can turn a signed shr into an unsigned shr.
3133 if (MaskedValueIsZero(Op0,
3134 APInt::getSignBit(I.getType()->getScalarSizeInBits())))
3135 return BinaryOperator::CreateLShr(Op0, I.getOperand(1));
3136
3137 // Arithmetic shifting an all-sign-bit value is a no-op.
3138 unsigned NumSignBits = ComputeNumSignBits(Op0);
3139 if (NumSignBits == Op0->getType()->getScalarSizeInBits())
3140 return ReplaceInstUsesWith(I, Op0);
Dan Gohman0001e562009-02-24 02:00:40 +00003141
Chris Lattner348f6652007-12-06 01:59:46 +00003142 return 0;
Reid Spencer832254e2007-02-02 02:16:23 +00003143}
3144
3145Instruction *InstCombiner::commonShiftTransforms(BinaryOperator &I) {
3146 assert(I.getOperand(1)->getType() == I.getOperand(0)->getType());
Chris Lattner7e708292002-06-25 16:13:24 +00003147 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00003148
3149 // shl X, 0 == X and shr X, 0 == X
3150 // shl 0, X == 0 and shr 0, X == 0
Owen Andersona7235ea2009-07-31 20:28:14 +00003151 if (Op1 == Constant::getNullValue(Op1->getType()) ||
3152 Op0 == Constant::getNullValue(Op0->getType()))
Chris Lattner233f7dc2002-08-12 21:17:25 +00003153 return ReplaceInstUsesWith(I, Op0);
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00003154
Reid Spencere4d87aa2006-12-23 06:05:41 +00003155 if (isa<UndefValue>(Op0)) {
3156 if (I.getOpcode() == Instruction::AShr) // undef >>s X -> undef
Chris Lattner79a564c2004-10-16 23:28:04 +00003157 return ReplaceInstUsesWith(I, Op0);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003158 else // undef << X -> 0, undef >>u X -> 0
Owen Andersona7235ea2009-07-31 20:28:14 +00003159 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00003160 }
3161 if (isa<UndefValue>(Op1)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00003162 if (I.getOpcode() == Instruction::AShr) // X >>s undef -> X
3163 return ReplaceInstUsesWith(I, Op0);
3164 else // X << undef, X >>u undef -> 0
Owen Andersona7235ea2009-07-31 20:28:14 +00003165 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00003166 }
3167
Dan Gohman9004c8a2009-05-21 02:28:33 +00003168 // See if we can fold away this shift.
Dan Gohman6de29f82009-06-15 22:12:54 +00003169 if (SimplifyDemandedInstructionBits(I))
Dan Gohman9004c8a2009-05-21 02:28:33 +00003170 return &I;
3171
Chris Lattner2eefe512004-04-09 19:05:30 +00003172 // Try to fold constant and into select arguments.
3173 if (isa<Constant>(Op0))
3174 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner80f43d32010-01-04 07:53:58 +00003175 if (Instruction *R = FoldOpIntoSelect(I, SI))
Chris Lattner2eefe512004-04-09 19:05:30 +00003176 return R;
3177
Reid Spencerb83eb642006-10-20 07:07:24 +00003178 if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
Reid Spencerc5b206b2006-12-31 05:48:39 +00003179 if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
3180 return Res;
Chris Lattner4d5542c2006-01-06 07:12:35 +00003181 return 0;
3182}
3183
Reid Spencerb83eb642006-10-20 07:07:24 +00003184Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
Reid Spencer832254e2007-02-02 02:16:23 +00003185 BinaryOperator &I) {
Chris Lattner4598c942009-01-31 08:24:16 +00003186 bool isLeftShift = I.getOpcode() == Instruction::Shl;
Chris Lattner4d5542c2006-01-06 07:12:35 +00003187
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00003188 // See if we can simplify any instructions used by the instruction whose sole
3189 // purpose is to compute bits we don't care about.
Dan Gohmanc6ac3222009-06-16 19:55:29 +00003190 uint32_t TypeBits = Op0->getType()->getScalarSizeInBits();
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00003191
Dan Gohmana119de82009-06-14 23:30:43 +00003192 // shl i32 X, 32 = 0 and srl i8 Y, 9 = 0, ... just don't eliminate
3193 // a signed shift.
Chris Lattner4d5542c2006-01-06 07:12:35 +00003194 //
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003195 if (Op1->uge(TypeBits)) {
Chris Lattner0737c242007-02-02 05:29:55 +00003196 if (I.getOpcode() != Instruction::AShr)
Owen Andersona7235ea2009-07-31 20:28:14 +00003197 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
Chris Lattner4d5542c2006-01-06 07:12:35 +00003198 else {
Owen Andersoneed707b2009-07-24 23:12:02 +00003199 I.setOperand(1, ConstantInt::get(I.getType(), TypeBits-1));
Chris Lattner4d5542c2006-01-06 07:12:35 +00003200 return &I;
Chris Lattner8adac752004-02-23 20:30:06 +00003201 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00003202 }
3203
3204 // ((X*C1) << C2) == (X * (C1 << C2))
3205 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
3206 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
3207 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003208 return BinaryOperator::CreateMul(BO->getOperand(0),
Owen Andersonbaf3c402009-07-29 18:55:55 +00003209 ConstantExpr::getShl(BOOp, Op1));
Chris Lattner4d5542c2006-01-06 07:12:35 +00003210
3211 // Try to fold constant and into select arguments.
3212 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner80f43d32010-01-04 07:53:58 +00003213 if (Instruction *R = FoldOpIntoSelect(I, SI))
Chris Lattner4d5542c2006-01-06 07:12:35 +00003214 return R;
3215 if (isa<PHINode>(Op0))
3216 if (Instruction *NV = FoldOpIntoPhi(I))
3217 return NV;
3218
Chris Lattner8999dd32007-12-22 09:07:47 +00003219 // Fold shift2(trunc(shift1(x,c1)), c2) -> trunc(shift2(shift1(x,c1),c2))
3220 if (TruncInst *TI = dyn_cast<TruncInst>(Op0)) {
3221 Instruction *TrOp = dyn_cast<Instruction>(TI->getOperand(0));
3222 // If 'shift2' is an ashr, we would have to get the sign bit into a funny
3223 // place. Don't try to do this transformation in this case. Also, we
3224 // require that the input operand is a shift-by-constant so that we have
3225 // confidence that the shifts will get folded together. We could do this
3226 // xform in more cases, but it is unlikely to be profitable.
3227 if (TrOp && I.isLogicalShift() && TrOp->isShift() &&
3228 isa<ConstantInt>(TrOp->getOperand(1))) {
3229 // Okay, we'll do this xform. Make the shift of shift.
Owen Andersonbaf3c402009-07-29 18:55:55 +00003230 Constant *ShAmt = ConstantExpr::getZExt(Op1, TrOp->getType());
Chris Lattner74381062009-08-30 07:44:24 +00003231 // (shift2 (shift1 & 0x00FF), c2)
3232 Value *NSh = Builder->CreateBinOp(I.getOpcode(), TrOp, ShAmt,I.getName());
Chris Lattner8999dd32007-12-22 09:07:47 +00003233
3234 // For logical shifts, the truncation has the effect of making the high
3235 // part of the register be zeros. Emulate this by inserting an AND to
3236 // clear the top bits as needed. This 'and' will usually be zapped by
3237 // other xforms later if dead.
Dan Gohmanc6ac3222009-06-16 19:55:29 +00003238 unsigned SrcSize = TrOp->getType()->getScalarSizeInBits();
3239 unsigned DstSize = TI->getType()->getScalarSizeInBits();
Chris Lattner8999dd32007-12-22 09:07:47 +00003240 APInt MaskV(APInt::getLowBitsSet(SrcSize, DstSize));
3241
3242 // The mask we constructed says what the trunc would do if occurring
3243 // between the shifts. We want to know the effect *after* the second
3244 // shift. We know that it is a logical shift by a constant, so adjust the
3245 // mask as appropriate.
3246 if (I.getOpcode() == Instruction::Shl)
3247 MaskV <<= Op1->getZExtValue();
3248 else {
3249 assert(I.getOpcode() == Instruction::LShr && "Unknown logical shift");
3250 MaskV = MaskV.lshr(Op1->getZExtValue());
3251 }
3252
Chris Lattner74381062009-08-30 07:44:24 +00003253 // shift1 & 0x00FF
Chris Lattner4de84762010-01-04 07:02:48 +00003254 Value *And = Builder->CreateAnd(NSh,
3255 ConstantInt::get(I.getContext(), MaskV),
Chris Lattner74381062009-08-30 07:44:24 +00003256 TI->getName());
Chris Lattner8999dd32007-12-22 09:07:47 +00003257
3258 // Return the value truncated to the interesting size.
3259 return new TruncInst(And, I.getType());
3260 }
3261 }
3262
Chris Lattner4d5542c2006-01-06 07:12:35 +00003263 if (Op0->hasOneUse()) {
Chris Lattner4d5542c2006-01-06 07:12:35 +00003264 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
3265 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
3266 Value *V1, *V2;
3267 ConstantInt *CC;
3268 switch (Op0BO->getOpcode()) {
Chris Lattner11021cb2005-09-18 05:12:10 +00003269 default: break;
3270 case Instruction::Add:
3271 case Instruction::And:
3272 case Instruction::Or:
Reid Spencera07cb7d2007-02-02 14:41:37 +00003273 case Instruction::Xor: {
Chris Lattner11021cb2005-09-18 05:12:10 +00003274 // These operators commute.
3275 // Turn (Y + (X >> C)) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00003276 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00003277 match(Op0BO->getOperand(1), m_Shr(m_Value(V1),
Chris Lattnerf925cbd2009-08-30 18:50:58 +00003278 m_Specific(Op1)))) {
3279 Value *YS = // (Y << C)
3280 Builder->CreateShl(Op0BO->getOperand(0), Op1, Op0BO->getName());
3281 // (X + (Y << C))
3282 Value *X = Builder->CreateBinOp(Op0BO->getOpcode(), YS, V1,
3283 Op0BO->getOperand(1)->getName());
Zhou Sheng302748d2007-03-30 17:20:39 +00003284 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
Chris Lattner4de84762010-01-04 07:02:48 +00003285 return BinaryOperator::CreateAnd(X, ConstantInt::get(I.getContext(),
Zhou Sheng90b96812007-03-30 05:45:18 +00003286 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
Chris Lattner150f12a2005-09-18 06:30:59 +00003287 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00003288
Chris Lattner150f12a2005-09-18 06:30:59 +00003289 // Turn (Y + ((X >> C) & CC)) << C -> ((X & (CC << C)) + (Y << C))
Reid Spencera07cb7d2007-02-02 14:41:37 +00003290 Value *Op0BOOp1 = Op0BO->getOperand(1);
Chris Lattner3c698492007-03-05 00:11:19 +00003291 if (isLeftShift && Op0BOOp1->hasOneUse() &&
Reid Spencera07cb7d2007-02-02 14:41:37 +00003292 match(Op0BOOp1,
Chris Lattnercb504b92008-11-16 05:38:51 +00003293 m_And(m_Shr(m_Value(V1), m_Specific(Op1)),
Dan Gohman4ae51262009-08-12 16:23:25 +00003294 m_ConstantInt(CC))) &&
Chris Lattnercb504b92008-11-16 05:38:51 +00003295 cast<BinaryOperator>(Op0BOOp1)->getOperand(0)->hasOneUse()) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +00003296 Value *YS = // (Y << C)
3297 Builder->CreateShl(Op0BO->getOperand(0), Op1,
3298 Op0BO->getName());
3299 // X & (CC << C)
3300 Value *XM = Builder->CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
3301 V1->getName()+".mask");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003302 return BinaryOperator::Create(Op0BO->getOpcode(), YS, XM);
Chris Lattner150f12a2005-09-18 06:30:59 +00003303 }
Reid Spencera07cb7d2007-02-02 14:41:37 +00003304 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00003305
Reid Spencera07cb7d2007-02-02 14:41:37 +00003306 // FALL THROUGH.
3307 case Instruction::Sub: {
Chris Lattner11021cb2005-09-18 05:12:10 +00003308 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00003309 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00003310 match(Op0BO->getOperand(0), m_Shr(m_Value(V1),
Dan Gohman4ae51262009-08-12 16:23:25 +00003311 m_Specific(Op1)))) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +00003312 Value *YS = // (Y << C)
3313 Builder->CreateShl(Op0BO->getOperand(1), Op1, Op0BO->getName());
3314 // (X + (Y << C))
3315 Value *X = Builder->CreateBinOp(Op0BO->getOpcode(), V1, YS,
3316 Op0BO->getOperand(0)->getName());
Zhou Sheng302748d2007-03-30 17:20:39 +00003317 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
Chris Lattner4de84762010-01-04 07:02:48 +00003318 return BinaryOperator::CreateAnd(X, ConstantInt::get(I.getContext(),
Zhou Sheng90b96812007-03-30 05:45:18 +00003319 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
Chris Lattner150f12a2005-09-18 06:30:59 +00003320 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00003321
Chris Lattner13d4ab42006-05-31 21:14:00 +00003322 // Turn (((X >> C)&CC) + Y) << C -> (X + (Y << C)) & (CC << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00003323 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
3324 match(Op0BO->getOperand(0),
3325 m_And(m_Shr(m_Value(V1), m_Value(V2)),
Dan Gohman4ae51262009-08-12 16:23:25 +00003326 m_ConstantInt(CC))) && V2 == Op1 &&
Chris Lattner9a4cacb2006-02-09 07:41:14 +00003327 cast<BinaryOperator>(Op0BO->getOperand(0))
3328 ->getOperand(0)->hasOneUse()) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +00003329 Value *YS = // (Y << C)
3330 Builder->CreateShl(Op0BO->getOperand(1), Op1, Op0BO->getName());
3331 // X & (CC << C)
3332 Value *XM = Builder->CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
3333 V1->getName()+".mask");
Chris Lattner150f12a2005-09-18 06:30:59 +00003334
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003335 return BinaryOperator::Create(Op0BO->getOpcode(), XM, YS);
Chris Lattner150f12a2005-09-18 06:30:59 +00003336 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00003337
Chris Lattner11021cb2005-09-18 05:12:10 +00003338 break;
Reid Spencera07cb7d2007-02-02 14:41:37 +00003339 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00003340 }
3341
3342
3343 // If the operand is an bitwise operator with a constant RHS, and the
3344 // shift is the only use, we can pull it out of the shift.
3345 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
3346 bool isValid = true; // Valid only for And, Or, Xor
3347 bool highBitSet = false; // Transform if high bit of constant set?
3348
3349 switch (Op0BO->getOpcode()) {
Chris Lattnerdf17af12003-08-12 21:53:41 +00003350 default: isValid = false; break; // Do not perform transform!
Chris Lattner1f7e1602004-10-08 03:46:20 +00003351 case Instruction::Add:
3352 isValid = isLeftShift;
3353 break;
Chris Lattnerdf17af12003-08-12 21:53:41 +00003354 case Instruction::Or:
3355 case Instruction::Xor:
3356 highBitSet = false;
3357 break;
3358 case Instruction::And:
3359 highBitSet = true;
3360 break;
Chris Lattner4d5542c2006-01-06 07:12:35 +00003361 }
3362
3363 // If this is a signed shift right, and the high bit is modified
3364 // by the logical operation, do not perform the transformation.
3365 // The highBitSet boolean indicates the value of the high bit of
3366 // the constant which would cause it to be modified for this
3367 // operation.
3368 //
Chris Lattnerc95ba442007-12-06 06:25:04 +00003369 if (isValid && I.getOpcode() == Instruction::AShr)
Zhou Shenge9e03f62007-03-28 15:02:20 +00003370 isValid = Op0C->getValue()[TypeBits-1] == highBitSet;
Chris Lattner4d5542c2006-01-06 07:12:35 +00003371
3372 if (isValid) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00003373 Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
Chris Lattner4d5542c2006-01-06 07:12:35 +00003374
Chris Lattnerf925cbd2009-08-30 18:50:58 +00003375 Value *NewShift =
3376 Builder->CreateBinOp(I.getOpcode(), Op0BO->getOperand(0), Op1);
Chris Lattner6934a042007-02-11 01:23:03 +00003377 NewShift->takeName(Op0BO);
Chris Lattner4d5542c2006-01-06 07:12:35 +00003378
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003379 return BinaryOperator::Create(Op0BO->getOpcode(), NewShift,
Chris Lattner4d5542c2006-01-06 07:12:35 +00003380 NewRHS);
3381 }
3382 }
3383 }
3384 }
3385
Chris Lattnerad0124c2006-01-06 07:52:12 +00003386 // Find out if this is a shift of a shift by a constant.
Reid Spencer832254e2007-02-02 02:16:23 +00003387 BinaryOperator *ShiftOp = dyn_cast<BinaryOperator>(Op0);
3388 if (ShiftOp && !ShiftOp->isShift())
3389 ShiftOp = 0;
Chris Lattnerad0124c2006-01-06 07:52:12 +00003390
Reid Spencerb83eb642006-10-20 07:07:24 +00003391 if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
Reid Spencerb83eb642006-10-20 07:07:24 +00003392 ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003393 uint32_t ShiftAmt1 = ShiftAmt1C->getLimitedValue(TypeBits);
3394 uint32_t ShiftAmt2 = Op1->getLimitedValue(TypeBits);
Chris Lattnerb87056f2007-02-05 00:57:54 +00003395 assert(ShiftAmt2 != 0 && "Should have been simplified earlier");
3396 if (ShiftAmt1 == 0) return 0; // Will be simplified in the future.
3397 Value *X = ShiftOp->getOperand(0);
Chris Lattnerad0124c2006-01-06 07:52:12 +00003398
Zhou Sheng4351c642007-04-02 08:20:41 +00003399 uint32_t AmtSum = ShiftAmt1+ShiftAmt2; // Fold into one big shift.
Chris Lattnerb87056f2007-02-05 00:57:54 +00003400
3401 const IntegerType *Ty = cast<IntegerType>(I.getType());
3402
3403 // Check for (X << c1) << c2 and (X >> c1) >> c2
Chris Lattner7f3da2d2007-02-03 23:28:07 +00003404 if (I.getOpcode() == ShiftOp->getOpcode()) {
Chris Lattner344c7c52009-03-20 22:41:15 +00003405 // If this is oversized composite shift, then unsigned shifts get 0, ashr
3406 // saturates.
3407 if (AmtSum >= TypeBits) {
3408 if (I.getOpcode() != Instruction::AShr)
Owen Andersona7235ea2009-07-31 20:28:14 +00003409 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner344c7c52009-03-20 22:41:15 +00003410 AmtSum = TypeBits-1; // Saturate to 31 for i32 ashr.
3411 }
3412
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003413 return BinaryOperator::Create(I.getOpcode(), X,
Owen Andersoneed707b2009-07-24 23:12:02 +00003414 ConstantInt::get(Ty, AmtSum));
Chris Lattnerf925cbd2009-08-30 18:50:58 +00003415 }
3416
3417 if (ShiftOp->getOpcode() == Instruction::LShr &&
3418 I.getOpcode() == Instruction::AShr) {
Chris Lattner344c7c52009-03-20 22:41:15 +00003419 if (AmtSum >= TypeBits)
Owen Andersona7235ea2009-07-31 20:28:14 +00003420 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner344c7c52009-03-20 22:41:15 +00003421
Chris Lattnerb87056f2007-02-05 00:57:54 +00003422 // ((X >>u C1) >>s C2) -> (X >>u (C1+C2)) since C1 != 0.
Owen Andersoneed707b2009-07-24 23:12:02 +00003423 return BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, AmtSum));
Chris Lattnerf925cbd2009-08-30 18:50:58 +00003424 }
3425
3426 if (ShiftOp->getOpcode() == Instruction::AShr &&
3427 I.getOpcode() == Instruction::LShr) {
Chris Lattnerb87056f2007-02-05 00:57:54 +00003428 // ((X >>s C1) >>u C2) -> ((X >>s (C1+C2)) & mask) since C1 != 0.
Chris Lattner344c7c52009-03-20 22:41:15 +00003429 if (AmtSum >= TypeBits)
3430 AmtSum = TypeBits-1;
3431
Chris Lattnerf925cbd2009-08-30 18:50:58 +00003432 Value *Shift = Builder->CreateAShr(X, ConstantInt::get(Ty, AmtSum));
Chris Lattnerb87056f2007-02-05 00:57:54 +00003433
Zhou Shenge9e03f62007-03-28 15:02:20 +00003434 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Chris Lattner4de84762010-01-04 07:02:48 +00003435 return BinaryOperator::CreateAnd(Shift,
3436 ConstantInt::get(I.getContext(), Mask));
Chris Lattnerad0124c2006-01-06 07:52:12 +00003437 }
3438
Chris Lattnerb87056f2007-02-05 00:57:54 +00003439 // Okay, if we get here, one shift must be left, and the other shift must be
3440 // right. See if the amounts are equal.
3441 if (ShiftAmt1 == ShiftAmt2) {
3442 // If we have ((X >>? C) << C), turn this into X & (-1 << C).
3443 if (I.getOpcode() == Instruction::Shl) {
Reid Spencer55702aa2007-03-25 21:11:44 +00003444 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt1));
Chris Lattner4de84762010-01-04 07:02:48 +00003445 return BinaryOperator::CreateAnd(X,
3446 ConstantInt::get(I.getContext(),Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00003447 }
3448 // If we have ((X << C) >>u C), turn this into X & (-1 >>u C).
3449 if (I.getOpcode() == Instruction::LShr) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003450 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt1));
Chris Lattner4de84762010-01-04 07:02:48 +00003451 return BinaryOperator::CreateAnd(X,
3452 ConstantInt::get(I.getContext(), Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00003453 }
3454 // We can simplify ((X << C) >>s C) into a trunc + sext.
3455 // NOTE: we could do this for any C, but that would make 'unusual' integer
3456 // types. For now, just stick to ones well-supported by the code
3457 // generators.
3458 const Type *SExtType = 0;
3459 switch (Ty->getBitWidth() - ShiftAmt1) {
Zhou Shenge9e03f62007-03-28 15:02:20 +00003460 case 1 :
3461 case 8 :
3462 case 16 :
3463 case 32 :
3464 case 64 :
3465 case 128:
Chris Lattner4de84762010-01-04 07:02:48 +00003466 SExtType = IntegerType::get(I.getContext(),
3467 Ty->getBitWidth() - ShiftAmt1);
Zhou Shenge9e03f62007-03-28 15:02:20 +00003468 break;
Chris Lattnerb87056f2007-02-05 00:57:54 +00003469 default: break;
3470 }
Chris Lattnerf925cbd2009-08-30 18:50:58 +00003471 if (SExtType)
3472 return new SExtInst(Builder->CreateTrunc(X, SExtType, "sext"), Ty);
Chris Lattnerb87056f2007-02-05 00:57:54 +00003473 // Otherwise, we can't handle it yet.
3474 } else if (ShiftAmt1 < ShiftAmt2) {
Zhou Sheng4351c642007-04-02 08:20:41 +00003475 uint32_t ShiftDiff = ShiftAmt2-ShiftAmt1;
Chris Lattnerad0124c2006-01-06 07:52:12 +00003476
Chris Lattnerb0b991a2007-02-05 05:57:49 +00003477 // (X >>? C1) << C2 --> X << (C2-C1) & (-1 << C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00003478 if (I.getOpcode() == Instruction::Shl) {
3479 assert(ShiftOp->getOpcode() == Instruction::LShr ||
3480 ShiftOp->getOpcode() == Instruction::AShr);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00003481 Value *Shift = Builder->CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
Chris Lattnere8d56c52006-01-07 01:32:28 +00003482
Reid Spencer55702aa2007-03-25 21:11:44 +00003483 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersoneed707b2009-07-24 23:12:02 +00003484 return BinaryOperator::CreateAnd(Shift,
Chris Lattner4de84762010-01-04 07:02:48 +00003485 ConstantInt::get(I.getContext(),Mask));
Chris Lattnerad0124c2006-01-06 07:52:12 +00003486 }
Chris Lattnerb87056f2007-02-05 00:57:54 +00003487
Chris Lattnerb0b991a2007-02-05 05:57:49 +00003488 // (X << C1) >>u C2 --> X >>u (C2-C1) & (-1 >> C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00003489 if (I.getOpcode() == Instruction::LShr) {
3490 assert(ShiftOp->getOpcode() == Instruction::Shl);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00003491 Value *Shift = Builder->CreateLShr(X, ConstantInt::get(Ty, ShiftDiff));
Chris Lattnerad0124c2006-01-06 07:52:12 +00003492
Reid Spencerd5e30f02007-03-26 17:18:58 +00003493 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersoneed707b2009-07-24 23:12:02 +00003494 return BinaryOperator::CreateAnd(Shift,
Chris Lattner4de84762010-01-04 07:02:48 +00003495 ConstantInt::get(I.getContext(),Mask));
Chris Lattner11021cb2005-09-18 05:12:10 +00003496 }
Chris Lattnerb87056f2007-02-05 00:57:54 +00003497
3498 // We can't handle (X << C1) >>s C2, it shifts arbitrary bits in.
3499 } else {
3500 assert(ShiftAmt2 < ShiftAmt1);
Zhou Sheng4351c642007-04-02 08:20:41 +00003501 uint32_t ShiftDiff = ShiftAmt1-ShiftAmt2;
Chris Lattnerb87056f2007-02-05 00:57:54 +00003502
Chris Lattnerb0b991a2007-02-05 05:57:49 +00003503 // (X >>? C1) << C2 --> X >>? (C1-C2) & (-1 << C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00003504 if (I.getOpcode() == Instruction::Shl) {
3505 assert(ShiftOp->getOpcode() == Instruction::LShr ||
3506 ShiftOp->getOpcode() == Instruction::AShr);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00003507 Value *Shift = Builder->CreateBinOp(ShiftOp->getOpcode(), X,
3508 ConstantInt::get(Ty, ShiftDiff));
Chris Lattnerb87056f2007-02-05 00:57:54 +00003509
Reid Spencer55702aa2007-03-25 21:11:44 +00003510 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersoneed707b2009-07-24 23:12:02 +00003511 return BinaryOperator::CreateAnd(Shift,
Chris Lattner4de84762010-01-04 07:02:48 +00003512 ConstantInt::get(I.getContext(),Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00003513 }
3514
Chris Lattnerb0b991a2007-02-05 05:57:49 +00003515 // (X << C1) >>u C2 --> X << (C1-C2) & (-1 >> C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00003516 if (I.getOpcode() == Instruction::LShr) {
3517 assert(ShiftOp->getOpcode() == Instruction::Shl);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00003518 Value *Shift = Builder->CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
Chris Lattnerb87056f2007-02-05 00:57:54 +00003519
Reid Spencer68d27cf2007-03-26 23:45:51 +00003520 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersoneed707b2009-07-24 23:12:02 +00003521 return BinaryOperator::CreateAnd(Shift,
Chris Lattner4de84762010-01-04 07:02:48 +00003522 ConstantInt::get(I.getContext(),Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00003523 }
3524
3525 // We can't handle (X << C1) >>a C2, it shifts arbitrary bits in.
Chris Lattner6e7ba452005-01-01 16:22:27 +00003526 }
Chris Lattnerad0124c2006-01-06 07:52:12 +00003527 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00003528 return 0;
3529}
3530
Chris Lattnera1be5662002-05-02 17:06:02 +00003531
Reid Spencer3da59db2006-11-27 01:05:10 +00003532
Chris Lattner46cd5a12009-01-09 05:44:56 +00003533/// FindElementAtOffset - Given a type and a constant offset, determine whether
3534/// or not there is a sequence of GEP indices into the type that will land us at
Chris Lattner3914f722009-01-24 01:00:13 +00003535/// the specified offset. If so, fill them into NewIndices and return the
3536/// resultant element type, otherwise return null.
Chris Lattner80f43d32010-01-04 07:53:58 +00003537const Type *InstCombiner::FindElementAtOffset(const Type *Ty, int64_t Offset,
3538 SmallVectorImpl<Value*> &NewIndices) {
Dan Gohmance9fe9f2009-07-21 23:21:54 +00003539 if (!TD) return 0;
Chris Lattner3914f722009-01-24 01:00:13 +00003540 if (!Ty->isSized()) return 0;
Chris Lattner46cd5a12009-01-09 05:44:56 +00003541
3542 // Start with the index over the outer type. Note that the type size
3543 // might be zero (even if the offset isn't zero) if the indexed type
3544 // is something like [0 x {int, int}]
Chris Lattner4de84762010-01-04 07:02:48 +00003545 const Type *IntPtrTy = TD->getIntPtrType(Ty->getContext());
Chris Lattner46cd5a12009-01-09 05:44:56 +00003546 int64_t FirstIdx = 0;
Duncan Sands777d2302009-05-09 07:06:46 +00003547 if (int64_t TySize = TD->getTypeAllocSize(Ty)) {
Chris Lattner46cd5a12009-01-09 05:44:56 +00003548 FirstIdx = Offset/TySize;
Chris Lattner31a69cb2009-01-11 20:41:36 +00003549 Offset -= FirstIdx*TySize;
Chris Lattner46cd5a12009-01-09 05:44:56 +00003550
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00003551 // Handle hosts where % returns negative instead of values [0..TySize).
Chris Lattner46cd5a12009-01-09 05:44:56 +00003552 if (Offset < 0) {
3553 --FirstIdx;
3554 Offset += TySize;
3555 assert(Offset >= 0);
3556 }
3557 assert((uint64_t)Offset < (uint64_t)TySize && "Out of range offset");
3558 }
3559
Owen Andersoneed707b2009-07-24 23:12:02 +00003560 NewIndices.push_back(ConstantInt::get(IntPtrTy, FirstIdx));
Chris Lattner46cd5a12009-01-09 05:44:56 +00003561
3562 // Index into the types. If we fail, set OrigBase to null.
3563 while (Offset) {
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00003564 // Indexing into tail padding between struct/array elements.
3565 if (uint64_t(Offset*8) >= TD->getTypeSizeInBits(Ty))
Chris Lattner3914f722009-01-24 01:00:13 +00003566 return 0;
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00003567
Chris Lattner46cd5a12009-01-09 05:44:56 +00003568 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
3569 const StructLayout *SL = TD->getStructLayout(STy);
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00003570 assert(Offset < (int64_t)SL->getSizeInBytes() &&
3571 "Offset must stay within the indexed type");
3572
Chris Lattner46cd5a12009-01-09 05:44:56 +00003573 unsigned Elt = SL->getElementContainingOffset(Offset);
Chris Lattner4de84762010-01-04 07:02:48 +00003574 NewIndices.push_back(ConstantInt::get(Type::getInt32Ty(Ty->getContext()),
3575 Elt));
Chris Lattner46cd5a12009-01-09 05:44:56 +00003576
3577 Offset -= SL->getElementOffset(Elt);
3578 Ty = STy->getElementType(Elt);
Chris Lattner1c412d92009-01-11 20:23:52 +00003579 } else if (const ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
Duncan Sands777d2302009-05-09 07:06:46 +00003580 uint64_t EltSize = TD->getTypeAllocSize(AT->getElementType());
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00003581 assert(EltSize && "Cannot index into a zero-sized array");
Owen Andersoneed707b2009-07-24 23:12:02 +00003582 NewIndices.push_back(ConstantInt::get(IntPtrTy,Offset/EltSize));
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00003583 Offset %= EltSize;
Chris Lattner1c412d92009-01-11 20:23:52 +00003584 Ty = AT->getElementType();
Chris Lattner46cd5a12009-01-09 05:44:56 +00003585 } else {
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00003586 // Otherwise, we can't index into the middle of this atomic type, bail.
Chris Lattner3914f722009-01-24 01:00:13 +00003587 return 0;
Chris Lattner46cd5a12009-01-09 05:44:56 +00003588 }
3589 }
3590
Chris Lattner3914f722009-01-24 01:00:13 +00003591 return Ty;
Chris Lattner46cd5a12009-01-09 05:44:56 +00003592}
3593
Chris Lattner8a2a3112001-12-14 16:52:21 +00003594
Dan Gohmaneee962e2008-04-10 18:43:06 +00003595/// EnforceKnownAlignment - If the specified pointer points to an object that
3596/// we control, modify the object's alignment to PrefAlign. This isn't
3597/// often possible though. If alignment is important, a more reliable approach
3598/// is to simply align all global variables and allocation instructions to
3599/// their preferred alignment from the beginning.
3600///
3601static unsigned EnforceKnownAlignment(Value *V,
3602 unsigned Align, unsigned PrefAlign) {
Chris Lattnerf2369f22007-08-09 19:05:49 +00003603
Dan Gohmaneee962e2008-04-10 18:43:06 +00003604 User *U = dyn_cast<User>(V);
3605 if (!U) return Align;
3606
Dan Gohmanca178902009-07-17 20:47:02 +00003607 switch (Operator::getOpcode(U)) {
Dan Gohmaneee962e2008-04-10 18:43:06 +00003608 default: break;
3609 case Instruction::BitCast:
3610 return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
3611 case Instruction::GetElementPtr: {
Chris Lattner95a959d2006-03-06 20:18:44 +00003612 // If all indexes are zero, it is just the alignment of the base pointer.
3613 bool AllZeroOperands = true;
Gabor Greif52ed3632008-06-12 21:51:29 +00003614 for (User::op_iterator i = U->op_begin() + 1, e = U->op_end(); i != e; ++i)
Gabor Greif177dd3f2008-06-12 21:37:33 +00003615 if (!isa<Constant>(*i) ||
3616 !cast<Constant>(*i)->isNullValue()) {
Chris Lattner95a959d2006-03-06 20:18:44 +00003617 AllZeroOperands = false;
3618 break;
3619 }
Chris Lattnerf2369f22007-08-09 19:05:49 +00003620
3621 if (AllZeroOperands) {
3622 // Treat this like a bitcast.
Dan Gohmaneee962e2008-04-10 18:43:06 +00003623 return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
Chris Lattnerf2369f22007-08-09 19:05:49 +00003624 }
Dan Gohmaneee962e2008-04-10 18:43:06 +00003625 break;
Chris Lattner95a959d2006-03-06 20:18:44 +00003626 }
Dan Gohmaneee962e2008-04-10 18:43:06 +00003627 }
3628
3629 if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
3630 // If there is a large requested alignment and we can, bump up the alignment
3631 // of the global.
3632 if (!GV->isDeclaration()) {
Dan Gohmanecd0fb52009-02-16 23:02:21 +00003633 if (GV->getAlignment() >= PrefAlign)
3634 Align = GV->getAlignment();
3635 else {
3636 GV->setAlignment(PrefAlign);
3637 Align = PrefAlign;
3638 }
Dan Gohmaneee962e2008-04-10 18:43:06 +00003639 }
Chris Lattner42ebefa2009-09-27 21:42:46 +00003640 } else if (AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
3641 // If there is a requested alignment and if this is an alloca, round up.
3642 if (AI->getAlignment() >= PrefAlign)
3643 Align = AI->getAlignment();
3644 else {
3645 AI->setAlignment(PrefAlign);
3646 Align = PrefAlign;
Dan Gohmaneee962e2008-04-10 18:43:06 +00003647 }
3648 }
3649
3650 return Align;
3651}
3652
3653/// GetOrEnforceKnownAlignment - If the specified pointer has an alignment that
3654/// we can determine, return it, otherwise return 0. If PrefAlign is specified,
3655/// and it is more than the alignment of the ultimate object, see if we can
3656/// increase the alignment of the ultimate object, making this check succeed.
3657unsigned InstCombiner::GetOrEnforceKnownAlignment(Value *V,
3658 unsigned PrefAlign) {
3659 unsigned BitWidth = TD ? TD->getTypeSizeInBits(V->getType()) :
3660 sizeof(PrefAlign) * CHAR_BIT;
3661 APInt Mask = APInt::getAllOnesValue(BitWidth);
3662 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
3663 ComputeMaskedBits(V, Mask, KnownZero, KnownOne);
3664 unsigned TrailZ = KnownZero.countTrailingOnes();
3665 unsigned Align = 1u << std::min(BitWidth - 1, TrailZ);
3666
3667 if (PrefAlign > Align)
3668 Align = EnforceKnownAlignment(V, Align, PrefAlign);
3669
3670 // We don't need to make any adjustment.
3671 return Align;
Chris Lattner95a959d2006-03-06 20:18:44 +00003672}
3673
Chris Lattnerf497b022008-01-13 23:50:23 +00003674Instruction *InstCombiner::SimplifyMemTransfer(MemIntrinsic *MI) {
Dan Gohmaneee962e2008-04-10 18:43:06 +00003675 unsigned DstAlign = GetOrEnforceKnownAlignment(MI->getOperand(1));
Dan Gohmanbc989d42009-02-22 18:06:32 +00003676 unsigned SrcAlign = GetOrEnforceKnownAlignment(MI->getOperand(2));
Chris Lattnerf497b022008-01-13 23:50:23 +00003677 unsigned MinAlign = std::min(DstAlign, SrcAlign);
Chris Lattnerdfe964c2009-03-08 03:59:00 +00003678 unsigned CopyAlign = MI->getAlignment();
Chris Lattnerf497b022008-01-13 23:50:23 +00003679
3680 if (CopyAlign < MinAlign) {
Owen Andersoneed707b2009-07-24 23:12:02 +00003681 MI->setAlignment(ConstantInt::get(MI->getAlignmentType(),
Owen Andersona547b472009-07-09 18:36:20 +00003682 MinAlign, false));
Chris Lattnerf497b022008-01-13 23:50:23 +00003683 return MI;
3684 }
3685
3686 // If MemCpyInst length is 1/2/4/8 bytes then replace memcpy with
3687 // load/store.
3688 ConstantInt *MemOpLength = dyn_cast<ConstantInt>(MI->getOperand(3));
3689 if (MemOpLength == 0) return 0;
3690
Chris Lattner37ac6082008-01-14 00:28:35 +00003691 // Source and destination pointer types are always "i8*" for intrinsic. See
3692 // if the size is something we can handle with a single primitive load/store.
3693 // A single load+store correctly handles overlapping memory in the memmove
3694 // case.
Chris Lattnerf497b022008-01-13 23:50:23 +00003695 unsigned Size = MemOpLength->getZExtValue();
Chris Lattner69ea9d22008-04-30 06:39:11 +00003696 if (Size == 0) return MI; // Delete this mem transfer.
3697
3698 if (Size > 8 || (Size&(Size-1)))
Chris Lattner37ac6082008-01-14 00:28:35 +00003699 return 0; // If not 1/2/4/8 bytes, exit.
Chris Lattnerf497b022008-01-13 23:50:23 +00003700
Chris Lattner37ac6082008-01-14 00:28:35 +00003701 // Use an integer load+store unless we can find something better.
Owen Andersond672ecb2009-07-03 00:17:18 +00003702 Type *NewPtrTy =
Chris Lattner4de84762010-01-04 07:02:48 +00003703 PointerType::getUnqual(IntegerType::get(MI->getContext(), Size<<3));
Chris Lattner37ac6082008-01-14 00:28:35 +00003704
3705 // Memcpy forces the use of i8* for the source and destination. That means
3706 // that if you're using memcpy to move one double around, you'll get a cast
3707 // from double* to i8*. We'd much rather use a double load+store rather than
3708 // an i64 load+store, here because this improves the odds that the source or
3709 // dest address will be promotable. See if we can find a better type than the
3710 // integer datatype.
3711 if (Value *Op = getBitCastOperand(MI->getOperand(1))) {
3712 const Type *SrcETy = cast<PointerType>(Op->getType())->getElementType();
Dan Gohmance9fe9f2009-07-21 23:21:54 +00003713 if (TD && SrcETy->isSized() && TD->getTypeStoreSize(SrcETy) == Size) {
Chris Lattner37ac6082008-01-14 00:28:35 +00003714 // The SrcETy might be something like {{{double}}} or [1 x double]. Rip
3715 // down through these levels if so.
Dan Gohman8f8e2692008-05-23 01:52:21 +00003716 while (!SrcETy->isSingleValueType()) {
Chris Lattner37ac6082008-01-14 00:28:35 +00003717 if (const StructType *STy = dyn_cast<StructType>(SrcETy)) {
3718 if (STy->getNumElements() == 1)
3719 SrcETy = STy->getElementType(0);
3720 else
3721 break;
3722 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcETy)) {
3723 if (ATy->getNumElements() == 1)
3724 SrcETy = ATy->getElementType();
3725 else
3726 break;
3727 } else
3728 break;
3729 }
3730
Dan Gohman8f8e2692008-05-23 01:52:21 +00003731 if (SrcETy->isSingleValueType())
Owen Andersondebcb012009-07-29 22:17:13 +00003732 NewPtrTy = PointerType::getUnqual(SrcETy);
Chris Lattner37ac6082008-01-14 00:28:35 +00003733 }
3734 }
3735
3736
Chris Lattnerf497b022008-01-13 23:50:23 +00003737 // If the memcpy/memmove provides better alignment info than we can
3738 // infer, use it.
3739 SrcAlign = std::max(SrcAlign, CopyAlign);
3740 DstAlign = std::max(DstAlign, CopyAlign);
3741
Chris Lattner08142f22009-08-30 19:47:22 +00003742 Value *Src = Builder->CreateBitCast(MI->getOperand(2), NewPtrTy);
3743 Value *Dest = Builder->CreateBitCast(MI->getOperand(1), NewPtrTy);
Chris Lattner37ac6082008-01-14 00:28:35 +00003744 Instruction *L = new LoadInst(Src, "tmp", false, SrcAlign);
3745 InsertNewInstBefore(L, *MI);
3746 InsertNewInstBefore(new StoreInst(L, Dest, false, DstAlign), *MI);
3747
3748 // Set the size of the copy to 0, it will be deleted on the next iteration.
Owen Andersona7235ea2009-07-31 20:28:14 +00003749 MI->setOperand(3, Constant::getNullValue(MemOpLength->getType()));
Chris Lattner37ac6082008-01-14 00:28:35 +00003750 return MI;
Chris Lattnerf497b022008-01-13 23:50:23 +00003751}
Chris Lattner3d69f462004-03-12 05:52:32 +00003752
Chris Lattner69ea9d22008-04-30 06:39:11 +00003753Instruction *InstCombiner::SimplifyMemSet(MemSetInst *MI) {
3754 unsigned Alignment = GetOrEnforceKnownAlignment(MI->getDest());
Chris Lattnerdfe964c2009-03-08 03:59:00 +00003755 if (MI->getAlignment() < Alignment) {
Owen Andersoneed707b2009-07-24 23:12:02 +00003756 MI->setAlignment(ConstantInt::get(MI->getAlignmentType(),
Owen Andersona547b472009-07-09 18:36:20 +00003757 Alignment, false));
Chris Lattner69ea9d22008-04-30 06:39:11 +00003758 return MI;
3759 }
3760
3761 // Extract the length and alignment and fill if they are constant.
3762 ConstantInt *LenC = dyn_cast<ConstantInt>(MI->getLength());
3763 ConstantInt *FillC = dyn_cast<ConstantInt>(MI->getValue());
Chris Lattner4de84762010-01-04 07:02:48 +00003764 if (!LenC || !FillC || FillC->getType() != Type::getInt8Ty(MI->getContext()))
Chris Lattner69ea9d22008-04-30 06:39:11 +00003765 return 0;
3766 uint64_t Len = LenC->getZExtValue();
Chris Lattnerdfe964c2009-03-08 03:59:00 +00003767 Alignment = MI->getAlignment();
Chris Lattner69ea9d22008-04-30 06:39:11 +00003768
3769 // If the length is zero, this is a no-op
3770 if (Len == 0) return MI; // memset(d,c,0,a) -> noop
3771
3772 // memset(s,c,n) -> store s, c (for n=1,2,4,8)
3773 if (Len <= 8 && isPowerOf2_32((uint32_t)Len)) {
Chris Lattner4de84762010-01-04 07:02:48 +00003774 const Type *ITy = IntegerType::get(MI->getContext(), Len*8); // n=1 -> i8.
Chris Lattner69ea9d22008-04-30 06:39:11 +00003775
3776 Value *Dest = MI->getDest();
Chris Lattner08142f22009-08-30 19:47:22 +00003777 Dest = Builder->CreateBitCast(Dest, PointerType::getUnqual(ITy));
Chris Lattner69ea9d22008-04-30 06:39:11 +00003778
3779 // Alignment 0 is identity for alignment 1 for memset, but not store.
3780 if (Alignment == 0) Alignment = 1;
3781
3782 // Extract the fill value and store.
3783 uint64_t Fill = FillC->getZExtValue()*0x0101010101010101ULL;
Owen Andersoneed707b2009-07-24 23:12:02 +00003784 InsertNewInstBefore(new StoreInst(ConstantInt::get(ITy, Fill),
Owen Andersond672ecb2009-07-03 00:17:18 +00003785 Dest, false, Alignment), *MI);
Chris Lattner69ea9d22008-04-30 06:39:11 +00003786
3787 // Set the size of the copy to 0, it will be deleted on the next iteration.
Owen Andersona7235ea2009-07-31 20:28:14 +00003788 MI->setLength(Constant::getNullValue(LenC->getType()));
Chris Lattner69ea9d22008-04-30 06:39:11 +00003789 return MI;
3790 }
3791
3792 return 0;
3793}
3794
3795
Chris Lattner8b0ea312006-01-13 20:11:04 +00003796/// visitCallInst - CallInst simplification. This mostly only handles folding
3797/// of intrinsic instructions. For normal calls, it allows visitCallSite to do
3798/// the heavy lifting.
3799///
Chris Lattner9fe38862003-06-19 17:00:31 +00003800Instruction *InstCombiner::visitCallInst(CallInst &CI) {
Victor Hernandez66284e02009-10-24 04:23:03 +00003801 if (isFreeCall(&CI))
3802 return visitFree(CI);
3803
Chris Lattneraab6ec42009-05-13 17:39:14 +00003804 // If the caller function is nounwind, mark the call as nounwind, even if the
3805 // callee isn't.
3806 if (CI.getParent()->getParent()->doesNotThrow() &&
3807 !CI.doesNotThrow()) {
3808 CI.setDoesNotThrow();
3809 return &CI;
3810 }
3811
Chris Lattner8b0ea312006-01-13 20:11:04 +00003812 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
3813 if (!II) return visitCallSite(&CI);
3814
Chris Lattner7bcc0e72004-02-28 05:22:00 +00003815 // Intrinsics cannot occur in an invoke, so handle them here instead of in
3816 // visitCallSite.
Chris Lattner8b0ea312006-01-13 20:11:04 +00003817 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
Chris Lattner35b9e482004-10-12 04:52:52 +00003818 bool Changed = false;
3819
3820 // memmove/cpy/set of zero bytes is a noop.
3821 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
3822 if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
3823
Chris Lattner35b9e482004-10-12 04:52:52 +00003824 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
Reid Spencerb83eb642006-10-20 07:07:24 +00003825 if (CI->getZExtValue() == 1) {
Chris Lattner35b9e482004-10-12 04:52:52 +00003826 // Replace the instruction with just byte operations. We would
3827 // transform other cases to loads/stores, but we don't know if
3828 // alignment is sufficient.
3829 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +00003830 }
3831
Chris Lattner35b9e482004-10-12 04:52:52 +00003832 // If we have a memmove and the source operation is a constant global,
3833 // then the source and dest pointers can't alias, so we can change this
3834 // into a call to memcpy.
Chris Lattnerf497b022008-01-13 23:50:23 +00003835 if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI)) {
Chris Lattner35b9e482004-10-12 04:52:52 +00003836 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
3837 if (GVSrc->isConstant()) {
3838 Module *M = CI.getParent()->getParent()->getParent();
Chris Lattner824b9582008-11-21 16:42:48 +00003839 Intrinsic::ID MemCpyID = Intrinsic::memcpy;
3840 const Type *Tys[1];
3841 Tys[0] = CI.getOperand(3)->getType();
3842 CI.setOperand(0,
3843 Intrinsic::getDeclaration(M, MemCpyID, Tys, 1));
Chris Lattner35b9e482004-10-12 04:52:52 +00003844 Changed = true;
3845 }
Eli Friedman0c826d92009-12-17 21:07:31 +00003846 }
Chris Lattnera935db82008-05-28 05:30:41 +00003847
Eli Friedman0c826d92009-12-17 21:07:31 +00003848 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(MI)) {
Chris Lattnera935db82008-05-28 05:30:41 +00003849 // memmove(x,x,size) -> noop.
Eli Friedman0c826d92009-12-17 21:07:31 +00003850 if (MTI->getSource() == MTI->getDest())
Chris Lattnera935db82008-05-28 05:30:41 +00003851 return EraseInstFromFunction(CI);
Chris Lattner95a959d2006-03-06 20:18:44 +00003852 }
Chris Lattner35b9e482004-10-12 04:52:52 +00003853
Chris Lattner95a959d2006-03-06 20:18:44 +00003854 // If we can determine a pointer alignment that is bigger than currently
3855 // set, update the alignment.
Chris Lattner3ce5e882009-03-08 03:37:16 +00003856 if (isa<MemTransferInst>(MI)) {
Chris Lattnerf497b022008-01-13 23:50:23 +00003857 if (Instruction *I = SimplifyMemTransfer(MI))
3858 return I;
Chris Lattner69ea9d22008-04-30 06:39:11 +00003859 } else if (MemSetInst *MSI = dyn_cast<MemSetInst>(MI)) {
3860 if (Instruction *I = SimplifyMemSet(MSI))
3861 return I;
Chris Lattner95a959d2006-03-06 20:18:44 +00003862 }
3863
Chris Lattner8b0ea312006-01-13 20:11:04 +00003864 if (Changed) return II;
Chris Lattner0521e3c2008-06-18 04:33:20 +00003865 }
3866
3867 switch (II->getIntrinsicID()) {
3868 default: break;
3869 case Intrinsic::bswap:
3870 // bswap(bswap(x)) -> x
3871 if (IntrinsicInst *Operand = dyn_cast<IntrinsicInst>(II->getOperand(1)))
3872 if (Operand->getIntrinsicID() == Intrinsic::bswap)
3873 return ReplaceInstUsesWith(CI, Operand->getOperand(1));
Chris Lattnere33d4132010-01-01 18:34:40 +00003874
3875 // bswap(trunc(bswap(x))) -> trunc(lshr(x, c))
3876 if (TruncInst *TI = dyn_cast<TruncInst>(II->getOperand(1))) {
3877 if (IntrinsicInst *Operand = dyn_cast<IntrinsicInst>(TI->getOperand(0)))
3878 if (Operand->getIntrinsicID() == Intrinsic::bswap) {
3879 unsigned C = Operand->getType()->getPrimitiveSizeInBits() -
3880 TI->getType()->getPrimitiveSizeInBits();
3881 Value *CV = ConstantInt::get(Operand->getType(), C);
3882 Value *V = Builder->CreateLShr(Operand->getOperand(1), CV);
3883 return new TruncInst(V, TI->getType());
3884 }
3885 }
3886
Chris Lattner0521e3c2008-06-18 04:33:20 +00003887 break;
Chris Lattnerd27f9112010-01-01 01:52:15 +00003888 case Intrinsic::powi:
3889 if (ConstantInt *Power = dyn_cast<ConstantInt>(II->getOperand(2))) {
3890 // powi(x, 0) -> 1.0
3891 if (Power->isZero())
3892 return ReplaceInstUsesWith(CI, ConstantFP::get(CI.getType(), 1.0));
3893 // powi(x, 1) -> x
3894 if (Power->isOne())
3895 return ReplaceInstUsesWith(CI, II->getOperand(1));
3896 // powi(x, -1) -> 1/x
Chris Lattnerf9ead872010-01-01 01:54:08 +00003897 if (Power->isAllOnesValue())
3898 return BinaryOperator::CreateFDiv(ConstantFP::get(CI.getType(), 1.0),
3899 II->getOperand(1));
Chris Lattnerd27f9112010-01-01 01:52:15 +00003900 }
3901 break;
3902
Chris Lattner2bbac752009-11-26 21:42:47 +00003903 case Intrinsic::uadd_with_overflow: {
3904 Value *LHS = II->getOperand(1), *RHS = II->getOperand(2);
3905 const IntegerType *IT = cast<IntegerType>(II->getOperand(1)->getType());
3906 uint32_t BitWidth = IT->getBitWidth();
3907 APInt Mask = APInt::getSignBit(BitWidth);
Chris Lattner998e25a2009-11-26 22:08:06 +00003908 APInt LHSKnownZero(BitWidth, 0);
3909 APInt LHSKnownOne(BitWidth, 0);
Chris Lattner2bbac752009-11-26 21:42:47 +00003910 ComputeMaskedBits(LHS, Mask, LHSKnownZero, LHSKnownOne);
3911 bool LHSKnownNegative = LHSKnownOne[BitWidth - 1];
3912 bool LHSKnownPositive = LHSKnownZero[BitWidth - 1];
3913
3914 if (LHSKnownNegative || LHSKnownPositive) {
Chris Lattner998e25a2009-11-26 22:08:06 +00003915 APInt RHSKnownZero(BitWidth, 0);
3916 APInt RHSKnownOne(BitWidth, 0);
Chris Lattner2bbac752009-11-26 21:42:47 +00003917 ComputeMaskedBits(RHS, Mask, RHSKnownZero, RHSKnownOne);
3918 bool RHSKnownNegative = RHSKnownOne[BitWidth - 1];
3919 bool RHSKnownPositive = RHSKnownZero[BitWidth - 1];
3920 if (LHSKnownNegative && RHSKnownNegative) {
3921 // The sign bit is set in both cases: this MUST overflow.
3922 // Create a simple add instruction, and insert it into the struct.
3923 Instruction *Add = BinaryOperator::CreateAdd(LHS, RHS, "", &CI);
3924 Worklist.Add(Add);
Chris Lattnercd188e92009-11-29 02:57:29 +00003925 Constant *V[] = {
Chris Lattner4de84762010-01-04 07:02:48 +00003926 UndefValue::get(LHS->getType()),ConstantInt::getTrue(II->getContext())
Chris Lattnercd188e92009-11-29 02:57:29 +00003927 };
Chris Lattner4de84762010-01-04 07:02:48 +00003928 Constant *Struct = ConstantStruct::get(II->getContext(), V, 2, false);
Chris Lattner2bbac752009-11-26 21:42:47 +00003929 return InsertValueInst::Create(Struct, Add, 0);
3930 }
3931
3932 if (LHSKnownPositive && RHSKnownPositive) {
3933 // The sign bit is clear in both cases: this CANNOT overflow.
3934 // Create a simple add instruction, and insert it into the struct.
3935 Instruction *Add = BinaryOperator::CreateNUWAdd(LHS, RHS, "", &CI);
3936 Worklist.Add(Add);
Chris Lattnercd188e92009-11-29 02:57:29 +00003937 Constant *V[] = {
Chris Lattner4de84762010-01-04 07:02:48 +00003938 UndefValue::get(LHS->getType()),
3939 ConstantInt::getFalse(II->getContext())
Chris Lattnercd188e92009-11-29 02:57:29 +00003940 };
Chris Lattner4de84762010-01-04 07:02:48 +00003941 Constant *Struct = ConstantStruct::get(II->getContext(), V, 2, false);
Chris Lattner2bbac752009-11-26 21:42:47 +00003942 return InsertValueInst::Create(Struct, Add, 0);
3943 }
3944 }
3945 }
3946 // FALL THROUGH uadd into sadd
3947 case Intrinsic::sadd_with_overflow:
3948 // Canonicalize constants into the RHS.
3949 if (isa<Constant>(II->getOperand(1)) &&
3950 !isa<Constant>(II->getOperand(2))) {
3951 Value *LHS = II->getOperand(1);
3952 II->setOperand(1, II->getOperand(2));
3953 II->setOperand(2, LHS);
3954 return II;
3955 }
3956
3957 // X + undef -> undef
3958 if (isa<UndefValue>(II->getOperand(2)))
3959 return ReplaceInstUsesWith(CI, UndefValue::get(II->getType()));
3960
3961 if (ConstantInt *RHS = dyn_cast<ConstantInt>(II->getOperand(2))) {
3962 // X + 0 -> {X, false}
3963 if (RHS->isZero()) {
3964 Constant *V[] = {
Chris Lattnercd188e92009-11-29 02:57:29 +00003965 UndefValue::get(II->getOperand(0)->getType()),
Chris Lattner4de84762010-01-04 07:02:48 +00003966 ConstantInt::getFalse(II->getContext())
Chris Lattner2bbac752009-11-26 21:42:47 +00003967 };
Chris Lattner4de84762010-01-04 07:02:48 +00003968 Constant *Struct = ConstantStruct::get(II->getContext(), V, 2, false);
Chris Lattner2bbac752009-11-26 21:42:47 +00003969 return InsertValueInst::Create(Struct, II->getOperand(1), 0);
3970 }
3971 }
3972 break;
3973 case Intrinsic::usub_with_overflow:
3974 case Intrinsic::ssub_with_overflow:
3975 // undef - X -> undef
3976 // X - undef -> undef
3977 if (isa<UndefValue>(II->getOperand(1)) ||
3978 isa<UndefValue>(II->getOperand(2)))
3979 return ReplaceInstUsesWith(CI, UndefValue::get(II->getType()));
3980
3981 if (ConstantInt *RHS = dyn_cast<ConstantInt>(II->getOperand(2))) {
3982 // X - 0 -> {X, false}
3983 if (RHS->isZero()) {
3984 Constant *V[] = {
Chris Lattnercd188e92009-11-29 02:57:29 +00003985 UndefValue::get(II->getOperand(1)->getType()),
Chris Lattner4de84762010-01-04 07:02:48 +00003986 ConstantInt::getFalse(II->getContext())
Chris Lattner2bbac752009-11-26 21:42:47 +00003987 };
Chris Lattner4de84762010-01-04 07:02:48 +00003988 Constant *Struct = ConstantStruct::get(II->getContext(), V, 2, false);
Chris Lattner2bbac752009-11-26 21:42:47 +00003989 return InsertValueInst::Create(Struct, II->getOperand(1), 0);
3990 }
3991 }
3992 break;
3993 case Intrinsic::umul_with_overflow:
3994 case Intrinsic::smul_with_overflow:
3995 // Canonicalize constants into the RHS.
3996 if (isa<Constant>(II->getOperand(1)) &&
3997 !isa<Constant>(II->getOperand(2))) {
3998 Value *LHS = II->getOperand(1);
3999 II->setOperand(1, II->getOperand(2));
4000 II->setOperand(2, LHS);
4001 return II;
4002 }
4003
4004 // X * undef -> undef
4005 if (isa<UndefValue>(II->getOperand(2)))
4006 return ReplaceInstUsesWith(CI, UndefValue::get(II->getType()));
4007
4008 if (ConstantInt *RHSI = dyn_cast<ConstantInt>(II->getOperand(2))) {
4009 // X*0 -> {0, false}
4010 if (RHSI->isZero())
4011 return ReplaceInstUsesWith(CI, Constant::getNullValue(II->getType()));
4012
4013 // X * 1 -> {X, false}
4014 if (RHSI->equalsInt(1)) {
Chris Lattnercd188e92009-11-29 02:57:29 +00004015 Constant *V[] = {
4016 UndefValue::get(II->getOperand(1)->getType()),
Chris Lattner4de84762010-01-04 07:02:48 +00004017 ConstantInt::getFalse(II->getContext())
Chris Lattnercd188e92009-11-29 02:57:29 +00004018 };
Chris Lattner4de84762010-01-04 07:02:48 +00004019 Constant *Struct = ConstantStruct::get(II->getContext(), V, 2, false);
Chris Lattnercd188e92009-11-29 02:57:29 +00004020 return InsertValueInst::Create(Struct, II->getOperand(1), 0);
Chris Lattner2bbac752009-11-26 21:42:47 +00004021 }
4022 }
4023 break;
Chris Lattner0521e3c2008-06-18 04:33:20 +00004024 case Intrinsic::ppc_altivec_lvx:
4025 case Intrinsic::ppc_altivec_lvxl:
4026 case Intrinsic::x86_sse_loadu_ps:
4027 case Intrinsic::x86_sse2_loadu_pd:
4028 case Intrinsic::x86_sse2_loadu_dq:
4029 // Turn PPC lvx -> load if the pointer is known aligned.
4030 // Turn X86 loadups -> load if the pointer is known aligned.
4031 if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
Chris Lattner08142f22009-08-30 19:47:22 +00004032 Value *Ptr = Builder->CreateBitCast(II->getOperand(1),
4033 PointerType::getUnqual(II->getType()));
Chris Lattner0521e3c2008-06-18 04:33:20 +00004034 return new LoadInst(Ptr);
Chris Lattner867b99f2006-10-05 06:55:50 +00004035 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00004036 break;
4037 case Intrinsic::ppc_altivec_stvx:
4038 case Intrinsic::ppc_altivec_stvxl:
4039 // Turn stvx -> store if the pointer is known aligned.
4040 if (GetOrEnforceKnownAlignment(II->getOperand(2), 16) >= 16) {
4041 const Type *OpPtrTy =
Owen Andersondebcb012009-07-29 22:17:13 +00004042 PointerType::getUnqual(II->getOperand(1)->getType());
Chris Lattner08142f22009-08-30 19:47:22 +00004043 Value *Ptr = Builder->CreateBitCast(II->getOperand(2), OpPtrTy);
Chris Lattner0521e3c2008-06-18 04:33:20 +00004044 return new StoreInst(II->getOperand(1), Ptr);
4045 }
4046 break;
4047 case Intrinsic::x86_sse_storeu_ps:
4048 case Intrinsic::x86_sse2_storeu_pd:
4049 case Intrinsic::x86_sse2_storeu_dq:
Chris Lattner0521e3c2008-06-18 04:33:20 +00004050 // Turn X86 storeu -> store if the pointer is known aligned.
4051 if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
4052 const Type *OpPtrTy =
Owen Andersondebcb012009-07-29 22:17:13 +00004053 PointerType::getUnqual(II->getOperand(2)->getType());
Chris Lattner08142f22009-08-30 19:47:22 +00004054 Value *Ptr = Builder->CreateBitCast(II->getOperand(1), OpPtrTy);
Chris Lattner0521e3c2008-06-18 04:33:20 +00004055 return new StoreInst(II->getOperand(2), Ptr);
4056 }
4057 break;
4058
4059 case Intrinsic::x86_sse_cvttss2si: {
4060 // These intrinsics only demands the 0th element of its input vector. If
4061 // we can simplify the input based on that, do so now.
Evan Cheng388df622009-02-03 10:05:09 +00004062 unsigned VWidth =
4063 cast<VectorType>(II->getOperand(1)->getType())->getNumElements();
4064 APInt DemandedElts(VWidth, 1);
4065 APInt UndefElts(VWidth, 0);
4066 if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
Chris Lattner0521e3c2008-06-18 04:33:20 +00004067 UndefElts)) {
4068 II->setOperand(1, V);
4069 return II;
4070 }
4071 break;
4072 }
4073
4074 case Intrinsic::ppc_altivec_vperm:
4075 // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
4076 if (ConstantVector *Mask = dyn_cast<ConstantVector>(II->getOperand(3))) {
4077 assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
Chris Lattner867b99f2006-10-05 06:55:50 +00004078
Chris Lattner0521e3c2008-06-18 04:33:20 +00004079 // Check that all of the elements are integer constants or undefs.
4080 bool AllEltsOk = true;
4081 for (unsigned i = 0; i != 16; ++i) {
4082 if (!isa<ConstantInt>(Mask->getOperand(i)) &&
4083 !isa<UndefValue>(Mask->getOperand(i))) {
4084 AllEltsOk = false;
4085 break;
4086 }
4087 }
4088
4089 if (AllEltsOk) {
4090 // Cast the input vectors to byte vectors.
Chris Lattner08142f22009-08-30 19:47:22 +00004091 Value *Op0 = Builder->CreateBitCast(II->getOperand(1), Mask->getType());
4092 Value *Op1 = Builder->CreateBitCast(II->getOperand(2), Mask->getType());
Owen Anderson9e9a0d52009-07-30 23:03:37 +00004093 Value *Result = UndefValue::get(Op0->getType());
Chris Lattnere2ed0572006-04-06 19:19:17 +00004094
Chris Lattner0521e3c2008-06-18 04:33:20 +00004095 // Only extract each element once.
4096 Value *ExtractedElts[32];
4097 memset(ExtractedElts, 0, sizeof(ExtractedElts));
4098
Chris Lattnere2ed0572006-04-06 19:19:17 +00004099 for (unsigned i = 0; i != 16; ++i) {
Chris Lattner0521e3c2008-06-18 04:33:20 +00004100 if (isa<UndefValue>(Mask->getOperand(i)))
4101 continue;
4102 unsigned Idx=cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
4103 Idx &= 31; // Match the hardware behavior.
4104
4105 if (ExtractedElts[Idx] == 0) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +00004106 ExtractedElts[Idx] =
4107 Builder->CreateExtractElement(Idx < 16 ? Op0 : Op1,
Chris Lattner4de84762010-01-04 07:02:48 +00004108 ConstantInt::get(Type::getInt32Ty(II->getContext()),
4109 Idx&15, false), "tmp");
Chris Lattnere2ed0572006-04-06 19:19:17 +00004110 }
Chris Lattnere2ed0572006-04-06 19:19:17 +00004111
Chris Lattner0521e3c2008-06-18 04:33:20 +00004112 // Insert this value into the result vector.
Chris Lattnerf925cbd2009-08-30 18:50:58 +00004113 Result = Builder->CreateInsertElement(Result, ExtractedElts[Idx],
Chris Lattner4de84762010-01-04 07:02:48 +00004114 ConstantInt::get(Type::getInt32Ty(II->getContext()),
4115 i, false), "tmp");
Chris Lattnere2ed0572006-04-06 19:19:17 +00004116 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00004117 return CastInst::Create(Instruction::BitCast, Result, CI.getType());
Chris Lattnere2ed0572006-04-06 19:19:17 +00004118 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00004119 }
4120 break;
Chris Lattnere2ed0572006-04-06 19:19:17 +00004121
Chris Lattner0521e3c2008-06-18 04:33:20 +00004122 case Intrinsic::stackrestore: {
4123 // If the save is right next to the restore, remove the restore. This can
4124 // happen when variable allocas are DCE'd.
4125 if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
4126 if (SS->getIntrinsicID() == Intrinsic::stacksave) {
4127 BasicBlock::iterator BI = SS;
4128 if (&*++BI == II)
4129 return EraseInstFromFunction(CI);
Chris Lattnera728ddc2006-01-13 21:28:09 +00004130 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00004131 }
4132
4133 // Scan down this block to see if there is another stack restore in the
4134 // same block without an intervening call/alloca.
4135 BasicBlock::iterator BI = II;
4136 TerminatorInst *TI = II->getParent()->getTerminator();
4137 bool CannotRemove = false;
4138 for (++BI; &*BI != TI; ++BI) {
Victor Hernandez83d63912009-09-18 22:35:49 +00004139 if (isa<AllocaInst>(BI) || isMalloc(BI)) {
Chris Lattner0521e3c2008-06-18 04:33:20 +00004140 CannotRemove = true;
4141 break;
4142 }
Chris Lattneraa0bf522008-06-25 05:59:28 +00004143 if (CallInst *BCI = dyn_cast<CallInst>(BI)) {
4144 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(BCI)) {
4145 // If there is a stackrestore below this one, remove this one.
4146 if (II->getIntrinsicID() == Intrinsic::stackrestore)
4147 return EraseInstFromFunction(CI);
4148 // Otherwise, ignore the intrinsic.
4149 } else {
4150 // If we found a non-intrinsic call, we can't remove the stack
4151 // restore.
Chris Lattnerbf1d8a72008-02-18 06:12:38 +00004152 CannotRemove = true;
4153 break;
4154 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00004155 }
Chris Lattnera728ddc2006-01-13 21:28:09 +00004156 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00004157
4158 // If the stack restore is in a return/unwind block and if there are no
4159 // allocas or calls between the restore and the return, nuke the restore.
4160 if (!CannotRemove && (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)))
4161 return EraseInstFromFunction(CI);
4162 break;
4163 }
Chris Lattner35b9e482004-10-12 04:52:52 +00004164 }
4165
Chris Lattner8b0ea312006-01-13 20:11:04 +00004166 return visitCallSite(II);
Chris Lattner9fe38862003-06-19 17:00:31 +00004167}
4168
4169// InvokeInst simplification
4170//
4171Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
Chris Lattnera44d8a22003-10-07 22:32:43 +00004172 return visitCallSite(&II);
Chris Lattner9fe38862003-06-19 17:00:31 +00004173}
4174
Dale Johannesenda30ccb2008-04-25 21:16:07 +00004175/// isSafeToEliminateVarargsCast - If this cast does not affect the value
4176/// passed through the varargs area, we can eliminate the use of the cast.
Dale Johannesen1f530a52008-04-23 18:34:37 +00004177static bool isSafeToEliminateVarargsCast(const CallSite CS,
4178 const CastInst * const CI,
4179 const TargetData * const TD,
4180 const int ix) {
4181 if (!CI->isLosslessCast())
4182 return false;
4183
4184 // The size of ByVal arguments is derived from the type, so we
4185 // can't change to a type with a different size. If the size were
4186 // passed explicitly we could avoid this check.
Devang Patel05988662008-09-25 21:00:45 +00004187 if (!CS.paramHasAttr(ix, Attribute::ByVal))
Dale Johannesen1f530a52008-04-23 18:34:37 +00004188 return true;
4189
4190 const Type* SrcTy =
4191 cast<PointerType>(CI->getOperand(0)->getType())->getElementType();
4192 const Type* DstTy = cast<PointerType>(CI->getType())->getElementType();
4193 if (!SrcTy->isSized() || !DstTy->isSized())
4194 return false;
Dan Gohmance9fe9f2009-07-21 23:21:54 +00004195 if (!TD || TD->getTypeAllocSize(SrcTy) != TD->getTypeAllocSize(DstTy))
Dale Johannesen1f530a52008-04-23 18:34:37 +00004196 return false;
4197 return true;
4198}
4199
Chris Lattnera44d8a22003-10-07 22:32:43 +00004200// visitCallSite - Improvements for call and invoke instructions.
4201//
4202Instruction *InstCombiner::visitCallSite(CallSite CS) {
Chris Lattner6c266db2003-10-07 22:54:13 +00004203 bool Changed = false;
4204
4205 // If the callee is a constexpr cast of a function, attempt to move the cast
4206 // to the arguments of the call/invoke.
Chris Lattnera44d8a22003-10-07 22:32:43 +00004207 if (transformConstExprCastCall(CS)) return 0;
4208
Chris Lattner6c266db2003-10-07 22:54:13 +00004209 Value *Callee = CS.getCalledValue();
Chris Lattnere87597f2004-10-16 18:11:37 +00004210
Chris Lattner08b22ec2005-05-13 07:09:09 +00004211 if (Function *CalleeF = dyn_cast<Function>(Callee))
4212 if (CalleeF->getCallingConv() != CS.getCallingConv()) {
4213 Instruction *OldCall = CS.getInstruction();
4214 // If the call and callee calling conventions don't match, this call must
4215 // be unreachable, as the call is undefined.
Chris Lattner4de84762010-01-04 07:02:48 +00004216 new StoreInst(ConstantInt::getTrue(Callee->getContext()),
4217 UndefValue::get(Type::getInt1PtrTy(Callee->getContext())),
Owen Andersond672ecb2009-07-03 00:17:18 +00004218 OldCall);
Devang Patel228ebd02009-10-13 22:56:32 +00004219 // If OldCall dues not return void then replaceAllUsesWith undef.
4220 // This allows ValueHandlers and custom metadata to adjust itself.
Devang Patel9674d152009-10-14 17:29:00 +00004221 if (!OldCall->getType()->isVoidTy())
Devang Patel228ebd02009-10-13 22:56:32 +00004222 OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
Chris Lattner08b22ec2005-05-13 07:09:09 +00004223 if (isa<CallInst>(OldCall)) // Not worth removing an invoke here.
4224 return EraseInstFromFunction(*OldCall);
4225 return 0;
4226 }
4227
Chris Lattner17be6352004-10-18 02:59:09 +00004228 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
4229 // This instruction is not reachable, just remove it. We insert a store to
4230 // undef so that we know that this code is not reachable, despite the fact
4231 // that we can't modify the CFG here.
Chris Lattner4de84762010-01-04 07:02:48 +00004232 new StoreInst(ConstantInt::getTrue(Callee->getContext()),
4233 UndefValue::get(Type::getInt1PtrTy(Callee->getContext())),
Chris Lattner17be6352004-10-18 02:59:09 +00004234 CS.getInstruction());
4235
Devang Patel228ebd02009-10-13 22:56:32 +00004236 // If CS dues not return void then replaceAllUsesWith undef.
4237 // This allows ValueHandlers and custom metadata to adjust itself.
Devang Patel9674d152009-10-14 17:29:00 +00004238 if (!CS.getInstruction()->getType()->isVoidTy())
Devang Patel228ebd02009-10-13 22:56:32 +00004239 CS.getInstruction()->
4240 replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
Chris Lattner17be6352004-10-18 02:59:09 +00004241
4242 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
4243 // Don't break the CFG, insert a dummy cond branch.
Gabor Greif051a9502008-04-06 20:25:17 +00004244 BranchInst::Create(II->getNormalDest(), II->getUnwindDest(),
Chris Lattner4de84762010-01-04 07:02:48 +00004245 ConstantInt::getTrue(Callee->getContext()), II);
Chris Lattnere87597f2004-10-16 18:11:37 +00004246 }
Chris Lattner17be6352004-10-18 02:59:09 +00004247 return EraseInstFromFunction(*CS.getInstruction());
4248 }
Chris Lattnere87597f2004-10-16 18:11:37 +00004249
Duncan Sandscdb6d922007-09-17 10:26:40 +00004250 if (BitCastInst *BC = dyn_cast<BitCastInst>(Callee))
4251 if (IntrinsicInst *In = dyn_cast<IntrinsicInst>(BC->getOperand(0)))
4252 if (In->getIntrinsicID() == Intrinsic::init_trampoline)
4253 return transformCallThroughTrampoline(CS);
4254
Chris Lattner6c266db2003-10-07 22:54:13 +00004255 const PointerType *PTy = cast<PointerType>(Callee->getType());
4256 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
4257 if (FTy->isVarArg()) {
Dale Johannesen63e7eb42008-04-23 01:03:05 +00004258 int ix = FTy->getNumParams() + (isa<InvokeInst>(Callee) ? 3 : 1);
Chris Lattner6c266db2003-10-07 22:54:13 +00004259 // See if we can optimize any arguments passed through the varargs area of
4260 // the call.
4261 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
Dale Johannesen1f530a52008-04-23 18:34:37 +00004262 E = CS.arg_end(); I != E; ++I, ++ix) {
4263 CastInst *CI = dyn_cast<CastInst>(*I);
4264 if (CI && isSafeToEliminateVarargsCast(CS, CI, TD, ix)) {
4265 *I = CI->getOperand(0);
4266 Changed = true;
Chris Lattner6c266db2003-10-07 22:54:13 +00004267 }
Dale Johannesen1f530a52008-04-23 18:34:37 +00004268 }
Chris Lattner6c266db2003-10-07 22:54:13 +00004269 }
Misha Brukmanfd939082005-04-21 23:48:37 +00004270
Duncan Sandsf0c33542007-12-19 21:13:37 +00004271 if (isa<InlineAsm>(Callee) && !CS.doesNotThrow()) {
Duncan Sandsece2c042007-12-16 15:51:49 +00004272 // Inline asm calls cannot throw - mark them 'nounwind'.
Duncan Sandsf0c33542007-12-19 21:13:37 +00004273 CS.setDoesNotThrow();
Duncan Sandsece2c042007-12-16 15:51:49 +00004274 Changed = true;
4275 }
4276
Chris Lattner6c266db2003-10-07 22:54:13 +00004277 return Changed ? CS.getInstruction() : 0;
Chris Lattnera44d8a22003-10-07 22:32:43 +00004278}
4279
Chris Lattner9fe38862003-06-19 17:00:31 +00004280// transformConstExprCastCall - If the callee is a constexpr cast of a function,
4281// attempt to move the cast to the arguments of the call/invoke.
4282//
4283bool InstCombiner::transformConstExprCastCall(CallSite CS) {
4284 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
4285 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
Reid Spencer3da59db2006-11-27 01:05:10 +00004286 if (CE->getOpcode() != Instruction::BitCast ||
4287 !isa<Function>(CE->getOperand(0)))
Chris Lattner9fe38862003-06-19 17:00:31 +00004288 return false;
Reid Spencer8863f182004-07-18 00:38:32 +00004289 Function *Callee = cast<Function>(CE->getOperand(0));
Chris Lattner9fe38862003-06-19 17:00:31 +00004290 Instruction *Caller = CS.getInstruction();
Devang Patel05988662008-09-25 21:00:45 +00004291 const AttrListPtr &CallerPAL = CS.getAttributes();
Chris Lattner9fe38862003-06-19 17:00:31 +00004292
4293 // Okay, this is a cast from a function to a different type. Unless doing so
4294 // would cause a type conversion of one of our arguments, change this call to
4295 // be a direct call with arguments casted to the appropriate types.
4296 //
4297 const FunctionType *FT = Callee->getFunctionType();
4298 const Type *OldRetTy = Caller->getType();
Duncan Sandsf413cdf2008-06-01 07:38:42 +00004299 const Type *NewRetTy = FT->getReturnType();
Chris Lattner9fe38862003-06-19 17:00:31 +00004300
Duncan Sandsf413cdf2008-06-01 07:38:42 +00004301 if (isa<StructType>(NewRetTy))
Devang Patel75e6f022008-03-11 18:04:06 +00004302 return false; // TODO: Handle multiple return values.
4303
Chris Lattnerf78616b2004-01-14 06:06:08 +00004304 // Check to see if we are changing the return type...
Duncan Sandsf413cdf2008-06-01 07:38:42 +00004305 if (OldRetTy != NewRetTy) {
Bill Wendlinga6c31122008-05-14 22:45:20 +00004306 if (Callee->isDeclaration() &&
Duncan Sandsf413cdf2008-06-01 07:38:42 +00004307 // Conversion is ok if changing from one pointer type to another or from
4308 // a pointer to an integer of the same size.
Dan Gohmance9fe9f2009-07-21 23:21:54 +00004309 !((isa<PointerType>(OldRetTy) || !TD ||
Owen Anderson1d0be152009-08-13 21:58:54 +00004310 OldRetTy == TD->getIntPtrType(Caller->getContext())) &&
Dan Gohmance9fe9f2009-07-21 23:21:54 +00004311 (isa<PointerType>(NewRetTy) || !TD ||
Owen Anderson1d0be152009-08-13 21:58:54 +00004312 NewRetTy == TD->getIntPtrType(Caller->getContext()))))
Chris Lattnerec479922007-01-06 02:09:32 +00004313 return false; // Cannot transform this return value.
Chris Lattnerf78616b2004-01-14 06:06:08 +00004314
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00004315 if (!Caller->use_empty() &&
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00004316 // void -> non-void is handled specially
Devang Patel9674d152009-10-14 17:29:00 +00004317 !NewRetTy->isVoidTy() && !CastInst::isCastable(NewRetTy, OldRetTy))
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00004318 return false; // Cannot transform this return value.
4319
Chris Lattner58d74912008-03-12 17:45:29 +00004320 if (!CallerPAL.isEmpty() && !Caller->use_empty()) {
Devang Patel19c87462008-09-26 22:53:05 +00004321 Attributes RAttrs = CallerPAL.getRetAttributes();
Devang Patel05988662008-09-25 21:00:45 +00004322 if (RAttrs & Attribute::typeIncompatible(NewRetTy))
Duncan Sands6c3470e2008-01-07 17:16:06 +00004323 return false; // Attribute not compatible with transformed value.
4324 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +00004325
Chris Lattnerf78616b2004-01-14 06:06:08 +00004326 // If the callsite is an invoke instruction, and the return value is used by
4327 // a PHI node in a successor, we cannot change the return type of the call
4328 // because there is no place to put the cast instruction (without breaking
4329 // the critical edge). Bail out in this case.
4330 if (!Caller->use_empty())
4331 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
4332 for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
4333 UI != E; ++UI)
4334 if (PHINode *PN = dyn_cast<PHINode>(*UI))
4335 if (PN->getParent() == II->getNormalDest() ||
Chris Lattneraeb2a1d2004-02-08 21:44:31 +00004336 PN->getParent() == II->getUnwindDest())
Chris Lattnerf78616b2004-01-14 06:06:08 +00004337 return false;
4338 }
Chris Lattner9fe38862003-06-19 17:00:31 +00004339
4340 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
4341 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
Misha Brukmanfd939082005-04-21 23:48:37 +00004342
Chris Lattner9fe38862003-06-19 17:00:31 +00004343 CallSite::arg_iterator AI = CS.arg_begin();
4344 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
4345 const Type *ParamTy = FT->getParamType(i);
Andrew Lenharthb8e604c2006-06-28 01:01:52 +00004346 const Type *ActTy = (*AI)->getType();
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00004347
4348 if (!CastInst::isCastable(ActTy, ParamTy))
Duncan Sandsad9a9e12008-01-06 18:27:01 +00004349 return false; // Cannot transform this parameter value.
4350
Devang Patel19c87462008-09-26 22:53:05 +00004351 if (CallerPAL.getParamAttributes(i + 1)
4352 & Attribute::typeIncompatible(ParamTy))
Chris Lattner58d74912008-03-12 17:45:29 +00004353 return false; // Attribute not compatible with transformed value.
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00004354
Duncan Sandsf413cdf2008-06-01 07:38:42 +00004355 // Converting from one pointer type to another or between a pointer and an
4356 // integer of the same size is safe even if we do not have a body.
Chris Lattnerec479922007-01-06 02:09:32 +00004357 bool isConvertible = ActTy == ParamTy ||
Owen Anderson1d0be152009-08-13 21:58:54 +00004358 (TD && ((isa<PointerType>(ParamTy) ||
4359 ParamTy == TD->getIntPtrType(Caller->getContext())) &&
4360 (isa<PointerType>(ActTy) ||
4361 ActTy == TD->getIntPtrType(Caller->getContext()))));
Reid Spencer5cbf9852007-01-30 20:08:39 +00004362 if (Callee->isDeclaration() && !isConvertible) return false;
Chris Lattner9fe38862003-06-19 17:00:31 +00004363 }
4364
4365 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
Reid Spencer5cbf9852007-01-30 20:08:39 +00004366 Callee->isDeclaration())
Chris Lattner58d74912008-03-12 17:45:29 +00004367 return false; // Do not delete arguments unless we have a function body.
Chris Lattner9fe38862003-06-19 17:00:31 +00004368
Chris Lattner58d74912008-03-12 17:45:29 +00004369 if (FT->getNumParams() < NumActualArgs && FT->isVarArg() &&
4370 !CallerPAL.isEmpty())
Duncan Sandsad9a9e12008-01-06 18:27:01 +00004371 // In this case we have more arguments than the new function type, but we
Duncan Sandse1e520f2008-01-13 08:02:44 +00004372 // won't be dropping them. Check that these extra arguments have attributes
4373 // that are compatible with being a vararg call argument.
Chris Lattner58d74912008-03-12 17:45:29 +00004374 for (unsigned i = CallerPAL.getNumSlots(); i; --i) {
4375 if (CallerPAL.getSlot(i - 1).Index <= FT->getNumParams())
Duncan Sandse1e520f2008-01-13 08:02:44 +00004376 break;
Devang Pateleaf42ab2008-09-23 23:03:40 +00004377 Attributes PAttrs = CallerPAL.getSlot(i - 1).Attrs;
Devang Patel05988662008-09-25 21:00:45 +00004378 if (PAttrs & Attribute::VarArgsIncompatible)
Duncan Sandse1e520f2008-01-13 08:02:44 +00004379 return false;
4380 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +00004381
Chris Lattner9fe38862003-06-19 17:00:31 +00004382 // Okay, we decided that this is a safe thing to do: go ahead and start
4383 // inserting cast instructions as necessary...
4384 std::vector<Value*> Args;
4385 Args.reserve(NumActualArgs);
Devang Patel05988662008-09-25 21:00:45 +00004386 SmallVector<AttributeWithIndex, 8> attrVec;
Duncan Sandsad9a9e12008-01-06 18:27:01 +00004387 attrVec.reserve(NumCommonArgs);
4388
4389 // Get any return attributes.
Devang Patel19c87462008-09-26 22:53:05 +00004390 Attributes RAttrs = CallerPAL.getRetAttributes();
Duncan Sandsad9a9e12008-01-06 18:27:01 +00004391
4392 // If the return value is not being used, the type may not be compatible
4393 // with the existing attributes. Wipe out any problematic attributes.
Devang Patel05988662008-09-25 21:00:45 +00004394 RAttrs &= ~Attribute::typeIncompatible(NewRetTy);
Duncan Sandsad9a9e12008-01-06 18:27:01 +00004395
4396 // Add the new return attributes.
4397 if (RAttrs)
Devang Patel05988662008-09-25 21:00:45 +00004398 attrVec.push_back(AttributeWithIndex::get(0, RAttrs));
Chris Lattner9fe38862003-06-19 17:00:31 +00004399
4400 AI = CS.arg_begin();
4401 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
4402 const Type *ParamTy = FT->getParamType(i);
4403 if ((*AI)->getType() == ParamTy) {
4404 Args.push_back(*AI);
4405 } else {
Reid Spencer8a903db2006-12-18 08:47:13 +00004406 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
Reid Spencerc5b206b2006-12-31 05:48:39 +00004407 false, ParamTy, false);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00004408 Args.push_back(Builder->CreateCast(opcode, *AI, ParamTy, "tmp"));
Chris Lattner9fe38862003-06-19 17:00:31 +00004409 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +00004410
4411 // Add any parameter attributes.
Devang Patel19c87462008-09-26 22:53:05 +00004412 if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
Devang Patel05988662008-09-25 21:00:45 +00004413 attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
Chris Lattner9fe38862003-06-19 17:00:31 +00004414 }
4415
4416 // If the function takes more arguments than the call was taking, add them
Chris Lattnerf925cbd2009-08-30 18:50:58 +00004417 // now.
Chris Lattner9fe38862003-06-19 17:00:31 +00004418 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
Owen Andersona7235ea2009-07-31 20:28:14 +00004419 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
Chris Lattner9fe38862003-06-19 17:00:31 +00004420
Chris Lattnerf925cbd2009-08-30 18:50:58 +00004421 // If we are removing arguments to the function, emit an obnoxious warning.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00004422 if (FT->getNumParams() < NumActualArgs) {
Chris Lattner9fe38862003-06-19 17:00:31 +00004423 if (!FT->isVarArg()) {
Daniel Dunbarce63ffb2009-07-25 00:23:56 +00004424 errs() << "WARNING: While resolving call to function '"
4425 << Callee->getName() << "' arguments were dropped!\n";
Chris Lattner9fe38862003-06-19 17:00:31 +00004426 } else {
Chris Lattnerf925cbd2009-08-30 18:50:58 +00004427 // Add all of the arguments in their promoted form to the arg list.
Chris Lattner9fe38862003-06-19 17:00:31 +00004428 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
4429 const Type *PTy = getPromotedType((*AI)->getType());
4430 if (PTy != (*AI)->getType()) {
4431 // Must promote to pass through va_arg area!
Chris Lattnerf925cbd2009-08-30 18:50:58 +00004432 Instruction::CastOps opcode =
4433 CastInst::getCastOpcode(*AI, false, PTy, false);
4434 Args.push_back(Builder->CreateCast(opcode, *AI, PTy, "tmp"));
Chris Lattner9fe38862003-06-19 17:00:31 +00004435 } else {
4436 Args.push_back(*AI);
4437 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +00004438
Duncan Sandse1e520f2008-01-13 08:02:44 +00004439 // Add any parameter attributes.
Devang Patel19c87462008-09-26 22:53:05 +00004440 if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
Devang Patel05988662008-09-25 21:00:45 +00004441 attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
Duncan Sandse1e520f2008-01-13 08:02:44 +00004442 }
Chris Lattner9fe38862003-06-19 17:00:31 +00004443 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00004444 }
Chris Lattner9fe38862003-06-19 17:00:31 +00004445
Devang Patel19c87462008-09-26 22:53:05 +00004446 if (Attributes FnAttrs = CallerPAL.getFnAttributes())
4447 attrVec.push_back(AttributeWithIndex::get(~0, FnAttrs));
4448
Devang Patel9674d152009-10-14 17:29:00 +00004449 if (NewRetTy->isVoidTy())
Chris Lattner6934a042007-02-11 01:23:03 +00004450 Caller->setName(""); // Void type should not have a name.
Chris Lattner9fe38862003-06-19 17:00:31 +00004451
Eric Christophera66297a2009-07-25 02:45:27 +00004452 const AttrListPtr &NewCallerPAL = AttrListPtr::get(attrVec.begin(),
4453 attrVec.end());
Duncan Sandsad9a9e12008-01-06 18:27:01 +00004454
Chris Lattner9fe38862003-06-19 17:00:31 +00004455 Instruction *NC;
4456 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Gabor Greif051a9502008-04-06 20:25:17 +00004457 NC = InvokeInst::Create(Callee, II->getNormalDest(), II->getUnwindDest(),
Gabor Greifb1dbcd82008-05-15 10:04:30 +00004458 Args.begin(), Args.end(),
4459 Caller->getName(), Caller);
Reid Spencered3fa852007-07-30 19:53:57 +00004460 cast<InvokeInst>(NC)->setCallingConv(II->getCallingConv());
Devang Patel05988662008-09-25 21:00:45 +00004461 cast<InvokeInst>(NC)->setAttributes(NewCallerPAL);
Chris Lattner9fe38862003-06-19 17:00:31 +00004462 } else {
Gabor Greif051a9502008-04-06 20:25:17 +00004463 NC = CallInst::Create(Callee, Args.begin(), Args.end(),
4464 Caller->getName(), Caller);
Duncan Sandsdc024672007-11-27 13:23:08 +00004465 CallInst *CI = cast<CallInst>(Caller);
4466 if (CI->isTailCall())
Chris Lattnera9e92112005-05-06 06:48:21 +00004467 cast<CallInst>(NC)->setTailCall();
Duncan Sandsdc024672007-11-27 13:23:08 +00004468 cast<CallInst>(NC)->setCallingConv(CI->getCallingConv());
Devang Patel05988662008-09-25 21:00:45 +00004469 cast<CallInst>(NC)->setAttributes(NewCallerPAL);
Chris Lattner9fe38862003-06-19 17:00:31 +00004470 }
4471
Chris Lattner6934a042007-02-11 01:23:03 +00004472 // Insert a cast of the return type as necessary.
Chris Lattner9fe38862003-06-19 17:00:31 +00004473 Value *NV = NC;
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00004474 if (OldRetTy != NV->getType() && !Caller->use_empty()) {
Devang Patel9674d152009-10-14 17:29:00 +00004475 if (!NV->getType()->isVoidTy()) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00004476 Instruction::CastOps opcode = CastInst::getCastOpcode(NC, false,
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00004477 OldRetTy, false);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004478 NV = NC = CastInst::Create(opcode, NC, OldRetTy, "tmp");
Chris Lattnerbb609042003-10-30 00:46:41 +00004479
4480 // If this is an invoke instruction, we should insert it after the first
4481 // non-phi, instruction in the normal successor block.
4482 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Dan Gohman02dea8b2008-05-23 21:05:58 +00004483 BasicBlock::iterator I = II->getNormalDest()->getFirstNonPHI();
Chris Lattnerbb609042003-10-30 00:46:41 +00004484 InsertNewInstBefore(NC, *I);
4485 } else {
4486 // Otherwise, it's a call, just insert cast right after the call instr
4487 InsertNewInstBefore(NC, *Caller);
4488 }
Chris Lattnere5ecdb52009-08-30 06:22:51 +00004489 Worklist.AddUsersToWorkList(*Caller);
Chris Lattner9fe38862003-06-19 17:00:31 +00004490 } else {
Owen Anderson9e9a0d52009-07-30 23:03:37 +00004491 NV = UndefValue::get(Caller->getType());
Chris Lattner9fe38862003-06-19 17:00:31 +00004492 }
4493 }
4494
Devang Patel1bf5ebc2009-10-13 21:41:20 +00004495
Chris Lattner931f8f32009-08-31 05:17:58 +00004496 if (!Caller->use_empty())
Chris Lattner9fe38862003-06-19 17:00:31 +00004497 Caller->replaceAllUsesWith(NV);
Chris Lattner931f8f32009-08-31 05:17:58 +00004498
4499 EraseInstFromFunction(*Caller);
Chris Lattner9fe38862003-06-19 17:00:31 +00004500 return true;
4501}
4502
Duncan Sandscdb6d922007-09-17 10:26:40 +00004503// transformCallThroughTrampoline - Turn a call to a function created by the
4504// init_trampoline intrinsic into a direct call to the underlying function.
4505//
4506Instruction *InstCombiner::transformCallThroughTrampoline(CallSite CS) {
4507 Value *Callee = CS.getCalledValue();
4508 const PointerType *PTy = cast<PointerType>(Callee->getType());
4509 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
Devang Patel05988662008-09-25 21:00:45 +00004510 const AttrListPtr &Attrs = CS.getAttributes();
Duncan Sandsb0c9b932008-01-14 19:52:09 +00004511
4512 // If the call already has the 'nest' attribute somewhere then give up -
4513 // otherwise 'nest' would occur twice after splicing in the chain.
Devang Patel05988662008-09-25 21:00:45 +00004514 if (Attrs.hasAttrSomewhere(Attribute::Nest))
Duncan Sandsb0c9b932008-01-14 19:52:09 +00004515 return 0;
Duncan Sandscdb6d922007-09-17 10:26:40 +00004516
4517 IntrinsicInst *Tramp =
4518 cast<IntrinsicInst>(cast<BitCastInst>(Callee)->getOperand(0));
4519
Anton Korobeynikov0b12ecf2008-05-07 22:54:15 +00004520 Function *NestF = cast<Function>(Tramp->getOperand(2)->stripPointerCasts());
Duncan Sandscdb6d922007-09-17 10:26:40 +00004521 const PointerType *NestFPTy = cast<PointerType>(NestF->getType());
4522 const FunctionType *NestFTy = cast<FunctionType>(NestFPTy->getElementType());
4523
Devang Patel05988662008-09-25 21:00:45 +00004524 const AttrListPtr &NestAttrs = NestF->getAttributes();
Chris Lattner58d74912008-03-12 17:45:29 +00004525 if (!NestAttrs.isEmpty()) {
Duncan Sandscdb6d922007-09-17 10:26:40 +00004526 unsigned NestIdx = 1;
4527 const Type *NestTy = 0;
Devang Patel05988662008-09-25 21:00:45 +00004528 Attributes NestAttr = Attribute::None;
Duncan Sandscdb6d922007-09-17 10:26:40 +00004529
4530 // Look for a parameter marked with the 'nest' attribute.
4531 for (FunctionType::param_iterator I = NestFTy->param_begin(),
4532 E = NestFTy->param_end(); I != E; ++NestIdx, ++I)
Devang Patel05988662008-09-25 21:00:45 +00004533 if (NestAttrs.paramHasAttr(NestIdx, Attribute::Nest)) {
Duncan Sandscdb6d922007-09-17 10:26:40 +00004534 // Record the parameter type and any other attributes.
4535 NestTy = *I;
Devang Patel19c87462008-09-26 22:53:05 +00004536 NestAttr = NestAttrs.getParamAttributes(NestIdx);
Duncan Sandscdb6d922007-09-17 10:26:40 +00004537 break;
4538 }
4539
4540 if (NestTy) {
4541 Instruction *Caller = CS.getInstruction();
4542 std::vector<Value*> NewArgs;
4543 NewArgs.reserve(unsigned(CS.arg_end()-CS.arg_begin())+1);
4544
Devang Patel05988662008-09-25 21:00:45 +00004545 SmallVector<AttributeWithIndex, 8> NewAttrs;
Chris Lattner58d74912008-03-12 17:45:29 +00004546 NewAttrs.reserve(Attrs.getNumSlots() + 1);
Duncan Sandsb0c9b932008-01-14 19:52:09 +00004547
Duncan Sandscdb6d922007-09-17 10:26:40 +00004548 // Insert the nest argument into the call argument list, which may
Duncan Sandsb0c9b932008-01-14 19:52:09 +00004549 // mean appending it. Likewise for attributes.
4550
Devang Patel19c87462008-09-26 22:53:05 +00004551 // Add any result attributes.
4552 if (Attributes Attr = Attrs.getRetAttributes())
Devang Patel05988662008-09-25 21:00:45 +00004553 NewAttrs.push_back(AttributeWithIndex::get(0, Attr));
Duncan Sandsb0c9b932008-01-14 19:52:09 +00004554
Duncan Sandscdb6d922007-09-17 10:26:40 +00004555 {
4556 unsigned Idx = 1;
4557 CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
4558 do {
4559 if (Idx == NestIdx) {
Duncan Sandsb0c9b932008-01-14 19:52:09 +00004560 // Add the chain argument and attributes.
Duncan Sandscdb6d922007-09-17 10:26:40 +00004561 Value *NestVal = Tramp->getOperand(3);
4562 if (NestVal->getType() != NestTy)
4563 NestVal = new BitCastInst(NestVal, NestTy, "nest", Caller);
4564 NewArgs.push_back(NestVal);
Devang Patel05988662008-09-25 21:00:45 +00004565 NewAttrs.push_back(AttributeWithIndex::get(NestIdx, NestAttr));
Duncan Sandscdb6d922007-09-17 10:26:40 +00004566 }
4567
4568 if (I == E)
4569 break;
4570
Duncan Sandsb0c9b932008-01-14 19:52:09 +00004571 // Add the original argument and attributes.
Duncan Sandscdb6d922007-09-17 10:26:40 +00004572 NewArgs.push_back(*I);
Devang Patel19c87462008-09-26 22:53:05 +00004573 if (Attributes Attr = Attrs.getParamAttributes(Idx))
Duncan Sandsb0c9b932008-01-14 19:52:09 +00004574 NewAttrs.push_back
Devang Patel05988662008-09-25 21:00:45 +00004575 (AttributeWithIndex::get(Idx + (Idx >= NestIdx), Attr));
Duncan Sandscdb6d922007-09-17 10:26:40 +00004576
4577 ++Idx, ++I;
4578 } while (1);
4579 }
4580
Devang Patel19c87462008-09-26 22:53:05 +00004581 // Add any function attributes.
4582 if (Attributes Attr = Attrs.getFnAttributes())
4583 NewAttrs.push_back(AttributeWithIndex::get(~0, Attr));
4584
Duncan Sandscdb6d922007-09-17 10:26:40 +00004585 // The trampoline may have been bitcast to a bogus type (FTy).
4586 // Handle this by synthesizing a new function type, equal to FTy
Duncan Sandsb0c9b932008-01-14 19:52:09 +00004587 // with the chain parameter inserted.
Duncan Sandscdb6d922007-09-17 10:26:40 +00004588
Duncan Sandscdb6d922007-09-17 10:26:40 +00004589 std::vector<const Type*> NewTypes;
Duncan Sandscdb6d922007-09-17 10:26:40 +00004590 NewTypes.reserve(FTy->getNumParams()+1);
4591
Duncan Sandscdb6d922007-09-17 10:26:40 +00004592 // Insert the chain's type into the list of parameter types, which may
Duncan Sandsb0c9b932008-01-14 19:52:09 +00004593 // mean appending it.
Duncan Sandscdb6d922007-09-17 10:26:40 +00004594 {
4595 unsigned Idx = 1;
4596 FunctionType::param_iterator I = FTy->param_begin(),
4597 E = FTy->param_end();
4598
4599 do {
Duncan Sandsb0c9b932008-01-14 19:52:09 +00004600 if (Idx == NestIdx)
4601 // Add the chain's type.
Duncan Sandscdb6d922007-09-17 10:26:40 +00004602 NewTypes.push_back(NestTy);
Duncan Sandscdb6d922007-09-17 10:26:40 +00004603
4604 if (I == E)
4605 break;
4606
Duncan Sandsb0c9b932008-01-14 19:52:09 +00004607 // Add the original type.
Duncan Sandscdb6d922007-09-17 10:26:40 +00004608 NewTypes.push_back(*I);
Duncan Sandscdb6d922007-09-17 10:26:40 +00004609
4610 ++Idx, ++I;
4611 } while (1);
4612 }
4613
4614 // Replace the trampoline call with a direct call. Let the generic
4615 // code sort out any function type mismatches.
Owen Andersondebcb012009-07-29 22:17:13 +00004616 FunctionType *NewFTy = FunctionType::get(FTy->getReturnType(), NewTypes,
Owen Andersond672ecb2009-07-03 00:17:18 +00004617 FTy->isVarArg());
4618 Constant *NewCallee =
Owen Andersondebcb012009-07-29 22:17:13 +00004619 NestF->getType() == PointerType::getUnqual(NewFTy) ?
Owen Andersonbaf3c402009-07-29 18:55:55 +00004620 NestF : ConstantExpr::getBitCast(NestF,
Owen Andersondebcb012009-07-29 22:17:13 +00004621 PointerType::getUnqual(NewFTy));
Eric Christophera66297a2009-07-25 02:45:27 +00004622 const AttrListPtr &NewPAL = AttrListPtr::get(NewAttrs.begin(),
4623 NewAttrs.end());
Duncan Sandscdb6d922007-09-17 10:26:40 +00004624
4625 Instruction *NewCaller;
4626 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Gabor Greif051a9502008-04-06 20:25:17 +00004627 NewCaller = InvokeInst::Create(NewCallee,
4628 II->getNormalDest(), II->getUnwindDest(),
4629 NewArgs.begin(), NewArgs.end(),
4630 Caller->getName(), Caller);
Duncan Sandscdb6d922007-09-17 10:26:40 +00004631 cast<InvokeInst>(NewCaller)->setCallingConv(II->getCallingConv());
Devang Patel05988662008-09-25 21:00:45 +00004632 cast<InvokeInst>(NewCaller)->setAttributes(NewPAL);
Duncan Sandscdb6d922007-09-17 10:26:40 +00004633 } else {
Gabor Greif051a9502008-04-06 20:25:17 +00004634 NewCaller = CallInst::Create(NewCallee, NewArgs.begin(), NewArgs.end(),
4635 Caller->getName(), Caller);
Duncan Sandscdb6d922007-09-17 10:26:40 +00004636 if (cast<CallInst>(Caller)->isTailCall())
4637 cast<CallInst>(NewCaller)->setTailCall();
4638 cast<CallInst>(NewCaller)->
4639 setCallingConv(cast<CallInst>(Caller)->getCallingConv());
Devang Patel05988662008-09-25 21:00:45 +00004640 cast<CallInst>(NewCaller)->setAttributes(NewPAL);
Duncan Sandscdb6d922007-09-17 10:26:40 +00004641 }
Devang Patel9674d152009-10-14 17:29:00 +00004642 if (!Caller->getType()->isVoidTy())
Duncan Sandscdb6d922007-09-17 10:26:40 +00004643 Caller->replaceAllUsesWith(NewCaller);
4644 Caller->eraseFromParent();
Chris Lattner7a1e9242009-08-30 06:13:40 +00004645 Worklist.Remove(Caller);
Duncan Sandscdb6d922007-09-17 10:26:40 +00004646 return 0;
4647 }
4648 }
4649
4650 // Replace the trampoline call with a direct call. Since there is no 'nest'
4651 // parameter, there is no need to adjust the argument list. Let the generic
4652 // code sort out any function type mismatches.
4653 Constant *NewCallee =
Owen Andersond672ecb2009-07-03 00:17:18 +00004654 NestF->getType() == PTy ? NestF :
Owen Andersonbaf3c402009-07-29 18:55:55 +00004655 ConstantExpr::getBitCast(NestF, PTy);
Duncan Sandscdb6d922007-09-17 10:26:40 +00004656 CS.setCalledFunction(NewCallee);
4657 return CS.getInstruction();
4658}
4659
Reid Spencere4d87aa2006-12-23 06:05:41 +00004660
Chris Lattner473945d2002-05-06 18:06:38 +00004661
Chris Lattner7e708292002-06-25 16:13:24 +00004662Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
Chris Lattnerc514c1f2009-11-27 00:29:05 +00004663 SmallVector<Value*, 8> Ops(GEP.op_begin(), GEP.op_end());
4664
4665 if (Value *V = SimplifyGEPInst(&Ops[0], Ops.size(), TD))
4666 return ReplaceInstUsesWith(GEP, V);
4667
Chris Lattner620ce142004-05-07 22:09:22 +00004668 Value *PtrOp = GEP.getOperand(0);
Chris Lattnerc6bd1952004-02-22 05:25:17 +00004669
Chris Lattnere87597f2004-10-16 18:11:37 +00004670 if (isa<UndefValue>(GEP.getOperand(0)))
Owen Anderson9e9a0d52009-07-30 23:03:37 +00004671 return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00004672
Chris Lattner28977af2004-04-05 01:30:19 +00004673 // Eliminate unneeded casts for indices.
Chris Lattnerccf4b342009-08-30 04:49:01 +00004674 if (TD) {
4675 bool MadeChange = false;
4676 unsigned PtrSize = TD->getPointerSizeInBits();
4677
4678 gep_type_iterator GTI = gep_type_begin(GEP);
4679 for (User::op_iterator I = GEP.op_begin() + 1, E = GEP.op_end();
4680 I != E; ++I, ++GTI) {
4681 if (!isa<SequentialType>(*GTI)) continue;
4682
Chris Lattnercb69a4e2004-04-07 18:38:20 +00004683 // If we are using a wider index than needed for this platform, shrink it
Chris Lattnerccf4b342009-08-30 04:49:01 +00004684 // to what we need. If narrower, sign-extend it to what we need. This
4685 // explicit cast can make subsequent optimizations more obvious.
4686 unsigned OpBits = cast<IntegerType>((*I)->getType())->getBitWidth();
Chris Lattnerccf4b342009-08-30 04:49:01 +00004687 if (OpBits == PtrSize)
4688 continue;
4689
Chris Lattner2345d1d2009-08-30 20:01:10 +00004690 *I = Builder->CreateIntCast(*I, TD->getIntPtrType(GEP.getContext()),true);
Chris Lattnerccf4b342009-08-30 04:49:01 +00004691 MadeChange = true;
Chris Lattner28977af2004-04-05 01:30:19 +00004692 }
Chris Lattnerccf4b342009-08-30 04:49:01 +00004693 if (MadeChange) return &GEP;
Chris Lattnerdb9654e2007-03-25 20:43:09 +00004694 }
Chris Lattner28977af2004-04-05 01:30:19 +00004695
Chris Lattner90ac28c2002-08-02 19:29:35 +00004696 // Combine Indices - If the source pointer to this getelementptr instruction
4697 // is a getelementptr instruction, combine the indices of the two
4698 // getelementptr instructions into a single instruction.
4699 //
Dan Gohmand6aa02d2009-07-28 01:40:03 +00004700 if (GEPOperator *Src = dyn_cast<GEPOperator>(PtrOp)) {
Chris Lattner620ce142004-05-07 22:09:22 +00004701 // Note that if our source is a gep chain itself that we wait for that
4702 // chain to be resolved before we perform this transformation. This
4703 // avoids us creating a TON of code in some cases.
4704 //
Chris Lattnerf9b91bb2009-08-30 05:08:50 +00004705 if (GetElementPtrInst *SrcGEP =
4706 dyn_cast<GetElementPtrInst>(Src->getOperand(0)))
4707 if (SrcGEP->getNumOperands() == 2)
4708 return 0; // Wait until our source is folded to completion.
Chris Lattner620ce142004-05-07 22:09:22 +00004709
Chris Lattner72588fc2007-02-15 22:48:32 +00004710 SmallVector<Value*, 8> Indices;
Chris Lattner620ce142004-05-07 22:09:22 +00004711
4712 // Find out whether the last index in the source GEP is a sequential idx.
4713 bool EndsWithSequential = false;
Chris Lattnerab984842009-08-30 05:30:55 +00004714 for (gep_type_iterator I = gep_type_begin(*Src), E = gep_type_end(*Src);
4715 I != E; ++I)
Chris Lattnerbe97b4e2004-05-08 22:41:42 +00004716 EndsWithSequential = !isa<StructType>(*I);
Misha Brukmanfd939082005-04-21 23:48:37 +00004717
Chris Lattner90ac28c2002-08-02 19:29:35 +00004718 // Can we combine the two pointer arithmetics offsets?
Chris Lattner620ce142004-05-07 22:09:22 +00004719 if (EndsWithSequential) {
Chris Lattnerdecd0812003-03-05 22:33:14 +00004720 // Replace: gep (gep %P, long B), long A, ...
4721 // With: T = long A+B; gep %P, T, ...
4722 //
Chris Lattnerf9b91bb2009-08-30 05:08:50 +00004723 Value *Sum;
4724 Value *SO1 = Src->getOperand(Src->getNumOperands()-1);
4725 Value *GO1 = GEP.getOperand(1);
Owen Andersona7235ea2009-07-31 20:28:14 +00004726 if (SO1 == Constant::getNullValue(SO1->getType())) {
Chris Lattner28977af2004-04-05 01:30:19 +00004727 Sum = GO1;
Owen Andersona7235ea2009-07-31 20:28:14 +00004728 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
Chris Lattner28977af2004-04-05 01:30:19 +00004729 Sum = SO1;
4730 } else {
Chris Lattnerab984842009-08-30 05:30:55 +00004731 // If they aren't the same type, then the input hasn't been processed
4732 // by the loop above yet (which canonicalizes sequential index types to
4733 // intptr_t). Just avoid transforming this until the input has been
4734 // normalized.
4735 if (SO1->getType() != GO1->getType())
4736 return 0;
Chris Lattnerf925cbd2009-08-30 18:50:58 +00004737 Sum = Builder->CreateAdd(SO1, GO1, PtrOp->getName()+".sum");
Chris Lattner28977af2004-04-05 01:30:19 +00004738 }
Chris Lattner620ce142004-05-07 22:09:22 +00004739
Chris Lattnerab984842009-08-30 05:30:55 +00004740 // Update the GEP in place if possible.
Chris Lattnerf9b91bb2009-08-30 05:08:50 +00004741 if (Src->getNumOperands() == 2) {
4742 GEP.setOperand(0, Src->getOperand(0));
Chris Lattner620ce142004-05-07 22:09:22 +00004743 GEP.setOperand(1, Sum);
4744 return &GEP;
Chris Lattner620ce142004-05-07 22:09:22 +00004745 }
Chris Lattnerab984842009-08-30 05:30:55 +00004746 Indices.append(Src->op_begin()+1, Src->op_end()-1);
Chris Lattnerccf4b342009-08-30 04:49:01 +00004747 Indices.push_back(Sum);
Chris Lattnerab984842009-08-30 05:30:55 +00004748 Indices.append(GEP.op_begin()+2, GEP.op_end());
Misha Brukmanfd939082005-04-21 23:48:37 +00004749 } else if (isa<Constant>(*GEP.idx_begin()) &&
Chris Lattner28977af2004-04-05 01:30:19 +00004750 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
Chris Lattnerf9b91bb2009-08-30 05:08:50 +00004751 Src->getNumOperands() != 1) {
Chris Lattner90ac28c2002-08-02 19:29:35 +00004752 // Otherwise we can do the fold if the first index of the GEP is a zero
Chris Lattnerab984842009-08-30 05:30:55 +00004753 Indices.append(Src->op_begin()+1, Src->op_end());
4754 Indices.append(GEP.idx_begin()+1, GEP.idx_end());
Chris Lattner90ac28c2002-08-02 19:29:35 +00004755 }
4756
Dan Gohmanf8dbee72009-09-07 23:54:19 +00004757 if (!Indices.empty())
4758 return (cast<GEPOperator>(&GEP)->isInBounds() &&
4759 Src->isInBounds()) ?
4760 GetElementPtrInst::CreateInBounds(Src->getOperand(0), Indices.begin(),
4761 Indices.end(), GEP.getName()) :
Chris Lattnerf9b91bb2009-08-30 05:08:50 +00004762 GetElementPtrInst::Create(Src->getOperand(0), Indices.begin(),
Chris Lattnerccf4b342009-08-30 04:49:01 +00004763 Indices.end(), GEP.getName());
Chris Lattner6e24d832009-08-30 05:00:50 +00004764 }
4765
Chris Lattnerf9b91bb2009-08-30 05:08:50 +00004766 // Handle gep(bitcast x) and gep(gep x, 0, 0, 0).
4767 if (Value *X = getBitCastOperand(PtrOp)) {
Chris Lattner6e24d832009-08-30 05:00:50 +00004768 assert(isa<PointerType>(X->getType()) && "Must be cast from pointer");
Chris Lattner963f4ba2009-08-30 20:36:46 +00004769
Chris Lattner2de23192009-08-30 20:38:21 +00004770 // If the input bitcast is actually "bitcast(bitcast(x))", then we don't
4771 // want to change the gep until the bitcasts are eliminated.
4772 if (getBitCastOperand(X)) {
4773 Worklist.AddValue(PtrOp);
4774 return 0;
4775 }
4776
Chris Lattnerc514c1f2009-11-27 00:29:05 +00004777 bool HasZeroPointerIndex = false;
4778 if (ConstantInt *C = dyn_cast<ConstantInt>(GEP.getOperand(1)))
4779 HasZeroPointerIndex = C->isZero();
4780
Chris Lattner963f4ba2009-08-30 20:36:46 +00004781 // Transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ...
4782 // into : GEP [10 x i8]* X, i32 0, ...
4783 //
4784 // Likewise, transform: GEP (bitcast i8* X to [0 x i8]*), i32 0, ...
4785 // into : GEP i8* X, ...
4786 //
4787 // This occurs when the program declares an array extern like "int X[];"
Chris Lattner6e24d832009-08-30 05:00:50 +00004788 if (HasZeroPointerIndex) {
Chris Lattnereed48272005-09-13 00:40:14 +00004789 const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
4790 const PointerType *XTy = cast<PointerType>(X->getType());
Duncan Sands5b7cfb02009-03-02 09:18:21 +00004791 if (const ArrayType *CATy =
4792 dyn_cast<ArrayType>(CPTy->getElementType())) {
4793 // GEP (bitcast i8* X to [0 x i8]*), i32 0, ... ?
4794 if (CATy->getElementType() == XTy->getElementType()) {
4795 // -> GEP i8* X, ...
4796 SmallVector<Value*, 8> Indices(GEP.idx_begin()+1, GEP.idx_end());
Dan Gohmanf8dbee72009-09-07 23:54:19 +00004797 return cast<GEPOperator>(&GEP)->isInBounds() ?
4798 GetElementPtrInst::CreateInBounds(X, Indices.begin(), Indices.end(),
4799 GEP.getName()) :
Dan Gohmand6aa02d2009-07-28 01:40:03 +00004800 GetElementPtrInst::Create(X, Indices.begin(), Indices.end(),
4801 GEP.getName());
Chris Lattner963f4ba2009-08-30 20:36:46 +00004802 }
4803
4804 if (const ArrayType *XATy = dyn_cast<ArrayType>(XTy->getElementType())){
Duncan Sands5b7cfb02009-03-02 09:18:21 +00004805 // GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ... ?
Chris Lattnereed48272005-09-13 00:40:14 +00004806 if (CATy->getElementType() == XATy->getElementType()) {
Duncan Sands5b7cfb02009-03-02 09:18:21 +00004807 // -> GEP [10 x i8]* X, i32 0, ...
Chris Lattnereed48272005-09-13 00:40:14 +00004808 // At this point, we know that the cast source type is a pointer
4809 // to an array of the same type as the destination pointer
4810 // array. Because the array type is never stepped over (there
4811 // is a leading zero) we can fold the cast into this GEP.
4812 GEP.setOperand(0, X);
4813 return &GEP;
4814 }
Duncan Sands5b7cfb02009-03-02 09:18:21 +00004815 }
4816 }
Chris Lattnereed48272005-09-13 00:40:14 +00004817 } else if (GEP.getNumOperands() == 2) {
4818 // Transform things like:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +00004819 // %t = getelementptr i32* bitcast ([2 x i32]* %str to i32*), i32 %V
4820 // into: %t1 = getelementptr [2 x i32]* %str, i32 0, i32 %V; bitcast
Chris Lattnereed48272005-09-13 00:40:14 +00004821 const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
4822 const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
Dan Gohmance9fe9f2009-07-21 23:21:54 +00004823 if (TD && isa<ArrayType>(SrcElTy) &&
Duncan Sands777d2302009-05-09 07:06:46 +00004824 TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
4825 TD->getTypeAllocSize(ResElTy)) {
David Greeneb8f74792007-09-04 15:46:09 +00004826 Value *Idx[2];
Chris Lattner4de84762010-01-04 07:02:48 +00004827 Idx[0] = Constant::getNullValue(Type::getInt32Ty(GEP.getContext()));
David Greeneb8f74792007-09-04 15:46:09 +00004828 Idx[1] = GEP.getOperand(1);
Dan Gohmanf8dbee72009-09-07 23:54:19 +00004829 Value *NewGEP = cast<GEPOperator>(&GEP)->isInBounds() ?
4830 Builder->CreateInBoundsGEP(X, Idx, Idx + 2, GEP.getName()) :
Chris Lattnerf925cbd2009-08-30 18:50:58 +00004831 Builder->CreateGEP(X, Idx, Idx + 2, GEP.getName());
Reid Spencer3da59db2006-11-27 01:05:10 +00004832 // V and GEP are both pointer types --> BitCast
Chris Lattnerf925cbd2009-08-30 18:50:58 +00004833 return new BitCastInst(NewGEP, GEP.getType());
Chris Lattnerc6bd1952004-02-22 05:25:17 +00004834 }
Chris Lattner7835cdd2005-09-13 18:36:04 +00004835
4836 // Transform things like:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +00004837 // getelementptr i8* bitcast ([100 x double]* X to i8*), i32 %tmp
Chris Lattner7835cdd2005-09-13 18:36:04 +00004838 // (where tmp = 8*tmp2) into:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +00004839 // getelementptr [100 x double]* %arr, i32 0, i32 %tmp2; bitcast
Chris Lattner7835cdd2005-09-13 18:36:04 +00004840
Chris Lattner4de84762010-01-04 07:02:48 +00004841 if (TD && isa<ArrayType>(SrcElTy) &&
4842 ResElTy == Type::getInt8Ty(GEP.getContext())) {
Chris Lattner7835cdd2005-09-13 18:36:04 +00004843 uint64_t ArrayEltSize =
Duncan Sands777d2302009-05-09 07:06:46 +00004844 TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType());
Chris Lattner7835cdd2005-09-13 18:36:04 +00004845
4846 // Check to see if "tmp" is a scale by a multiple of ArrayEltSize. We
4847 // allow either a mul, shift, or constant here.
4848 Value *NewIdx = 0;
4849 ConstantInt *Scale = 0;
4850 if (ArrayEltSize == 1) {
4851 NewIdx = GEP.getOperand(1);
Chris Lattnerab984842009-08-30 05:30:55 +00004852 Scale = ConstantInt::get(cast<IntegerType>(NewIdx->getType()), 1);
Chris Lattner7835cdd2005-09-13 18:36:04 +00004853 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
Owen Andersoneed707b2009-07-24 23:12:02 +00004854 NewIdx = ConstantInt::get(CI->getType(), 1);
Chris Lattner7835cdd2005-09-13 18:36:04 +00004855 Scale = CI;
4856 } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
4857 if (Inst->getOpcode() == Instruction::Shl &&
4858 isa<ConstantInt>(Inst->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00004859 ConstantInt *ShAmt = cast<ConstantInt>(Inst->getOperand(1));
4860 uint32_t ShAmtVal = ShAmt->getLimitedValue(64);
Owen Andersoneed707b2009-07-24 23:12:02 +00004861 Scale = ConstantInt::get(cast<IntegerType>(Inst->getType()),
Dan Gohman6de29f82009-06-15 22:12:54 +00004862 1ULL << ShAmtVal);
Chris Lattner7835cdd2005-09-13 18:36:04 +00004863 NewIdx = Inst->getOperand(0);
4864 } else if (Inst->getOpcode() == Instruction::Mul &&
4865 isa<ConstantInt>(Inst->getOperand(1))) {
4866 Scale = cast<ConstantInt>(Inst->getOperand(1));
4867 NewIdx = Inst->getOperand(0);
4868 }
4869 }
Wojciech Matyjewiczed223252007-12-12 15:21:32 +00004870
Chris Lattner7835cdd2005-09-13 18:36:04 +00004871 // If the index will be to exactly the right offset with the scale taken
Wojciech Matyjewiczed223252007-12-12 15:21:32 +00004872 // out, perform the transformation. Note, we don't know whether Scale is
4873 // signed or not. We'll use unsigned version of division/modulo
4874 // operation after making sure Scale doesn't have the sign bit set.
Chris Lattner58b1ac72009-02-25 18:20:01 +00004875 if (ArrayEltSize && Scale && Scale->getSExtValue() >= 0LL &&
Wojciech Matyjewiczed223252007-12-12 15:21:32 +00004876 Scale->getZExtValue() % ArrayEltSize == 0) {
Owen Andersoneed707b2009-07-24 23:12:02 +00004877 Scale = ConstantInt::get(Scale->getType(),
Wojciech Matyjewiczed223252007-12-12 15:21:32 +00004878 Scale->getZExtValue() / ArrayEltSize);
Reid Spencerb83eb642006-10-20 07:07:24 +00004879 if (Scale->getZExtValue() != 1) {
Chris Lattner878daed2009-08-30 05:56:44 +00004880 Constant *C = ConstantExpr::getIntegerCast(Scale, NewIdx->getType(),
4881 false /*ZExt*/);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00004882 NewIdx = Builder->CreateMul(NewIdx, C, "idxscale");
Chris Lattner7835cdd2005-09-13 18:36:04 +00004883 }
4884
4885 // Insert the new GEP instruction.
David Greeneb8f74792007-09-04 15:46:09 +00004886 Value *Idx[2];
Chris Lattner4de84762010-01-04 07:02:48 +00004887 Idx[0] = Constant::getNullValue(Type::getInt32Ty(GEP.getContext()));
David Greeneb8f74792007-09-04 15:46:09 +00004888 Idx[1] = NewIdx;
Dan Gohmanf8dbee72009-09-07 23:54:19 +00004889 Value *NewGEP = cast<GEPOperator>(&GEP)->isInBounds() ?
4890 Builder->CreateInBoundsGEP(X, Idx, Idx + 2, GEP.getName()) :
4891 Builder->CreateGEP(X, Idx, Idx + 2, GEP.getName());
Reid Spencer3da59db2006-11-27 01:05:10 +00004892 // The NewGEP must be pointer typed, so must the old one -> BitCast
4893 return new BitCastInst(NewGEP, GEP.getType());
Chris Lattner7835cdd2005-09-13 18:36:04 +00004894 }
4895 }
Chris Lattnerc6bd1952004-02-22 05:25:17 +00004896 }
Chris Lattner8a2a3112001-12-14 16:52:21 +00004897 }
Chris Lattner58407792009-01-09 04:53:57 +00004898
Chris Lattner46cd5a12009-01-09 05:44:56 +00004899 /// See if we can simplify:
Chris Lattner873ff012009-08-30 05:55:36 +00004900 /// X = bitcast A* to B*
Chris Lattner46cd5a12009-01-09 05:44:56 +00004901 /// Y = gep X, <...constant indices...>
4902 /// into a gep of the original struct. This is important for SROA and alias
4903 /// analysis of unions. If "A" is also a bitcast, wait for A/X to be merged.
Chris Lattner58407792009-01-09 04:53:57 +00004904 if (BitCastInst *BCI = dyn_cast<BitCastInst>(PtrOp)) {
Dan Gohmance9fe9f2009-07-21 23:21:54 +00004905 if (TD &&
4906 !isa<BitCastInst>(BCI->getOperand(0)) && GEP.hasAllConstantIndices()) {
Chris Lattner46cd5a12009-01-09 05:44:56 +00004907 // Determine how much the GEP moves the pointer. We are guaranteed to get
4908 // a constant back from EmitGEPOffset.
Chris Lattner02446fc2010-01-04 07:37:31 +00004909 ConstantInt *OffsetV = cast<ConstantInt>(EmitGEPOffset(&GEP));
Chris Lattner46cd5a12009-01-09 05:44:56 +00004910 int64_t Offset = OffsetV->getSExtValue();
4911
4912 // If this GEP instruction doesn't move the pointer, just replace the GEP
4913 // with a bitcast of the real input to the dest type.
4914 if (Offset == 0) {
4915 // If the bitcast is of an allocation, and the allocation will be
4916 // converted to match the type of the cast, don't touch this.
Victor Hernandez7b929da2009-10-23 21:09:37 +00004917 if (isa<AllocaInst>(BCI->getOperand(0)) ||
Victor Hernandez83d63912009-09-18 22:35:49 +00004918 isMalloc(BCI->getOperand(0))) {
Chris Lattner46cd5a12009-01-09 05:44:56 +00004919 // See if the bitcast simplifies, if so, don't nuke this GEP yet.
4920 if (Instruction *I = visitBitCast(*BCI)) {
4921 if (I != BCI) {
4922 I->takeName(BCI);
4923 BCI->getParent()->getInstList().insert(BCI, I);
4924 ReplaceInstUsesWith(*BCI, I);
4925 }
4926 return &GEP;
Chris Lattner58407792009-01-09 04:53:57 +00004927 }
Chris Lattner58407792009-01-09 04:53:57 +00004928 }
Chris Lattner46cd5a12009-01-09 05:44:56 +00004929 return new BitCastInst(BCI->getOperand(0), GEP.getType());
Chris Lattner58407792009-01-09 04:53:57 +00004930 }
Chris Lattner46cd5a12009-01-09 05:44:56 +00004931
4932 // Otherwise, if the offset is non-zero, we need to find out if there is a
4933 // field at Offset in 'A's type. If so, we can pull the cast through the
4934 // GEP.
4935 SmallVector<Value*, 8> NewIndices;
4936 const Type *InTy =
4937 cast<PointerType>(BCI->getOperand(0)->getType())->getElementType();
Chris Lattner80f43d32010-01-04 07:53:58 +00004938 if (FindElementAtOffset(InTy, Offset, NewIndices)) {
Dan Gohmanf8dbee72009-09-07 23:54:19 +00004939 Value *NGEP = cast<GEPOperator>(&GEP)->isInBounds() ?
4940 Builder->CreateInBoundsGEP(BCI->getOperand(0), NewIndices.begin(),
4941 NewIndices.end()) :
4942 Builder->CreateGEP(BCI->getOperand(0), NewIndices.begin(),
4943 NewIndices.end());
Chris Lattnerf925cbd2009-08-30 18:50:58 +00004944
4945 if (NGEP->getType() == GEP.getType())
4946 return ReplaceInstUsesWith(GEP, NGEP);
Chris Lattner46cd5a12009-01-09 05:44:56 +00004947 NGEP->takeName(&GEP);
4948 return new BitCastInst(NGEP, GEP.getType());
4949 }
Chris Lattner58407792009-01-09 04:53:57 +00004950 }
4951 }
4952
Chris Lattner8a2a3112001-12-14 16:52:21 +00004953 return 0;
4954}
4955
Victor Hernandez66284e02009-10-24 04:23:03 +00004956Instruction *InstCombiner::visitFree(Instruction &FI) {
4957 Value *Op = FI.getOperand(1);
4958
4959 // free undef -> unreachable.
4960 if (isa<UndefValue>(Op)) {
4961 // Insert a new store to null because we cannot modify the CFG here.
Chris Lattner4de84762010-01-04 07:02:48 +00004962 new StoreInst(ConstantInt::getTrue(FI.getContext()),
4963 UndefValue::get(Type::getInt1PtrTy(FI.getContext())), &FI);
Victor Hernandez66284e02009-10-24 04:23:03 +00004964 return EraseInstFromFunction(FI);
4965 }
4966
4967 // If we have 'free null' delete the instruction. This can happen in stl code
4968 // when lots of inlining happens.
4969 if (isa<ConstantPointerNull>(Op))
4970 return EraseInstFromFunction(FI);
4971
Victor Hernandez046e78c2009-10-26 23:43:48 +00004972 // If we have a malloc call whose only use is a free call, delete both.
Dan Gohman7f712a12009-10-27 00:11:02 +00004973 if (isMalloc(Op)) {
Victor Hernandez66284e02009-10-24 04:23:03 +00004974 if (CallInst* CI = extractMallocCallFromBitCast(Op)) {
4975 if (Op->hasOneUse() && CI->hasOneUse()) {
4976 EraseInstFromFunction(FI);
4977 EraseInstFromFunction(*CI);
4978 return EraseInstFromFunction(*cast<Instruction>(Op));
4979 }
4980 } else {
4981 // Op is a call to malloc
4982 if (Op->hasOneUse()) {
4983 EraseInstFromFunction(FI);
4984 return EraseInstFromFunction(*cast<Instruction>(Op));
4985 }
4986 }
Dan Gohman7f712a12009-10-27 00:11:02 +00004987 }
Victor Hernandez66284e02009-10-24 04:23:03 +00004988
4989 return 0;
4990}
Chris Lattner67b1e1b2003-12-07 01:24:23 +00004991
Chris Lattner3284d1f2007-04-15 00:07:55 +00004992
Chris Lattner2f503e62005-01-31 05:36:43 +00004993
Chris Lattnerc4d10eb2003-06-04 04:46:00 +00004994Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
4995 // Change br (not X), label True, label False to: br X, label False, True
Reid Spencer4b828e62005-06-18 17:37:34 +00004996 Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004997 BasicBlock *TrueDest;
4998 BasicBlock *FalseDest;
Dan Gohman4ae51262009-08-12 16:23:25 +00004999 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
Chris Lattneracd1f0f2004-07-30 07:50:03 +00005000 !isa<Constant>(X)) {
5001 // Swap Destinations and condition...
5002 BI.setCondition(X);
5003 BI.setSuccessor(0, FalseDest);
5004 BI.setSuccessor(1, TrueDest);
5005 return &BI;
5006 }
5007
Reid Spencere4d87aa2006-12-23 06:05:41 +00005008 // Cannonicalize fcmp_one -> fcmp_oeq
5009 FCmpInst::Predicate FPred; Value *Y;
5010 if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)),
Chris Lattner7a1e9242009-08-30 06:13:40 +00005011 TrueDest, FalseDest)) &&
5012 BI.getCondition()->hasOneUse())
5013 if (FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
5014 FPred == FCmpInst::FCMP_OGE) {
5015 FCmpInst *Cond = cast<FCmpInst>(BI.getCondition());
5016 Cond->setPredicate(FCmpInst::getInversePredicate(FPred));
5017
5018 // Swap Destinations and condition.
Reid Spencere4d87aa2006-12-23 06:05:41 +00005019 BI.setSuccessor(0, FalseDest);
5020 BI.setSuccessor(1, TrueDest);
Chris Lattner7a1e9242009-08-30 06:13:40 +00005021 Worklist.Add(Cond);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005022 return &BI;
5023 }
5024
5025 // Cannonicalize icmp_ne -> icmp_eq
5026 ICmpInst::Predicate IPred;
5027 if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
Chris Lattner7a1e9242009-08-30 06:13:40 +00005028 TrueDest, FalseDest)) &&
5029 BI.getCondition()->hasOneUse())
5030 if (IPred == ICmpInst::ICMP_NE || IPred == ICmpInst::ICMP_ULE ||
5031 IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
5032 IPred == ICmpInst::ICMP_SGE) {
5033 ICmpInst *Cond = cast<ICmpInst>(BI.getCondition());
5034 Cond->setPredicate(ICmpInst::getInversePredicate(IPred));
5035 // Swap Destinations and condition.
Chris Lattner40f5d702003-06-04 05:10:11 +00005036 BI.setSuccessor(0, FalseDest);
5037 BI.setSuccessor(1, TrueDest);
Chris Lattner7a1e9242009-08-30 06:13:40 +00005038 Worklist.Add(Cond);
Chris Lattner40f5d702003-06-04 05:10:11 +00005039 return &BI;
5040 }
Misha Brukmanfd939082005-04-21 23:48:37 +00005041
Chris Lattnerc4d10eb2003-06-04 04:46:00 +00005042 return 0;
5043}
Chris Lattner0864acf2002-11-04 16:18:53 +00005044
Chris Lattner46238a62004-07-03 00:26:11 +00005045Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
5046 Value *Cond = SI.getCondition();
5047 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
5048 if (I->getOpcode() == Instruction::Add)
5049 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
5050 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
5051 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
Owen Andersond672ecb2009-07-03 00:17:18 +00005052 SI.setOperand(i,
Owen Andersonbaf3c402009-07-29 18:55:55 +00005053 ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
Chris Lattner46238a62004-07-03 00:26:11 +00005054 AddRHS));
5055 SI.setOperand(0, I->getOperand(0));
Chris Lattner7a1e9242009-08-30 06:13:40 +00005056 Worklist.Add(I);
Chris Lattner46238a62004-07-03 00:26:11 +00005057 return &SI;
5058 }
5059 }
5060 return 0;
5061}
5062
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +00005063Instruction *InstCombiner::visitExtractValueInst(ExtractValueInst &EV) {
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +00005064 Value *Agg = EV.getAggregateOperand();
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +00005065
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +00005066 if (!EV.hasIndices())
5067 return ReplaceInstUsesWith(EV, Agg);
5068
5069 if (Constant *C = dyn_cast<Constant>(Agg)) {
5070 if (isa<UndefValue>(C))
Owen Anderson9e9a0d52009-07-30 23:03:37 +00005071 return ReplaceInstUsesWith(EV, UndefValue::get(EV.getType()));
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +00005072
5073 if (isa<ConstantAggregateZero>(C))
Owen Andersona7235ea2009-07-31 20:28:14 +00005074 return ReplaceInstUsesWith(EV, Constant::getNullValue(EV.getType()));
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +00005075
5076 if (isa<ConstantArray>(C) || isa<ConstantStruct>(C)) {
5077 // Extract the element indexed by the first index out of the constant
5078 Value *V = C->getOperand(*EV.idx_begin());
5079 if (EV.getNumIndices() > 1)
5080 // Extract the remaining indices out of the constant indexed by the
5081 // first index
5082 return ExtractValueInst::Create(V, EV.idx_begin() + 1, EV.idx_end());
5083 else
5084 return ReplaceInstUsesWith(EV, V);
5085 }
5086 return 0; // Can't handle other constants
5087 }
5088 if (InsertValueInst *IV = dyn_cast<InsertValueInst>(Agg)) {
5089 // We're extracting from an insertvalue instruction, compare the indices
5090 const unsigned *exti, *exte, *insi, *inse;
5091 for (exti = EV.idx_begin(), insi = IV->idx_begin(),
5092 exte = EV.idx_end(), inse = IV->idx_end();
5093 exti != exte && insi != inse;
5094 ++exti, ++insi) {
5095 if (*insi != *exti)
5096 // The insert and extract both reference distinctly different elements.
5097 // This means the extract is not influenced by the insert, and we can
5098 // replace the aggregate operand of the extract with the aggregate
5099 // operand of the insert. i.e., replace
5100 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
5101 // %E = extractvalue { i32, { i32 } } %I, 0
5102 // with
5103 // %E = extractvalue { i32, { i32 } } %A, 0
5104 return ExtractValueInst::Create(IV->getAggregateOperand(),
5105 EV.idx_begin(), EV.idx_end());
5106 }
5107 if (exti == exte && insi == inse)
5108 // Both iterators are at the end: Index lists are identical. Replace
5109 // %B = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
5110 // %C = extractvalue { i32, { i32 } } %B, 1, 0
5111 // with "i32 42"
5112 return ReplaceInstUsesWith(EV, IV->getInsertedValueOperand());
5113 if (exti == exte) {
5114 // The extract list is a prefix of the insert list. i.e. replace
5115 // %I = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
5116 // %E = extractvalue { i32, { i32 } } %I, 1
5117 // with
5118 // %X = extractvalue { i32, { i32 } } %A, 1
5119 // %E = insertvalue { i32 } %X, i32 42, 0
5120 // by switching the order of the insert and extract (though the
5121 // insertvalue should be left in, since it may have other uses).
Chris Lattnerf925cbd2009-08-30 18:50:58 +00005122 Value *NewEV = Builder->CreateExtractValue(IV->getAggregateOperand(),
5123 EV.idx_begin(), EV.idx_end());
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +00005124 return InsertValueInst::Create(NewEV, IV->getInsertedValueOperand(),
5125 insi, inse);
5126 }
5127 if (insi == inse)
5128 // The insert list is a prefix of the extract list
5129 // We can simply remove the common indices from the extract and make it
5130 // operate on the inserted value instead of the insertvalue result.
5131 // i.e., replace
5132 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
5133 // %E = extractvalue { i32, { i32 } } %I, 1, 0
5134 // with
5135 // %E extractvalue { i32 } { i32 42 }, 0
5136 return ExtractValueInst::Create(IV->getInsertedValueOperand(),
5137 exti, exte);
5138 }
Chris Lattner7e606e22009-11-09 07:07:56 +00005139 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Agg)) {
5140 // We're extracting from an intrinsic, see if we're the only user, which
5141 // allows us to simplify multiple result intrinsics to simpler things that
5142 // just get one value..
5143 if (II->hasOneUse()) {
5144 // Check if we're grabbing the overflow bit or the result of a 'with
5145 // overflow' intrinsic. If it's the latter we can remove the intrinsic
5146 // and replace it with a traditional binary instruction.
5147 switch (II->getIntrinsicID()) {
5148 case Intrinsic::uadd_with_overflow:
5149 case Intrinsic::sadd_with_overflow:
5150 if (*EV.idx_begin() == 0) { // Normal result.
5151 Value *LHS = II->getOperand(1), *RHS = II->getOperand(2);
5152 II->replaceAllUsesWith(UndefValue::get(II->getType()));
5153 EraseInstFromFunction(*II);
5154 return BinaryOperator::CreateAdd(LHS, RHS);
5155 }
5156 break;
5157 case Intrinsic::usub_with_overflow:
5158 case Intrinsic::ssub_with_overflow:
5159 if (*EV.idx_begin() == 0) { // Normal result.
5160 Value *LHS = II->getOperand(1), *RHS = II->getOperand(2);
5161 II->replaceAllUsesWith(UndefValue::get(II->getType()));
5162 EraseInstFromFunction(*II);
5163 return BinaryOperator::CreateSub(LHS, RHS);
5164 }
5165 break;
5166 case Intrinsic::umul_with_overflow:
5167 case Intrinsic::smul_with_overflow:
5168 if (*EV.idx_begin() == 0) { // Normal result.
5169 Value *LHS = II->getOperand(1), *RHS = II->getOperand(2);
5170 II->replaceAllUsesWith(UndefValue::get(II->getType()));
5171 EraseInstFromFunction(*II);
5172 return BinaryOperator::CreateMul(LHS, RHS);
5173 }
5174 break;
5175 default:
5176 break;
5177 }
5178 }
5179 }
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +00005180 // Can't simplify extracts from other values. Note that nested extracts are
5181 // already simplified implicitely by the above (extract ( extract (insert) )
5182 // will be translated into extract ( insert ( extract ) ) first and then just
5183 // the value inserted, if appropriate).
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +00005184 return 0;
5185}
5186
Chris Lattnera844fc4c2006-04-10 22:45:52 +00005187
Robert Bocchino1d7456d2006-01-13 22:48:06 +00005188
Chris Lattnerea1c4542004-12-08 23:43:58 +00005189
5190/// TryToSinkInstruction - Try to move the specified instruction from its
5191/// current block into the beginning of DestBlock, which can only happen if it's
5192/// safe to move the instruction past all of the instructions between it and the
5193/// end of its block.
5194static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
5195 assert(I->hasOneUse() && "Invariants didn't hold!");
5196
Chris Lattner108e9022005-10-27 17:13:11 +00005197 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
Duncan Sands7af1c782009-05-06 06:49:50 +00005198 if (isa<PHINode>(I) || I->mayHaveSideEffects() || isa<TerminatorInst>(I))
Chris Lattnerbfc538c2008-05-09 15:07:33 +00005199 return false;
Misha Brukmanfd939082005-04-21 23:48:37 +00005200
Chris Lattnerea1c4542004-12-08 23:43:58 +00005201 // Do not sink alloca instructions out of the entry block.
Dan Gohmanecb7a772007-03-22 16:38:57 +00005202 if (isa<AllocaInst>(I) && I->getParent() ==
5203 &DestBlock->getParent()->getEntryBlock())
Chris Lattnerea1c4542004-12-08 23:43:58 +00005204 return false;
5205
Chris Lattner96a52a62004-12-09 07:14:34 +00005206 // We can only sink load instructions if there is nothing between the load and
5207 // the end of block that could change the value.
Chris Lattner2539e332008-05-08 17:37:37 +00005208 if (I->mayReadFromMemory()) {
5209 for (BasicBlock::iterator Scan = I, E = I->getParent()->end();
Chris Lattner96a52a62004-12-09 07:14:34 +00005210 Scan != E; ++Scan)
5211 if (Scan->mayWriteToMemory())
5212 return false;
Chris Lattner96a52a62004-12-09 07:14:34 +00005213 }
Chris Lattnerea1c4542004-12-08 23:43:58 +00005214
Dan Gohman02dea8b2008-05-23 21:05:58 +00005215 BasicBlock::iterator InsertPos = DestBlock->getFirstNonPHI();
Chris Lattnerea1c4542004-12-08 23:43:58 +00005216
Chris Lattner4bc5f802005-08-08 19:11:57 +00005217 I->moveBefore(InsertPos);
Chris Lattnerea1c4542004-12-08 23:43:58 +00005218 ++NumSunkInst;
5219 return true;
5220}
5221
Chris Lattnerf4f5a772006-05-10 19:00:36 +00005222
5223/// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
5224/// all reachable code to the worklist.
5225///
5226/// This has a couple of tricks to make the code faster and more powerful. In
5227/// particular, we constant fold and DCE instructions as we go, to avoid adding
5228/// them to the worklist (this significantly speeds up instcombine on code where
5229/// many instructions are dead or constant). Additionally, if we find a branch
5230/// whose condition is a known constant, we only visit the reachable successors.
5231///
Chris Lattner2ee743b2009-10-15 04:59:28 +00005232static bool AddReachableCodeToWorklist(BasicBlock *BB,
Chris Lattner1f87a582007-02-15 19:41:52 +00005233 SmallPtrSet<BasicBlock*, 64> &Visited,
Chris Lattnerdbab3862007-03-02 21:28:56 +00005234 InstCombiner &IC,
Chris Lattner8c8c66a2006-05-11 17:11:52 +00005235 const TargetData *TD) {
Chris Lattner2ee743b2009-10-15 04:59:28 +00005236 bool MadeIRChange = false;
Chris Lattner2806dff2008-08-15 04:03:01 +00005237 SmallVector<BasicBlock*, 256> Worklist;
Chris Lattner2c7718a2007-03-23 19:17:18 +00005238 Worklist.push_back(BB);
Chris Lattner67f7d542009-10-12 03:58:40 +00005239
5240 std::vector<Instruction*> InstrsForInstCombineWorklist;
5241 InstrsForInstCombineWorklist.reserve(128);
Chris Lattnerf4f5a772006-05-10 19:00:36 +00005242
Chris Lattner2ee743b2009-10-15 04:59:28 +00005243 SmallPtrSet<ConstantExpr*, 64> FoldedConstants;
5244
Chris Lattner2c7718a2007-03-23 19:17:18 +00005245 while (!Worklist.empty()) {
5246 BB = Worklist.back();
5247 Worklist.pop_back();
5248
5249 // We have now visited this block! If we've already been here, ignore it.
5250 if (!Visited.insert(BB)) continue;
Devang Patel7fe1dec2008-11-19 18:56:50 +00005251
Chris Lattner2c7718a2007-03-23 19:17:18 +00005252 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
5253 Instruction *Inst = BBI++;
Chris Lattnerf4f5a772006-05-10 19:00:36 +00005254
Chris Lattner2c7718a2007-03-23 19:17:18 +00005255 // DCE instruction if trivially dead.
5256 if (isInstructionTriviallyDead(Inst)) {
5257 ++NumDeadInst;
Chris Lattnerbdff5482009-08-23 04:37:46 +00005258 DEBUG(errs() << "IC: DCE: " << *Inst << '\n');
Chris Lattner2c7718a2007-03-23 19:17:18 +00005259 Inst->eraseFromParent();
5260 continue;
5261 }
5262
5263 // ConstantProp instruction if trivially constant.
Chris Lattnere2cc1ad2009-10-15 04:13:44 +00005264 if (!Inst->use_empty() && isa<Constant>(Inst->getOperand(0)))
Chris Lattner7b550cc2009-11-06 04:27:31 +00005265 if (Constant *C = ConstantFoldInstruction(Inst, TD)) {
Chris Lattnere2cc1ad2009-10-15 04:13:44 +00005266 DEBUG(errs() << "IC: ConstFold to: " << *C << " from: "
5267 << *Inst << '\n');
5268 Inst->replaceAllUsesWith(C);
5269 ++NumConstProp;
5270 Inst->eraseFromParent();
5271 continue;
5272 }
Chris Lattner2ee743b2009-10-15 04:59:28 +00005273
5274
5275
5276 if (TD) {
5277 // See if we can constant fold its operands.
5278 for (User::op_iterator i = Inst->op_begin(), e = Inst->op_end();
5279 i != e; ++i) {
5280 ConstantExpr *CE = dyn_cast<ConstantExpr>(i);
5281 if (CE == 0) continue;
5282
5283 // If we already folded this constant, don't try again.
5284 if (!FoldedConstants.insert(CE))
5285 continue;
5286
Chris Lattner7b550cc2009-11-06 04:27:31 +00005287 Constant *NewC = ConstantFoldConstantExpression(CE, TD);
Chris Lattner2ee743b2009-10-15 04:59:28 +00005288 if (NewC && NewC != CE) {
5289 *i = NewC;
5290 MadeIRChange = true;
5291 }
5292 }
5293 }
5294
Devang Patel7fe1dec2008-11-19 18:56:50 +00005295
Chris Lattner67f7d542009-10-12 03:58:40 +00005296 InstrsForInstCombineWorklist.push_back(Inst);
Chris Lattnerf4f5a772006-05-10 19:00:36 +00005297 }
Chris Lattner2c7718a2007-03-23 19:17:18 +00005298
5299 // Recursively visit successors. If this is a branch or switch on a
5300 // constant, only visit the reachable successor.
5301 TerminatorInst *TI = BB->getTerminator();
5302 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
5303 if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
5304 bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
Nick Lewycky91436992008-03-09 08:50:23 +00005305 BasicBlock *ReachableBB = BI->getSuccessor(!CondVal);
Nick Lewycky280a6e62008-04-25 16:53:59 +00005306 Worklist.push_back(ReachableBB);
Chris Lattner2c7718a2007-03-23 19:17:18 +00005307 continue;
5308 }
5309 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
5310 if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
5311 // See if this is an explicit destination.
5312 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
5313 if (SI->getCaseValue(i) == Cond) {
Nick Lewycky91436992008-03-09 08:50:23 +00005314 BasicBlock *ReachableBB = SI->getSuccessor(i);
Nick Lewycky280a6e62008-04-25 16:53:59 +00005315 Worklist.push_back(ReachableBB);
Chris Lattner2c7718a2007-03-23 19:17:18 +00005316 continue;
5317 }
5318
5319 // Otherwise it is the default destination.
5320 Worklist.push_back(SI->getSuccessor(0));
5321 continue;
5322 }
5323 }
5324
5325 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
5326 Worklist.push_back(TI->getSuccessor(i));
Chris Lattnerf4f5a772006-05-10 19:00:36 +00005327 }
Chris Lattner67f7d542009-10-12 03:58:40 +00005328
5329 // Once we've found all of the instructions to add to instcombine's worklist,
5330 // add them in reverse order. This way instcombine will visit from the top
5331 // of the function down. This jives well with the way that it adds all uses
5332 // of instructions to the worklist after doing a transformation, thus avoiding
5333 // some N^2 behavior in pathological cases.
5334 IC.Worklist.AddInitialGroup(&InstrsForInstCombineWorklist[0],
5335 InstrsForInstCombineWorklist.size());
Chris Lattner2ee743b2009-10-15 04:59:28 +00005336
5337 return MadeIRChange;
Chris Lattnerf4f5a772006-05-10 19:00:36 +00005338}
5339
Chris Lattnerec9c3582007-03-03 02:04:50 +00005340bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) {
Chris Lattnerb0b822c2009-08-31 06:57:37 +00005341 MadeIRChange = false;
Chris Lattnerec9c3582007-03-03 02:04:50 +00005342
Daniel Dunbarce63ffb2009-07-25 00:23:56 +00005343 DEBUG(errs() << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
5344 << F.getNameStr() << "\n");
Chris Lattner8a2a3112001-12-14 16:52:21 +00005345
Chris Lattnerb3d59702005-07-07 20:40:38 +00005346 {
Chris Lattnerf4f5a772006-05-10 19:00:36 +00005347 // Do a depth-first traversal of the function, populate the worklist with
5348 // the reachable instructions. Ignore blocks that are not reachable. Keep
5349 // track of which blocks we visit.
Chris Lattner1f87a582007-02-15 19:41:52 +00005350 SmallPtrSet<BasicBlock*, 64> Visited;
Chris Lattner2ee743b2009-10-15 04:59:28 +00005351 MadeIRChange |= AddReachableCodeToWorklist(F.begin(), Visited, *this, TD);
Jeff Cohen00b168892005-07-27 06:12:32 +00005352
Chris Lattnerb3d59702005-07-07 20:40:38 +00005353 // Do a quick scan over the function. If we find any blocks that are
5354 // unreachable, remove any instructions inside of them. This prevents
5355 // the instcombine code from having to deal with some bad special cases.
5356 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
5357 if (!Visited.count(BB)) {
5358 Instruction *Term = BB->getTerminator();
5359 while (Term != BB->begin()) { // Remove instrs bottom-up
5360 BasicBlock::iterator I = Term; --I;
Chris Lattner6ffe5512004-04-27 15:13:33 +00005361
Chris Lattnerbdff5482009-08-23 04:37:46 +00005362 DEBUG(errs() << "IC: DCE: " << *I << '\n');
Dale Johannesenff278b12009-03-10 21:19:49 +00005363 // A debug intrinsic shouldn't force another iteration if we weren't
5364 // going to do one without it.
5365 if (!isa<DbgInfoIntrinsic>(I)) {
5366 ++NumDeadInst;
Chris Lattnerb0b822c2009-08-31 06:57:37 +00005367 MadeIRChange = true;
Dale Johannesenff278b12009-03-10 21:19:49 +00005368 }
Devang Patel228ebd02009-10-13 22:56:32 +00005369
Devang Patel228ebd02009-10-13 22:56:32 +00005370 // If I is not void type then replaceAllUsesWith undef.
5371 // This allows ValueHandlers and custom metadata to adjust itself.
Devang Patel9674d152009-10-14 17:29:00 +00005372 if (!I->getType()->isVoidTy())
Devang Patel228ebd02009-10-13 22:56:32 +00005373 I->replaceAllUsesWith(UndefValue::get(I->getType()));
Chris Lattnerb3d59702005-07-07 20:40:38 +00005374 I->eraseFromParent();
5375 }
5376 }
5377 }
Chris Lattner8a2a3112001-12-14 16:52:21 +00005378
Chris Lattner873ff012009-08-30 05:55:36 +00005379 while (!Worklist.isEmpty()) {
5380 Instruction *I = Worklist.RemoveOne();
Chris Lattnerdbab3862007-03-02 21:28:56 +00005381 if (I == 0) continue; // skip null values.
Chris Lattner8a2a3112001-12-14 16:52:21 +00005382
Chris Lattner8c8c66a2006-05-11 17:11:52 +00005383 // Check to see if we can DCE the instruction.
Chris Lattner62b14df2002-09-02 04:59:56 +00005384 if (isInstructionTriviallyDead(I)) {
Chris Lattnerbdff5482009-08-23 04:37:46 +00005385 DEBUG(errs() << "IC: DCE: " << *I << '\n');
Chris Lattner7a1e9242009-08-30 06:13:40 +00005386 EraseInstFromFunction(*I);
5387 ++NumDeadInst;
Chris Lattnerb0b822c2009-08-31 06:57:37 +00005388 MadeIRChange = true;
Chris Lattner4bb7c022003-10-06 17:11:01 +00005389 continue;
5390 }
Chris Lattner62b14df2002-09-02 04:59:56 +00005391
Chris Lattner8c8c66a2006-05-11 17:11:52 +00005392 // Instruction isn't dead, see if we can constant propagate it.
Chris Lattnere2cc1ad2009-10-15 04:13:44 +00005393 if (!I->use_empty() && isa<Constant>(I->getOperand(0)))
Chris Lattner7b550cc2009-11-06 04:27:31 +00005394 if (Constant *C = ConstantFoldInstruction(I, TD)) {
Chris Lattnere2cc1ad2009-10-15 04:13:44 +00005395 DEBUG(errs() << "IC: ConstFold to: " << *C << " from: " << *I << '\n');
Chris Lattnerad5fec12005-01-28 19:32:01 +00005396
Chris Lattnere2cc1ad2009-10-15 04:13:44 +00005397 // Add operands to the worklist.
5398 ReplaceInstUsesWith(*I, C);
5399 ++NumConstProp;
5400 EraseInstFromFunction(*I);
5401 MadeIRChange = true;
5402 continue;
5403 }
Chris Lattner4bb7c022003-10-06 17:11:01 +00005404
Chris Lattnerea1c4542004-12-08 23:43:58 +00005405 // See if we can trivially sink this instruction to a successor basic block.
Dan Gohmanfc74abf2008-07-23 00:34:11 +00005406 if (I->hasOneUse()) {
Chris Lattnerea1c4542004-12-08 23:43:58 +00005407 BasicBlock *BB = I->getParent();
Chris Lattner8db2cd12009-10-14 15:21:58 +00005408 Instruction *UserInst = cast<Instruction>(I->use_back());
5409 BasicBlock *UserParent;
5410
5411 // Get the block the use occurs in.
5412 if (PHINode *PN = dyn_cast<PHINode>(UserInst))
5413 UserParent = PN->getIncomingBlock(I->use_begin().getUse());
5414 else
5415 UserParent = UserInst->getParent();
5416
Chris Lattnerea1c4542004-12-08 23:43:58 +00005417 if (UserParent != BB) {
5418 bool UserIsSuccessor = false;
5419 // See if the user is one of our successors.
5420 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
5421 if (*SI == UserParent) {
5422 UserIsSuccessor = true;
5423 break;
5424 }
5425
5426 // If the user is one of our immediate successors, and if that successor
5427 // only has us as a predecessors (we'd have to split the critical edge
5428 // otherwise), we can keep going.
Chris Lattner8db2cd12009-10-14 15:21:58 +00005429 if (UserIsSuccessor && UserParent->getSinglePredecessor())
Chris Lattnerea1c4542004-12-08 23:43:58 +00005430 // Okay, the CFG is simple enough, try to sink this instruction.
Chris Lattnerb0b822c2009-08-31 06:57:37 +00005431 MadeIRChange |= TryToSinkInstruction(I, UserParent);
Chris Lattnerea1c4542004-12-08 23:43:58 +00005432 }
5433 }
5434
Chris Lattner74381062009-08-30 07:44:24 +00005435 // Now that we have an instruction, try combining it to simplify it.
5436 Builder->SetInsertPoint(I->getParent(), I);
5437
Reid Spencera9b81012007-03-26 17:44:01 +00005438#ifndef NDEBUG
5439 std::string OrigI;
5440#endif
Chris Lattnerbdff5482009-08-23 04:37:46 +00005441 DEBUG(raw_string_ostream SS(OrigI); I->print(SS); OrigI = SS.str(););
Jeffrey Yasskin43069632009-10-08 00:12:24 +00005442 DEBUG(errs() << "IC: Visiting: " << OrigI << '\n');
5443
Chris Lattner90ac28c2002-08-02 19:29:35 +00005444 if (Instruction *Result = visit(*I)) {
Chris Lattner3dec1f22002-05-10 15:38:35 +00005445 ++NumCombined;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00005446 // Should we replace the old instruction with a new one?
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +00005447 if (Result != I) {
Chris Lattnerbdff5482009-08-23 04:37:46 +00005448 DEBUG(errs() << "IC: Old = " << *I << '\n'
5449 << " New = " << *Result << '\n');
Chris Lattner0cea42a2004-03-13 23:54:27 +00005450
Chris Lattnerf523d062004-06-09 05:08:07 +00005451 // Everything uses the new instruction now.
5452 I->replaceAllUsesWith(Result);
5453
5454 // Push the new instruction and any users onto the worklist.
Chris Lattner7a1e9242009-08-30 06:13:40 +00005455 Worklist.Add(Result);
Chris Lattnere5ecdb52009-08-30 06:22:51 +00005456 Worklist.AddUsersToWorkList(*Result);
Chris Lattner4bb7c022003-10-06 17:11:01 +00005457
Chris Lattner6934a042007-02-11 01:23:03 +00005458 // Move the name to the new instruction first.
5459 Result->takeName(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +00005460
5461 // Insert the new instruction into the basic block...
5462 BasicBlock *InstParent = I->getParent();
Chris Lattnerbac32862004-11-14 19:13:23 +00005463 BasicBlock::iterator InsertPos = I;
5464
5465 if (!isa<PHINode>(Result)) // If combining a PHI, don't insert
5466 while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
5467 ++InsertPos;
5468
5469 InstParent->getInstList().insert(InsertPos, Result);
Chris Lattner4bb7c022003-10-06 17:11:01 +00005470
Chris Lattner7a1e9242009-08-30 06:13:40 +00005471 EraseInstFromFunction(*I);
Chris Lattner7e708292002-06-25 16:13:24 +00005472 } else {
Evan Chengc7baf682007-03-27 16:44:48 +00005473#ifndef NDEBUG
Chris Lattnerbdff5482009-08-23 04:37:46 +00005474 DEBUG(errs() << "IC: Mod = " << OrigI << '\n'
5475 << " New = " << *I << '\n');
Evan Chengc7baf682007-03-27 16:44:48 +00005476#endif
Chris Lattner0cea42a2004-03-13 23:54:27 +00005477
Chris Lattner90ac28c2002-08-02 19:29:35 +00005478 // If the instruction was modified, it's possible that it is now dead.
5479 // if so, remove it.
Chris Lattner00d51312004-05-01 23:27:23 +00005480 if (isInstructionTriviallyDead(I)) {
Chris Lattner7a1e9242009-08-30 06:13:40 +00005481 EraseInstFromFunction(*I);
Chris Lattnerf523d062004-06-09 05:08:07 +00005482 } else {
Chris Lattner7a1e9242009-08-30 06:13:40 +00005483 Worklist.Add(I);
Chris Lattnere5ecdb52009-08-30 06:22:51 +00005484 Worklist.AddUsersToWorkList(*I);
Chris Lattner90ac28c2002-08-02 19:29:35 +00005485 }
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +00005486 }
Chris Lattnerb0b822c2009-08-31 06:57:37 +00005487 MadeIRChange = true;
Chris Lattner8a2a3112001-12-14 16:52:21 +00005488 }
5489 }
5490
Chris Lattner873ff012009-08-30 05:55:36 +00005491 Worklist.Zap();
Chris Lattnerb0b822c2009-08-31 06:57:37 +00005492 return MadeIRChange;
Chris Lattnerbd0ef772002-02-26 21:46:54 +00005493}
5494
Chris Lattnerec9c3582007-03-03 02:04:50 +00005495
5496bool InstCombiner::runOnFunction(Function &F) {
Chris Lattnerf964f322007-03-04 04:27:24 +00005497 MustPreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
Chris Lattnere2cc1ad2009-10-15 04:13:44 +00005498 TD = getAnalysisIfAvailable<TargetData>();
5499
Chris Lattner74381062009-08-30 07:44:24 +00005500
5501 /// Builder - This is an IRBuilder that automatically inserts new
5502 /// instructions into the worklist when they are created.
Chris Lattnere2cc1ad2009-10-15 04:13:44 +00005503 IRBuilder<true, TargetFolder, InstCombineIRInserter>
Chris Lattnerf55eeb92009-11-06 05:59:53 +00005504 TheBuilder(F.getContext(), TargetFolder(TD),
Chris Lattner74381062009-08-30 07:44:24 +00005505 InstCombineIRInserter(Worklist));
5506 Builder = &TheBuilder;
5507
Chris Lattnerec9c3582007-03-03 02:04:50 +00005508 bool EverMadeChange = false;
5509
5510 // Iterate while there is work to do.
5511 unsigned Iteration = 0;
Bill Wendlinga6c31122008-05-14 22:45:20 +00005512 while (DoOneIteration(F, Iteration++))
Chris Lattnerec9c3582007-03-03 02:04:50 +00005513 EverMadeChange = true;
Chris Lattner74381062009-08-30 07:44:24 +00005514
5515 Builder = 0;
Chris Lattnerec9c3582007-03-03 02:04:50 +00005516 return EverMadeChange;
5517}
5518
Brian Gaeke96d4bf72004-07-27 17:43:21 +00005519FunctionPass *llvm::createInstructionCombiningPass() {
Chris Lattnerdd841ae2002-04-18 17:39:14 +00005520 return new InstCombiner();
Chris Lattnerbd0ef772002-02-26 21:46:54 +00005521}