blob: ca311dd994aa501544b5201963f584c786a520c4 [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 Lattner6e7ba452005-01-01 16:22:27 +0000291static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
Chris Lattner2eefe512004-04-09 19:05:30 +0000292 InstCombiner *IC) {
Chris Lattner08142f22009-08-30 19:47:22 +0000293 if (CastInst *CI = dyn_cast<CastInst>(&I))
Chris Lattner2345d1d2009-08-30 20:01:10 +0000294 return IC->Builder->CreateCast(CI->getOpcode(), SO, I.getType());
Chris Lattner6e7ba452005-01-01 16:22:27 +0000295
Chris Lattner2eefe512004-04-09 19:05:30 +0000296 // Figure out if the constant is the left or the right argument.
Chris Lattner6e7ba452005-01-01 16:22:27 +0000297 bool ConstIsRHS = isa<Constant>(I.getOperand(1));
298 Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
Chris Lattner564a7272003-08-13 19:01:45 +0000299
Chris Lattner2eefe512004-04-09 19:05:30 +0000300 if (Constant *SOC = dyn_cast<Constant>(SO)) {
301 if (ConstIsRHS)
Owen Andersonbaf3c402009-07-29 18:55:55 +0000302 return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
303 return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
Chris Lattner2eefe512004-04-09 19:05:30 +0000304 }
305
306 Value *Op0 = SO, *Op1 = ConstOperand;
307 if (!ConstIsRHS)
308 std::swap(Op0, Op1);
Chris Lattner74381062009-08-30 07:44:24 +0000309
Chris Lattner6e7ba452005-01-01 16:22:27 +0000310 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
Chris Lattner74381062009-08-30 07:44:24 +0000311 return IC->Builder->CreateBinOp(BO->getOpcode(), Op0, Op1,
312 SO->getName()+".op");
313 if (ICmpInst *CI = dyn_cast<ICmpInst>(&I))
314 return IC->Builder->CreateICmp(CI->getPredicate(), Op0, Op1,
315 SO->getName()+".cmp");
316 if (FCmpInst *CI = dyn_cast<FCmpInst>(&I))
317 return IC->Builder->CreateICmp(CI->getPredicate(), Op0, Op1,
318 SO->getName()+".cmp");
319 llvm_unreachable("Unknown binary instruction type!");
Chris Lattner6e7ba452005-01-01 16:22:27 +0000320}
321
322// FoldOpIntoSelect - Given an instruction with a select as one operand and a
323// constant as the other operand, try to fold the binary operator into the
324// select arguments. This also works for Cast instructions, which obviously do
325// not have a second operand.
Chris Lattner80f43d32010-01-04 07:53:58 +0000326Instruction *InstCombiner::FoldOpIntoSelect(Instruction &Op, SelectInst *SI) {
Chris Lattner6e7ba452005-01-01 16:22:27 +0000327 // Don't modify shared select instructions
328 if (!SI->hasOneUse()) return 0;
329 Value *TV = SI->getOperand(1);
330 Value *FV = SI->getOperand(2);
331
332 if (isa<Constant>(TV) || isa<Constant>(FV)) {
Chris Lattner956db272005-04-21 05:43:13 +0000333 // Bool selects with constant operands can be folded to logical ops.
Chris Lattner4de84762010-01-04 07:02:48 +0000334 if (SI->getType() == Type::getInt1Ty(SI->getContext())) return 0;
Chris Lattner956db272005-04-21 05:43:13 +0000335
Chris Lattner80f43d32010-01-04 07:53:58 +0000336 Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, this);
337 Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, this);
Chris Lattner6e7ba452005-01-01 16:22:27 +0000338
Gabor Greif051a9502008-04-06 20:25:17 +0000339 return SelectInst::Create(SI->getCondition(), SelectTrueVal,
340 SelectFalseVal);
Chris Lattner6e7ba452005-01-01 16:22:27 +0000341 }
342 return 0;
Chris Lattner2eefe512004-04-09 19:05:30 +0000343}
344
Chris Lattner4e998b22004-09-29 05:07:12 +0000345
Chris Lattner5d1704d2009-09-27 19:57:57 +0000346/// FoldOpIntoPhi - Given a binary operator, cast instruction, or select which
347/// has a PHI node as operand #0, see if we can fold the instruction into the
348/// PHI (which is only possible if all operands to the PHI are constants).
Chris Lattner213cd612009-09-27 20:46:36 +0000349///
350/// If AllowAggressive is true, FoldOpIntoPhi will allow certain transforms
351/// that would normally be unprofitable because they strongly encourage jump
352/// threading.
353Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I,
354 bool AllowAggressive) {
355 AllowAggressive = false;
Chris Lattner4e998b22004-09-29 05:07:12 +0000356 PHINode *PN = cast<PHINode>(I.getOperand(0));
Chris Lattnerbac32862004-11-14 19:13:23 +0000357 unsigned NumPHIValues = PN->getNumIncomingValues();
Chris Lattner213cd612009-09-27 20:46:36 +0000358 if (NumPHIValues == 0 ||
359 // We normally only transform phis with a single use, unless we're trying
360 // hard to make jump threading happen.
361 (!PN->hasOneUse() && !AllowAggressive))
362 return 0;
363
364
Chris Lattner5d1704d2009-09-27 19:57:57 +0000365 // Check to see if all of the operands of the PHI are simple constants
366 // (constantint/constantfp/undef). If there is one non-constant value,
Chris Lattnerc6df8f42009-09-27 20:18:49 +0000367 // remember the BB it is in. If there is more than one or if *it* is a PHI,
368 // bail out. We don't do arbitrary constant expressions here because moving
369 // their computation can be expensive without a cost model.
Chris Lattner2a86f3b2006-09-09 22:02:56 +0000370 BasicBlock *NonConstBB = 0;
371 for (unsigned i = 0; i != NumPHIValues; ++i)
Chris Lattner5d1704d2009-09-27 19:57:57 +0000372 if (!isa<Constant>(PN->getIncomingValue(i)) ||
373 isa<ConstantExpr>(PN->getIncomingValue(i))) {
Chris Lattner2a86f3b2006-09-09 22:02:56 +0000374 if (NonConstBB) return 0; // More than one non-const value.
Chris Lattnerb3036682007-02-24 01:03:45 +0000375 if (isa<PHINode>(PN->getIncomingValue(i))) return 0; // Itself a phi.
Chris Lattner2a86f3b2006-09-09 22:02:56 +0000376 NonConstBB = PN->getIncomingBlock(i);
377
378 // If the incoming non-constant value is in I's block, we have an infinite
379 // loop.
380 if (NonConstBB == I.getParent())
381 return 0;
382 }
383
384 // If there is exactly one non-constant value, we can insert a copy of the
385 // operation in that block. However, if this is a critical edge, we would be
386 // inserting the computation one some other paths (e.g. inside a loop). Only
387 // do this if the pred block is unconditionally branching into the phi block.
Chris Lattner213cd612009-09-27 20:46:36 +0000388 if (NonConstBB != 0 && !AllowAggressive) {
Chris Lattner2a86f3b2006-09-09 22:02:56 +0000389 BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
390 if (!BI || !BI->isUnconditional()) return 0;
391 }
Chris Lattner4e998b22004-09-29 05:07:12 +0000392
393 // Okay, we can do the transformation: create the new PHI node.
Gabor Greif051a9502008-04-06 20:25:17 +0000394 PHINode *NewPN = PHINode::Create(I.getType(), "");
Chris Lattner55517062005-01-29 00:39:08 +0000395 NewPN->reserveOperandSpace(PN->getNumOperands()/2);
Chris Lattner857eb572009-10-21 23:41:58 +0000396 InsertNewInstBefore(NewPN, *PN);
397 NewPN->takeName(PN);
Chris Lattner4e998b22004-09-29 05:07:12 +0000398
399 // Next, add all of the operands to the PHI.
Chris Lattner5d1704d2009-09-27 19:57:57 +0000400 if (SelectInst *SI = dyn_cast<SelectInst>(&I)) {
401 // We only currently try to fold the condition of a select when it is a phi,
402 // not the true/false values.
Chris Lattnerc6df8f42009-09-27 20:18:49 +0000403 Value *TrueV = SI->getTrueValue();
404 Value *FalseV = SI->getFalseValue();
Chris Lattner3ddfb212009-09-28 06:49:44 +0000405 BasicBlock *PhiTransBB = PN->getParent();
Chris Lattner5d1704d2009-09-27 19:57:57 +0000406 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattnerc6df8f42009-09-27 20:18:49 +0000407 BasicBlock *ThisBB = PN->getIncomingBlock(i);
Chris Lattner3ddfb212009-09-28 06:49:44 +0000408 Value *TrueVInPred = TrueV->DoPHITranslation(PhiTransBB, ThisBB);
409 Value *FalseVInPred = FalseV->DoPHITranslation(PhiTransBB, ThisBB);
Chris Lattner5d1704d2009-09-27 19:57:57 +0000410 Value *InV = 0;
411 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Chris Lattnerc6df8f42009-09-27 20:18:49 +0000412 InV = InC->isNullValue() ? FalseVInPred : TrueVInPred;
Chris Lattner5d1704d2009-09-27 19:57:57 +0000413 } else {
414 assert(PN->getIncomingBlock(i) == NonConstBB);
Chris Lattnerc6df8f42009-09-27 20:18:49 +0000415 InV = SelectInst::Create(PN->getIncomingValue(i), TrueVInPred,
416 FalseVInPred,
Chris Lattner5d1704d2009-09-27 19:57:57 +0000417 "phitmp", NonConstBB->getTerminator());
Chris Lattner857eb572009-10-21 23:41:58 +0000418 Worklist.Add(cast<Instruction>(InV));
Chris Lattner5d1704d2009-09-27 19:57:57 +0000419 }
Chris Lattnerc6df8f42009-09-27 20:18:49 +0000420 NewPN->addIncoming(InV, ThisBB);
Chris Lattner5d1704d2009-09-27 19:57:57 +0000421 }
422 } else if (I.getNumOperands() == 2) {
Chris Lattner4e998b22004-09-29 05:07:12 +0000423 Constant *C = cast<Constant>(I.getOperand(1));
Chris Lattnerbac32862004-11-14 19:13:23 +0000424 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattnera9ff5eb2007-08-05 08:47:58 +0000425 Value *InV = 0;
Chris Lattner2a86f3b2006-09-09 22:02:56 +0000426 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Reid Spencere4d87aa2006-12-23 06:05:41 +0000427 if (CmpInst *CI = dyn_cast<CmpInst>(&I))
Owen Andersonbaf3c402009-07-29 18:55:55 +0000428 InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C);
Reid Spencere4d87aa2006-12-23 06:05:41 +0000429 else
Owen Andersonbaf3c402009-07-29 18:55:55 +0000430 InV = ConstantExpr::get(I.getOpcode(), InC, C);
Chris Lattner2a86f3b2006-09-09 22:02:56 +0000431 } else {
432 assert(PN->getIncomingBlock(i) == NonConstBB);
433 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000434 InV = BinaryOperator::Create(BO->getOpcode(),
Chris Lattner2a86f3b2006-09-09 22:02:56 +0000435 PN->getIncomingValue(i), C, "phitmp",
436 NonConstBB->getTerminator());
Reid Spencere4d87aa2006-12-23 06:05:41 +0000437 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
Dan Gohman1c8a23c2009-08-25 23:17:54 +0000438 InV = CmpInst::Create(CI->getOpcode(),
Reid Spencere4d87aa2006-12-23 06:05:41 +0000439 CI->getPredicate(),
440 PN->getIncomingValue(i), C, "phitmp",
441 NonConstBB->getTerminator());
Chris Lattner2a86f3b2006-09-09 22:02:56 +0000442 else
Torok Edwinc23197a2009-07-14 16:55:14 +0000443 llvm_unreachable("Unknown binop!");
Chris Lattner857eb572009-10-21 23:41:58 +0000444
445 Worklist.Add(cast<Instruction>(InV));
Chris Lattner2a86f3b2006-09-09 22:02:56 +0000446 }
447 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner4e998b22004-09-29 05:07:12 +0000448 }
Reid Spencer3da59db2006-11-27 01:05:10 +0000449 } else {
450 CastInst *CI = cast<CastInst>(&I);
451 const Type *RetTy = CI->getType();
Chris Lattnerbac32862004-11-14 19:13:23 +0000452 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattner2a86f3b2006-09-09 22:02:56 +0000453 Value *InV;
454 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Owen Andersonbaf3c402009-07-29 18:55:55 +0000455 InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
Chris Lattner2a86f3b2006-09-09 22:02:56 +0000456 } else {
457 assert(PN->getIncomingBlock(i) == NonConstBB);
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000458 InV = CastInst::Create(CI->getOpcode(), PN->getIncomingValue(i),
Reid Spencer3da59db2006-11-27 01:05:10 +0000459 I.getType(), "phitmp",
460 NonConstBB->getTerminator());
Chris Lattner857eb572009-10-21 23:41:58 +0000461 Worklist.Add(cast<Instruction>(InV));
Chris Lattner2a86f3b2006-09-09 22:02:56 +0000462 }
463 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner4e998b22004-09-29 05:07:12 +0000464 }
465 }
466 return ReplaceInstUsesWith(I, NewPN);
467}
468
Chris Lattner2454a2e2008-01-29 06:52:45 +0000469
Chris Lattner3d28b1b2008-05-20 05:46:13 +0000470/// WillNotOverflowSignedAdd - Return true if we can prove that:
471/// (sext (add LHS, RHS)) === (add (sext LHS), (sext RHS))
472/// This basically requires proving that the add in the original type would not
473/// overflow to change the sign bit or have a carry out.
474bool InstCombiner::WillNotOverflowSignedAdd(Value *LHS, Value *RHS) {
475 // There are different heuristics we can use for this. Here are some simple
476 // ones.
477
478 // Add has the property that adding any two 2's complement numbers can only
479 // have one carry bit which can change a sign. As such, if LHS and RHS each
Chris Lattner8aee8ef2009-11-27 17:42:22 +0000480 // have at least two sign bits, we know that the addition of the two values
481 // will sign extend fine.
Chris Lattner3d28b1b2008-05-20 05:46:13 +0000482 if (ComputeNumSignBits(LHS) > 1 && ComputeNumSignBits(RHS) > 1)
483 return true;
484
485
486 // If one of the operands only has one non-zero bit, and if the other operand
487 // has a known-zero bit in a more significant place than it (not including the
488 // sign bit) the ripple may go up to and fill the zero, but won't change the
489 // sign. For example, (X & ~4) + 1.
490
491 // TODO: Implement.
492
493 return false;
494}
495
Chris Lattner2454a2e2008-01-29 06:52:45 +0000496
Chris Lattner7e708292002-06-25 16:13:24 +0000497Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +0000498 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +0000499 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
Chris Lattnerb35dde12002-05-06 16:49:18 +0000500
Chris Lattner8aee8ef2009-11-27 17:42:22 +0000501 if (Value *V = SimplifyAddInst(LHS, RHS, I.hasNoSignedWrap(),
502 I.hasNoUnsignedWrap(), TD))
503 return ReplaceInstUsesWith(I, V);
504
505
Chris Lattner66331a42004-04-10 22:01:55 +0000506 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
Chris Lattner66331a42004-04-10 22:01:55 +0000507 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
Chris Lattnerb4a2f052006-11-09 05:12:27 +0000508 // X + (signbit) --> X ^ signbit
Zhou Sheng3a507fd2007-04-01 17:13:37 +0000509 const APInt& Val = CI->getValue();
Zhou Sheng4351c642007-04-02 08:20:41 +0000510 uint32_t BitWidth = Val.getBitWidth();
Reid Spencer2ec619a2007-03-23 21:24:59 +0000511 if (Val == APInt::getSignBit(BitWidth))
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000512 return BinaryOperator::CreateXor(LHS, RHS);
Chris Lattnerb4a2f052006-11-09 05:12:27 +0000513
514 // See if SimplifyDemandedBits can simplify this. This handles stuff like
515 // (X & 254)+1 -> (X&254)|1
Dan Gohman6de29f82009-06-15 22:12:54 +0000516 if (SimplifyDemandedInstructionBits(I))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000517 return &I;
Dan Gohman1975d032008-10-30 20:40:10 +0000518
Eli Friedman709b33d2009-07-13 22:27:52 +0000519 // zext(bool) + C -> bool ? C + 1 : C
Dan Gohman1975d032008-10-30 20:40:10 +0000520 if (ZExtInst *ZI = dyn_cast<ZExtInst>(LHS))
Chris Lattner4de84762010-01-04 07:02:48 +0000521 if (ZI->getSrcTy() == Type::getInt1Ty(I.getContext()))
Dan Gohman186a6362009-08-12 16:04:34 +0000522 return SelectInst::Create(ZI->getOperand(0), AddOne(CI), CI);
Chris Lattner66331a42004-04-10 22:01:55 +0000523 }
Chris Lattner4e998b22004-09-29 05:07:12 +0000524
525 if (isa<PHINode>(LHS))
526 if (Instruction *NV = FoldOpIntoPhi(I))
527 return NV;
Chris Lattner5931c542005-09-24 23:43:33 +0000528
Chris Lattner4f637d42006-01-06 17:59:59 +0000529 ConstantInt *XorRHS = 0;
530 Value *XorLHS = 0;
Chris Lattnerc5eff442007-01-30 22:32:46 +0000531 if (isa<ConstantInt>(RHSC) &&
Dan Gohman4ae51262009-08-12 16:23:25 +0000532 match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
Dan Gohman6de29f82009-06-15 22:12:54 +0000533 uint32_t TySizeBits = I.getType()->getScalarSizeInBits();
Zhou Sheng3a507fd2007-04-01 17:13:37 +0000534 const APInt& RHSVal = cast<ConstantInt>(RHSC)->getValue();
Chris Lattner5931c542005-09-24 23:43:33 +0000535
Zhou Sheng4351c642007-04-02 08:20:41 +0000536 uint32_t Size = TySizeBits / 2;
Reid Spencer2ec619a2007-03-23 21:24:59 +0000537 APInt C0080Val(APInt(TySizeBits, 1ULL).shl(Size - 1));
538 APInt CFF80Val(-C0080Val);
Chris Lattner5931c542005-09-24 23:43:33 +0000539 do {
540 if (TySizeBits > Size) {
Chris Lattner5931c542005-09-24 23:43:33 +0000541 // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
542 // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
Reid Spencer2ec619a2007-03-23 21:24:59 +0000543 if ((RHSVal == CFF80Val && XorRHS->getValue() == C0080Val) ||
544 (RHSVal == C0080Val && XorRHS->getValue() == CFF80Val)) {
Chris Lattner5931c542005-09-24 23:43:33 +0000545 // This is a sign extend if the top bits are known zero.
Zhou Sheng290bec52007-03-29 08:15:12 +0000546 if (!MaskedValueIsZero(XorLHS,
547 APInt::getHighBitsSet(TySizeBits, TySizeBits - Size)))
Chris Lattner5931c542005-09-24 23:43:33 +0000548 Size = 0; // Not a sign ext, but can't be any others either.
Reid Spencer2ec619a2007-03-23 21:24:59 +0000549 break;
Chris Lattner5931c542005-09-24 23:43:33 +0000550 }
551 }
552 Size >>= 1;
Reid Spencer2ec619a2007-03-23 21:24:59 +0000553 C0080Val = APIntOps::lshr(C0080Val, Size);
554 CFF80Val = APIntOps::ashr(CFF80Val, Size);
555 } while (Size >= 1);
Chris Lattner5931c542005-09-24 23:43:33 +0000556
Reid Spencer35c38852007-03-28 01:36:16 +0000557 // FIXME: This shouldn't be necessary. When the backends can handle types
Chris Lattner0c7a9a02008-05-19 20:25:04 +0000558 // with funny bit widths then this switch statement should be removed. It
559 // is just here to get the size of the "middle" type back up to something
560 // that the back ends can handle.
Reid Spencer35c38852007-03-28 01:36:16 +0000561 const Type *MiddleType = 0;
562 switch (Size) {
563 default: break;
Chris Lattner4de84762010-01-04 07:02:48 +0000564 case 32:
565 case 16:
566 case 8: MiddleType = IntegerType::get(I.getContext(), Size); break;
Reid Spencer35c38852007-03-28 01:36:16 +0000567 }
568 if (MiddleType) {
Chris Lattner74381062009-08-30 07:44:24 +0000569 Value *NewTrunc = Builder->CreateTrunc(XorLHS, MiddleType, "sext");
Reid Spencer35c38852007-03-28 01:36:16 +0000570 return new SExtInst(NewTrunc, I.getType(), I.getName());
Chris Lattner5931c542005-09-24 23:43:33 +0000571 }
572 }
Chris Lattner66331a42004-04-10 22:01:55 +0000573 }
Chris Lattnerb35dde12002-05-06 16:49:18 +0000574
Chris Lattner4de84762010-01-04 07:02:48 +0000575 if (I.getType() == Type::getInt1Ty(I.getContext()))
Nick Lewycky9419ddb2008-05-31 17:59:52 +0000576 return BinaryOperator::CreateXor(LHS, RHS);
577
Nick Lewycky9419ddb2008-05-31 17:59:52 +0000578 if (I.getType()->isInteger()) {
Chris Lattner32c0cf52010-01-05 06:29:13 +0000579 // X + X --> X << 1
580 if (LHS == RHS)
581 return BinaryOperator::CreateShl(LHS, ConstantInt::get(I.getType(), 1));
Chris Lattner7edc8c22005-04-07 17:14:51 +0000582
583 if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
584 if (RHSI->getOpcode() == Instruction::Sub)
585 if (LHS == RHSI->getOperand(1)) // A + (B - A) --> B
586 return ReplaceInstUsesWith(I, RHSI->getOperand(0));
587 }
588 if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
589 if (LHSI->getOpcode() == Instruction::Sub)
590 if (RHS == LHSI->getOperand(1)) // (B - A) + A --> B
591 return ReplaceInstUsesWith(I, LHSI->getOperand(0));
592 }
Robert Bocchino71698282004-07-27 21:02:21 +0000593 }
Chris Lattnere92d2f42003-08-13 04:18:28 +0000594
Chris Lattner5c4afb92002-05-08 22:46:53 +0000595 // -A + B --> B - A
Chris Lattnerdd12f962008-02-17 21:03:36 +0000596 // -A + -B --> -(A + B)
Dan Gohman186a6362009-08-12 16:04:34 +0000597 if (Value *LHSV = dyn_castNegVal(LHS)) {
Chris Lattnere10c0b92008-02-18 17:50:16 +0000598 if (LHS->getType()->isIntOrIntVector()) {
Dan Gohman186a6362009-08-12 16:04:34 +0000599 if (Value *RHSV = dyn_castNegVal(RHS)) {
Chris Lattner74381062009-08-30 07:44:24 +0000600 Value *NewAdd = Builder->CreateAdd(LHSV, RHSV, "sum");
Dan Gohman4ae51262009-08-12 16:23:25 +0000601 return BinaryOperator::CreateNeg(NewAdd);
Chris Lattnere10c0b92008-02-18 17:50:16 +0000602 }
Chris Lattnerdd12f962008-02-17 21:03:36 +0000603 }
604
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000605 return BinaryOperator::CreateSub(RHS, LHSV);
Chris Lattnerdd12f962008-02-17 21:03:36 +0000606 }
Chris Lattnerb35dde12002-05-06 16:49:18 +0000607
608 // A + -B --> A - B
Chris Lattner8d969642003-03-10 23:06:50 +0000609 if (!isa<Constant>(RHS))
Dan Gohman186a6362009-08-12 16:04:34 +0000610 if (Value *V = dyn_castNegVal(RHS))
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000611 return BinaryOperator::CreateSub(LHS, V);
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000612
Misha Brukmanfd939082005-04-21 23:48:37 +0000613
Chris Lattner50af16a2004-11-13 19:50:12 +0000614 ConstantInt *C2;
Dan Gohman186a6362009-08-12 16:04:34 +0000615 if (Value *X = dyn_castFoldableMul(LHS, C2)) {
Chris Lattner50af16a2004-11-13 19:50:12 +0000616 if (X == RHS) // X*C + X --> X * (C+1)
Dan Gohman186a6362009-08-12 16:04:34 +0000617 return BinaryOperator::CreateMul(RHS, AddOne(C2));
Chris Lattner50af16a2004-11-13 19:50:12 +0000618
619 // X*C1 + X*C2 --> X * (C1+C2)
620 ConstantInt *C1;
Dan Gohman186a6362009-08-12 16:04:34 +0000621 if (X == dyn_castFoldableMul(RHS, C1))
Owen Andersonbaf3c402009-07-29 18:55:55 +0000622 return BinaryOperator::CreateMul(X, ConstantExpr::getAdd(C1, C2));
Chris Lattnerad3448c2003-02-18 19:57:07 +0000623 }
624
625 // X + X*C --> X * (C+1)
Dan Gohman186a6362009-08-12 16:04:34 +0000626 if (dyn_castFoldableMul(RHS, C2) == LHS)
627 return BinaryOperator::CreateMul(LHS, AddOne(C2));
Chris Lattner50af16a2004-11-13 19:50:12 +0000628
Chris Lattnere617c9e2007-01-05 02:17:46 +0000629 // X + ~X --> -1 since ~X = -X-1
Dan Gohman186a6362009-08-12 16:04:34 +0000630 if (dyn_castNotVal(LHS) == RHS ||
631 dyn_castNotVal(RHS) == LHS)
Owen Andersona7235ea2009-07-31 20:28:14 +0000632 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnere617c9e2007-01-05 02:17:46 +0000633
Chris Lattnerad3448c2003-02-18 19:57:07 +0000634
Chris Lattner5e0d7182008-05-19 20:01:56 +0000635 // A+B --> A|B iff A and B have no bits set in common.
636 if (const IntegerType *IT = dyn_cast<IntegerType>(I.getType())) {
637 APInt Mask = APInt::getAllOnesValue(IT->getBitWidth());
638 APInt LHSKnownOne(IT->getBitWidth(), 0);
639 APInt LHSKnownZero(IT->getBitWidth(), 0);
640 ComputeMaskedBits(LHS, Mask, LHSKnownZero, LHSKnownOne);
641 if (LHSKnownZero != 0) {
642 APInt RHSKnownOne(IT->getBitWidth(), 0);
643 APInt RHSKnownZero(IT->getBitWidth(), 0);
644 ComputeMaskedBits(RHS, Mask, RHSKnownZero, RHSKnownOne);
645
646 // No bits in common -> bitwise or.
Chris Lattner9d60ba92008-05-19 20:03:53 +0000647 if ((LHSKnownZero|RHSKnownZero).isAllOnesValue())
Chris Lattner5e0d7182008-05-19 20:01:56 +0000648 return BinaryOperator::CreateOr(LHS, RHS);
Chris Lattner5e0d7182008-05-19 20:01:56 +0000649 }
650 }
Chris Lattnerc8802d22003-03-11 00:12:48 +0000651
Nick Lewyckyb6eabff2008-02-03 07:42:09 +0000652 // W*X + Y*Z --> W * (X+Z) iff W == Y
Nick Lewycky0c2c3f62008-02-03 08:19:11 +0000653 if (I.getType()->isIntOrIntVector()) {
Nick Lewyckyb6eabff2008-02-03 07:42:09 +0000654 Value *W, *X, *Y, *Z;
Dan Gohman4ae51262009-08-12 16:23:25 +0000655 if (match(LHS, m_Mul(m_Value(W), m_Value(X))) &&
656 match(RHS, m_Mul(m_Value(Y), m_Value(Z)))) {
Nick Lewyckyb6eabff2008-02-03 07:42:09 +0000657 if (W != Y) {
658 if (W == Z) {
Bill Wendling587c01d2008-02-26 10:53:30 +0000659 std::swap(Y, Z);
Nick Lewyckyb6eabff2008-02-03 07:42:09 +0000660 } else if (Y == X) {
Bill Wendling587c01d2008-02-26 10:53:30 +0000661 std::swap(W, X);
662 } else if (X == Z) {
Nick Lewyckyb6eabff2008-02-03 07:42:09 +0000663 std::swap(Y, Z);
664 std::swap(W, X);
665 }
666 }
667
668 if (W == Y) {
Chris Lattner74381062009-08-30 07:44:24 +0000669 Value *NewAdd = Builder->CreateAdd(X, Z, LHS->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000670 return BinaryOperator::CreateMul(W, NewAdd);
Nick Lewyckyb6eabff2008-02-03 07:42:09 +0000671 }
672 }
673 }
674
Chris Lattner6b032052003-10-02 15:11:26 +0000675 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
Chris Lattner4f637d42006-01-06 17:59:59 +0000676 Value *X = 0;
Dan Gohman4ae51262009-08-12 16:23:25 +0000677 if (match(LHS, m_Not(m_Value(X)))) // ~X + C --> (C-1) - X
Dan Gohman186a6362009-08-12 16:04:34 +0000678 return BinaryOperator::CreateSub(SubOne(CRHS), X);
Chris Lattneracd1f0f2004-07-30 07:50:03 +0000679
Chris Lattnerb99d6b12004-10-08 05:07:56 +0000680 // (X & FF00) + xx00 -> (X+xx00) & FF00
Owen Andersonc7d2ce72009-07-10 17:35:01 +0000681 if (LHS->hasOneUse() &&
Dan Gohman4ae51262009-08-12 16:23:25 +0000682 match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
Owen Andersonbaf3c402009-07-29 18:55:55 +0000683 Constant *Anded = ConstantExpr::getAnd(CRHS, C2);
Chris Lattnerb99d6b12004-10-08 05:07:56 +0000684 if (Anded == CRHS) {
685 // See if all bits from the first bit set in the Add RHS up are included
686 // in the mask. First, get the rightmost bit.
Chris Lattner32c0cf52010-01-05 06:29:13 +0000687 const APInt &AddRHSV = CRHS->getValue();
Chris Lattnerb99d6b12004-10-08 05:07:56 +0000688
689 // Form a mask of all bits from the lowest bit added through the top.
Zhou Sheng3a507fd2007-04-01 17:13:37 +0000690 APInt AddRHSHighBits(~((AddRHSV & -AddRHSV)-1));
Chris Lattnerb99d6b12004-10-08 05:07:56 +0000691
692 // See if the and mask includes all of these bits.
Zhou Sheng3a507fd2007-04-01 17:13:37 +0000693 APInt AddRHSHighBitsAnd(AddRHSHighBits & C2->getValue());
Misha Brukmanfd939082005-04-21 23:48:37 +0000694
Chris Lattnerb99d6b12004-10-08 05:07:56 +0000695 if (AddRHSHighBits == AddRHSHighBitsAnd) {
696 // Okay, the xform is safe. Insert the new add pronto.
Chris Lattner74381062009-08-30 07:44:24 +0000697 Value *NewAdd = Builder->CreateAdd(X, CRHS, LHS->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000698 return BinaryOperator::CreateAnd(NewAdd, C2);
Chris Lattnerb99d6b12004-10-08 05:07:56 +0000699 }
700 }
701 }
702
Chris Lattneracd1f0f2004-07-30 07:50:03 +0000703 // Try to fold constant add into select arguments.
704 if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
Chris Lattner80f43d32010-01-04 07:53:58 +0000705 if (Instruction *R = FoldOpIntoSelect(I, SI))
Chris Lattneracd1f0f2004-07-30 07:50:03 +0000706 return R;
Chris Lattner6b032052003-10-02 15:11:26 +0000707 }
708
Chris Lattner42790482007-12-20 01:56:58 +0000709 // add (select X 0 (sub n A)) A --> select X A n
Christopher Lamb30f017a2007-12-18 09:34:41 +0000710 {
711 SelectInst *SI = dyn_cast<SelectInst>(LHS);
Chris Lattner6046fb72008-11-16 04:46:19 +0000712 Value *A = RHS;
Christopher Lamb30f017a2007-12-18 09:34:41 +0000713 if (!SI) {
714 SI = dyn_cast<SelectInst>(RHS);
Chris Lattner6046fb72008-11-16 04:46:19 +0000715 A = LHS;
Christopher Lamb30f017a2007-12-18 09:34:41 +0000716 }
Chris Lattner42790482007-12-20 01:56:58 +0000717 if (SI && SI->hasOneUse()) {
Christopher Lamb30f017a2007-12-18 09:34:41 +0000718 Value *TV = SI->getTrueValue();
719 Value *FV = SI->getFalseValue();
Chris Lattner6046fb72008-11-16 04:46:19 +0000720 Value *N;
Christopher Lamb30f017a2007-12-18 09:34:41 +0000721
722 // Can we fold the add into the argument of the select?
723 // We check both true and false select arguments for a matching subtract.
Dan Gohman4ae51262009-08-12 16:23:25 +0000724 if (match(FV, m_Zero()) &&
725 match(TV, m_Sub(m_Value(N), m_Specific(A))))
Chris Lattner6046fb72008-11-16 04:46:19 +0000726 // Fold the add into the true select value.
Gabor Greif051a9502008-04-06 20:25:17 +0000727 return SelectInst::Create(SI->getCondition(), N, A);
Dan Gohman4ae51262009-08-12 16:23:25 +0000728 if (match(TV, m_Zero()) &&
729 match(FV, m_Sub(m_Value(N), m_Specific(A))))
Chris Lattner6046fb72008-11-16 04:46:19 +0000730 // Fold the add into the false select value.
Gabor Greif051a9502008-04-06 20:25:17 +0000731 return SelectInst::Create(SI->getCondition(), A, N);
Christopher Lamb30f017a2007-12-18 09:34:41 +0000732 }
733 }
Andrew Lenharth16d79552006-09-19 18:24:51 +0000734
Chris Lattner3d28b1b2008-05-20 05:46:13 +0000735 // Check for (add (sext x), y), see if we can merge this into an
736 // integer add followed by a sext.
737 if (SExtInst *LHSConv = dyn_cast<SExtInst>(LHS)) {
738 // (add (sext x), cst) --> (sext (add x, cst'))
739 if (ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS)) {
740 Constant *CI =
Owen Andersonbaf3c402009-07-29 18:55:55 +0000741 ConstantExpr::getTrunc(RHSC, LHSConv->getOperand(0)->getType());
Chris Lattner3d28b1b2008-05-20 05:46:13 +0000742 if (LHSConv->hasOneUse() &&
Owen Andersonbaf3c402009-07-29 18:55:55 +0000743 ConstantExpr::getSExt(CI, I.getType()) == RHSC &&
Chris Lattner3d28b1b2008-05-20 05:46:13 +0000744 WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
745 // Insert the new, smaller add.
Dan Gohmanfe359552009-10-26 22:14:22 +0000746 Value *NewAdd = Builder->CreateNSWAdd(LHSConv->getOperand(0),
747 CI, "addconv");
Chris Lattner3d28b1b2008-05-20 05:46:13 +0000748 return new SExtInst(NewAdd, I.getType());
749 }
750 }
751
752 // (add (sext x), (sext y)) --> (sext (add int x, y))
753 if (SExtInst *RHSConv = dyn_cast<SExtInst>(RHS)) {
754 // Only do this if x/y have the same type, if at last one of them has a
755 // single use (so we don't increase the number of sexts), and if the
756 // integer add will not overflow.
757 if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
758 (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
759 WillNotOverflowSignedAdd(LHSConv->getOperand(0),
760 RHSConv->getOperand(0))) {
761 // Insert the new integer add.
Dan Gohmanfe359552009-10-26 22:14:22 +0000762 Value *NewAdd = Builder->CreateNSWAdd(LHSConv->getOperand(0),
763 RHSConv->getOperand(0), "addconv");
Chris Lattner3d28b1b2008-05-20 05:46:13 +0000764 return new SExtInst(NewAdd, I.getType());
765 }
766 }
767 }
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000768
769 return Changed ? &I : 0;
770}
771
772Instruction *InstCombiner::visitFAdd(BinaryOperator &I) {
773 bool Changed = SimplifyCommutative(I);
774 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
775
776 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
777 // X + 0 --> X
778 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
Owen Anderson6f83c9c2009-07-27 20:59:43 +0000779 if (CFP->isExactlyValue(ConstantFP::getNegativeZero
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000780 (I.getType())->getValueAPF()))
781 return ReplaceInstUsesWith(I, LHS);
782 }
783
784 if (isa<PHINode>(LHS))
785 if (Instruction *NV = FoldOpIntoPhi(I))
786 return NV;
787 }
788
789 // -A + B --> B - A
790 // -A + -B --> -(A + B)
Dan Gohman186a6362009-08-12 16:04:34 +0000791 if (Value *LHSV = dyn_castFNegVal(LHS))
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000792 return BinaryOperator::CreateFSub(RHS, LHSV);
793
794 // A + -B --> A - B
795 if (!isa<Constant>(RHS))
Dan Gohman186a6362009-08-12 16:04:34 +0000796 if (Value *V = dyn_castFNegVal(RHS))
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000797 return BinaryOperator::CreateFSub(LHS, V);
798
799 // Check for X+0.0. Simplify it to X if we know X is not -0.0.
800 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS))
801 if (CFP->getValueAPF().isPosZero() && CannotBeNegativeZero(LHS))
802 return ReplaceInstUsesWith(I, LHS);
803
Chris Lattner3d28b1b2008-05-20 05:46:13 +0000804 // Check for (add double (sitofp x), y), see if we can merge this into an
805 // integer add followed by a promotion.
806 if (SIToFPInst *LHSConv = dyn_cast<SIToFPInst>(LHS)) {
807 // (add double (sitofp x), fpcst) --> (sitofp (add int x, intcst))
808 // ... if the constant fits in the integer value. This is useful for things
809 // like (double)(x & 1234) + 4.0 -> (double)((X & 1234)+4) which no longer
810 // requires a constant pool load, and generally allows the add to be better
811 // instcombined.
812 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS)) {
813 Constant *CI =
Owen Andersonbaf3c402009-07-29 18:55:55 +0000814 ConstantExpr::getFPToSI(CFP, LHSConv->getOperand(0)->getType());
Chris Lattner3d28b1b2008-05-20 05:46:13 +0000815 if (LHSConv->hasOneUse() &&
Owen Andersonbaf3c402009-07-29 18:55:55 +0000816 ConstantExpr::getSIToFP(CI, I.getType()) == CFP &&
Chris Lattner3d28b1b2008-05-20 05:46:13 +0000817 WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
818 // Insert the new integer add.
Dan Gohmanfe359552009-10-26 22:14:22 +0000819 Value *NewAdd = Builder->CreateNSWAdd(LHSConv->getOperand(0),
820 CI, "addconv");
Chris Lattner3d28b1b2008-05-20 05:46:13 +0000821 return new SIToFPInst(NewAdd, I.getType());
822 }
823 }
824
825 // (add double (sitofp x), (sitofp y)) --> (sitofp (add int x, y))
826 if (SIToFPInst *RHSConv = dyn_cast<SIToFPInst>(RHS)) {
827 // Only do this if x/y have the same type, if at last one of them has a
828 // single use (so we don't increase the number of int->fp conversions),
829 // and if the integer add will not overflow.
830 if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
831 (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
832 WillNotOverflowSignedAdd(LHSConv->getOperand(0),
833 RHSConv->getOperand(0))) {
834 // Insert the new integer add.
Dan Gohmanfe359552009-10-26 22:14:22 +0000835 Value *NewAdd = Builder->CreateNSWAdd(LHSConv->getOperand(0),
Chris Lattner092543c2009-11-04 08:05:20 +0000836 RHSConv->getOperand(0),"addconv");
Chris Lattner3d28b1b2008-05-20 05:46:13 +0000837 return new SIToFPInst(NewAdd, I.getType());
838 }
839 }
840 }
841
Chris Lattner7e708292002-06-25 16:13:24 +0000842 return Changed ? &I : 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000843}
844
Chris Lattner092543c2009-11-04 08:05:20 +0000845
846/// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
847/// code necessary to compute the offset from the base pointer (without adding
848/// in the base pointer). Return the result as a signed integer of intptr size.
Chris Lattner02446fc2010-01-04 07:37:31 +0000849Value *InstCombiner::EmitGEPOffset(User *GEP) {
850 TargetData &TD = *getTargetData();
Chris Lattner092543c2009-11-04 08:05:20 +0000851 gep_type_iterator GTI = gep_type_begin(GEP);
852 const Type *IntPtrTy = TD.getIntPtrType(GEP->getContext());
853 Value *Result = Constant::getNullValue(IntPtrTy);
854
855 // Build a mask for high order bits.
856 unsigned IntPtrWidth = TD.getPointerSizeInBits();
857 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
858
859 for (User::op_iterator i = GEP->op_begin() + 1, e = GEP->op_end(); i != e;
860 ++i, ++GTI) {
861 Value *Op = *i;
862 uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType()) & PtrSizeMask;
863 if (ConstantInt *OpC = dyn_cast<ConstantInt>(Op)) {
864 if (OpC->isZero()) continue;
865
866 // Handle a struct index, which adds its field offset to the pointer.
867 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
868 Size = TD.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
869
Chris Lattner02446fc2010-01-04 07:37:31 +0000870 Result = Builder->CreateAdd(Result,
871 ConstantInt::get(IntPtrTy, Size),
872 GEP->getName()+".offs");
Chris Lattner092543c2009-11-04 08:05:20 +0000873 continue;
874 }
875
876 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
877 Constant *OC =
878 ConstantExpr::getIntegerCast(OpC, IntPtrTy, true /*SExt*/);
879 Scale = ConstantExpr::getMul(OC, Scale);
880 // Emit an add instruction.
Chris Lattner02446fc2010-01-04 07:37:31 +0000881 Result = Builder->CreateAdd(Result, Scale, GEP->getName()+".offs");
Chris Lattner092543c2009-11-04 08:05:20 +0000882 continue;
883 }
884 // Convert to correct type.
885 if (Op->getType() != IntPtrTy)
Chris Lattner02446fc2010-01-04 07:37:31 +0000886 Op = Builder->CreateIntCast(Op, IntPtrTy, true, Op->getName()+".c");
Chris Lattner092543c2009-11-04 08:05:20 +0000887 if (Size != 1) {
888 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
889 // We'll let instcombine(mul) convert this to a shl if possible.
Chris Lattner02446fc2010-01-04 07:37:31 +0000890 Op = Builder->CreateMul(Op, Scale, GEP->getName()+".idx");
Chris Lattner092543c2009-11-04 08:05:20 +0000891 }
892
893 // Emit an add instruction.
Chris Lattner02446fc2010-01-04 07:37:31 +0000894 Result = Builder->CreateAdd(Op, Result, GEP->getName()+".offs");
Chris Lattner092543c2009-11-04 08:05:20 +0000895 }
896 return Result;
897}
898
899
Chris Lattner092543c2009-11-04 08:05:20 +0000900
901
902/// Optimize pointer differences into the same array into a size. Consider:
903/// &A[10] - &A[0]: we should compile this to "10". LHS/RHS are the pointer
904/// operands to the ptrtoint instructions for the LHS/RHS of the subtract.
905///
906Value *InstCombiner::OptimizePointerDifference(Value *LHS, Value *RHS,
907 const Type *Ty) {
908 assert(TD && "Must have target data info for this");
909
910 // If LHS is a gep based on RHS or RHS is a gep based on LHS, we can optimize
911 // this.
Chris Lattner0cb1e9e2010-01-04 18:48:26 +0000912 bool Swapped = false;
Chris Lattner85c1c962010-01-01 22:42:29 +0000913 GetElementPtrInst *GEP = 0;
914 ConstantExpr *CstGEP = 0;
Chris Lattner092543c2009-11-04 08:05:20 +0000915
Chris Lattner85c1c962010-01-01 22:42:29 +0000916 // TODO: Could also optimize &A[i] - &A[j] -> "i-j", and "&A.foo[i] - &A.foo".
917 // For now we require one side to be the base pointer "A" or a constant
918 // expression derived from it.
919 if (GetElementPtrInst *LHSGEP = dyn_cast<GetElementPtrInst>(LHS)) {
920 // (gep X, ...) - X
921 if (LHSGEP->getOperand(0) == RHS) {
922 GEP = LHSGEP;
923 Swapped = false;
924 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(RHS)) {
925 // (gep X, ...) - (ce_gep X, ...)
926 if (CE->getOpcode() == Instruction::GetElementPtr &&
927 LHSGEP->getOperand(0) == CE->getOperand(0)) {
928 CstGEP = CE;
929 GEP = LHSGEP;
930 Swapped = false;
931 }
932 }
933 }
934
935 if (GetElementPtrInst *RHSGEP = dyn_cast<GetElementPtrInst>(RHS)) {
936 // X - (gep X, ...)
937 if (RHSGEP->getOperand(0) == LHS) {
938 GEP = RHSGEP;
939 Swapped = true;
940 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(LHS)) {
941 // (ce_gep X, ...) - (gep X, ...)
942 if (CE->getOpcode() == Instruction::GetElementPtr &&
943 RHSGEP->getOperand(0) == CE->getOperand(0)) {
944 CstGEP = CE;
945 GEP = RHSGEP;
946 Swapped = true;
947 }
948 }
949 }
950
951 if (GEP == 0)
Chris Lattner092543c2009-11-04 08:05:20 +0000952 return 0;
953
Chris Lattner092543c2009-11-04 08:05:20 +0000954 // Emit the offset of the GEP and an intptr_t.
Chris Lattner02446fc2010-01-04 07:37:31 +0000955 Value *Result = EmitGEPOffset(GEP);
Chris Lattner85c1c962010-01-01 22:42:29 +0000956
957 // If we had a constant expression GEP on the other side offsetting the
958 // pointer, subtract it from the offset we have.
959 if (CstGEP) {
Chris Lattner02446fc2010-01-04 07:37:31 +0000960 Value *CstOffset = EmitGEPOffset(CstGEP);
Chris Lattner85c1c962010-01-01 22:42:29 +0000961 Result = Builder->CreateSub(Result, CstOffset);
962 }
963
Chris Lattner092543c2009-11-04 08:05:20 +0000964
965 // If we have p - gep(p, ...) then we have to negate the result.
966 if (Swapped)
967 Result = Builder->CreateNeg(Result, "diff.neg");
968
969 return Builder->CreateIntCast(Result, Ty, true);
970}
971
972
Chris Lattner7e708292002-06-25 16:13:24 +0000973Instruction *InstCombiner::visitSub(BinaryOperator &I) {
Chris Lattner7e708292002-06-25 16:13:24 +0000974 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +0000975
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000976 if (Op0 == Op1) // sub X, X -> 0
Owen Andersona7235ea2009-07-31 20:28:14 +0000977 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000978
Chris Lattner3bf68152009-12-21 04:04:05 +0000979 // If this is a 'B = x-(-A)', change to B = x+A. This preserves NSW/NUW.
980 if (Value *V = dyn_castNegVal(Op1)) {
981 BinaryOperator *Res = BinaryOperator::CreateAdd(Op0, V);
982 Res->setHasNoSignedWrap(I.hasNoSignedWrap());
983 Res->setHasNoUnsignedWrap(I.hasNoUnsignedWrap());
984 return Res;
985 }
Chris Lattnerb35dde12002-05-06 16:49:18 +0000986
Chris Lattnere87597f2004-10-16 18:11:37 +0000987 if (isa<UndefValue>(Op0))
988 return ReplaceInstUsesWith(I, Op0); // undef - X -> undef
989 if (isa<UndefValue>(Op1))
990 return ReplaceInstUsesWith(I, Op1); // X - undef -> undef
Chris Lattner4de84762010-01-04 07:02:48 +0000991 if (I.getType() == Type::getInt1Ty(I.getContext()))
Chris Lattner092543c2009-11-04 08:05:20 +0000992 return BinaryOperator::CreateXor(Op0, Op1);
993
Chris Lattnerd65460f2003-11-05 01:06:05 +0000994 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
Chris Lattner092543c2009-11-04 08:05:20 +0000995 // Replace (-1 - A) with (~A).
Chris Lattnera2881962003-02-18 19:28:33 +0000996 if (C->isAllOnesValue())
Dan Gohman4ae51262009-08-12 16:23:25 +0000997 return BinaryOperator::CreateNot(Op1);
Chris Lattner40371712002-05-09 01:29:19 +0000998
Chris Lattnerd65460f2003-11-05 01:06:05 +0000999 // C - ~X == X + (1+C)
Reid Spencer4b828e62005-06-18 17:37:34 +00001000 Value *X = 0;
Dan Gohman4ae51262009-08-12 16:23:25 +00001001 if (match(Op1, m_Not(m_Value(X))))
Dan Gohman186a6362009-08-12 16:04:34 +00001002 return BinaryOperator::CreateAdd(X, AddOne(C));
Reid Spencer7177c3a2007-03-25 05:33:51 +00001003
Chris Lattner76b7a062007-01-15 07:02:54 +00001004 // -(X >>u 31) -> (X >>s 31)
1005 // -(X >>s 31) -> (X >>u 31)
Zhou Sheng302748d2007-03-30 17:20:39 +00001006 if (C->isZero()) {
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00001007 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op1)) {
Reid Spencer3822ff52006-11-08 06:47:33 +00001008 if (SI->getOpcode() == Instruction::LShr) {
Reid Spencerb83eb642006-10-20 07:07:24 +00001009 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
Chris Lattner9c290672004-03-12 23:53:13 +00001010 // Check to see if we are shifting out everything but the sign bit.
Zhou Sheng302748d2007-03-30 17:20:39 +00001011 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
Reid Spencerb83eb642006-10-20 07:07:24 +00001012 SI->getType()->getPrimitiveSizeInBits()-1) {
Reid Spencer3822ff52006-11-08 06:47:33 +00001013 // Ok, the transformation is safe. Insert AShr.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001014 return BinaryOperator::Create(Instruction::AShr,
Reid Spencer832254e2007-02-02 02:16:23 +00001015 SI->getOperand(0), CU, SI->getName());
Chris Lattner9c290672004-03-12 23:53:13 +00001016 }
1017 }
Chris Lattner092543c2009-11-04 08:05:20 +00001018 } else if (SI->getOpcode() == Instruction::AShr) {
Reid Spencer3822ff52006-11-08 06:47:33 +00001019 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
1020 // Check to see if we are shifting out everything but the sign bit.
Zhou Sheng302748d2007-03-30 17:20:39 +00001021 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
Reid Spencer3822ff52006-11-08 06:47:33 +00001022 SI->getType()->getPrimitiveSizeInBits()-1) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00001023 // Ok, the transformation is safe. Insert LShr.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001024 return BinaryOperator::CreateLShr(
Reid Spencer832254e2007-02-02 02:16:23 +00001025 SI->getOperand(0), CU, SI->getName());
Reid Spencer3822ff52006-11-08 06:47:33 +00001026 }
1027 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00001028 }
1029 }
Chris Lattnerbfe492b2004-03-13 00:11:49 +00001030 }
Chris Lattner2eefe512004-04-09 19:05:30 +00001031
1032 // Try to fold constant sub into select arguments.
1033 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner80f43d32010-01-04 07:53:58 +00001034 if (Instruction *R = FoldOpIntoSelect(I, SI))
Chris Lattner2eefe512004-04-09 19:05:30 +00001035 return R;
Eli Friedman709b33d2009-07-13 22:27:52 +00001036
1037 // C - zext(bool) -> bool ? C - 1 : C
1038 if (ZExtInst *ZI = dyn_cast<ZExtInst>(Op1))
Chris Lattner4de84762010-01-04 07:02:48 +00001039 if (ZI->getSrcTy() == Type::getInt1Ty(I.getContext()))
Dan Gohman186a6362009-08-12 16:04:34 +00001040 return SelectInst::Create(ZI->getOperand(0), SubOne(C), C);
Chris Lattnerd65460f2003-11-05 01:06:05 +00001041 }
1042
Chris Lattner43d84d62005-04-07 16:15:25 +00001043 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001044 if (Op1I->getOpcode() == Instruction::Add) {
Chris Lattner08954a22005-04-07 16:28:01 +00001045 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
Dan Gohman4ae51262009-08-12 16:23:25 +00001046 return BinaryOperator::CreateNeg(Op1I->getOperand(1),
Owen Anderson0a5372e2009-07-13 04:09:18 +00001047 I.getName());
Chris Lattner08954a22005-04-07 16:28:01 +00001048 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
Dan Gohman4ae51262009-08-12 16:23:25 +00001049 return BinaryOperator::CreateNeg(Op1I->getOperand(0),
Owen Anderson0a5372e2009-07-13 04:09:18 +00001050 I.getName());
Chris Lattner08954a22005-04-07 16:28:01 +00001051 else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
1052 if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
1053 // C1-(X+C2) --> (C1-C2)-X
Owen Andersond672ecb2009-07-03 00:17:18 +00001054 return BinaryOperator::CreateSub(
Owen Andersonbaf3c402009-07-29 18:55:55 +00001055 ConstantExpr::getSub(CI1, CI2), Op1I->getOperand(0));
Chris Lattner08954a22005-04-07 16:28:01 +00001056 }
Chris Lattner43d84d62005-04-07 16:15:25 +00001057 }
1058
Chris Lattnerfd059242003-10-15 16:48:29 +00001059 if (Op1I->hasOneUse()) {
Chris Lattnera2881962003-02-18 19:28:33 +00001060 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
1061 // is not used by anyone else...
1062 //
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001063 if (Op1I->getOpcode() == Instruction::Sub) {
Chris Lattnera2881962003-02-18 19:28:33 +00001064 // Swap the two operands of the subexpr...
1065 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
1066 Op1I->setOperand(0, IIOp1);
1067 Op1I->setOperand(1, IIOp0);
Misha Brukmanfd939082005-04-21 23:48:37 +00001068
Chris Lattnera2881962003-02-18 19:28:33 +00001069 // Create the new top level add instruction...
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001070 return BinaryOperator::CreateAdd(Op0, Op1);
Chris Lattnera2881962003-02-18 19:28:33 +00001071 }
1072
1073 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
1074 //
1075 if (Op1I->getOpcode() == Instruction::And &&
1076 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
1077 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
1078
Chris Lattner74381062009-08-30 07:44:24 +00001079 Value *NewNot = Builder->CreateNot(OtherOp, "B.not");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001080 return BinaryOperator::CreateAnd(Op0, NewNot);
Chris Lattnera2881962003-02-18 19:28:33 +00001081 }
Chris Lattnerad3448c2003-02-18 19:57:07 +00001082
Reid Spencerac5209e2006-10-16 23:08:08 +00001083 // 0 - (X sdiv C) -> (X sdiv -C)
Reid Spencer1628cec2006-10-26 06:15:43 +00001084 if (Op1I->getOpcode() == Instruction::SDiv)
Reid Spencerb83eb642006-10-20 07:07:24 +00001085 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
Zhou Sheng843f07672007-04-19 05:39:12 +00001086 if (CSI->isZero())
Chris Lattner91ccc152004-10-06 15:08:25 +00001087 if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001088 return BinaryOperator::CreateSDiv(Op1I->getOperand(0),
Owen Andersonbaf3c402009-07-29 18:55:55 +00001089 ConstantExpr::getNeg(DivRHS));
Chris Lattner91ccc152004-10-06 15:08:25 +00001090
Chris Lattnerad3448c2003-02-18 19:57:07 +00001091 // X - X*C --> X * (1-C)
Reid Spencer4b828e62005-06-18 17:37:34 +00001092 ConstantInt *C2 = 0;
Dan Gohman186a6362009-08-12 16:04:34 +00001093 if (dyn_castFoldableMul(Op1I, C2) == Op0) {
Owen Andersond672ecb2009-07-03 00:17:18 +00001094 Constant *CP1 =
Owen Andersonbaf3c402009-07-29 18:55:55 +00001095 ConstantExpr::getSub(ConstantInt::get(I.getType(), 1),
Dan Gohman6de29f82009-06-15 22:12:54 +00001096 C2);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001097 return BinaryOperator::CreateMul(Op0, CP1);
Chris Lattnerad3448c2003-02-18 19:57:07 +00001098 }
Chris Lattner40371712002-05-09 01:29:19 +00001099 }
Chris Lattner43d84d62005-04-07 16:15:25 +00001100 }
Chris Lattnera2881962003-02-18 19:28:33 +00001101
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001102 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
1103 if (Op0I->getOpcode() == Instruction::Add) {
1104 if (Op0I->getOperand(0) == Op1) // (Y+X)-Y == X
1105 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
1106 else if (Op0I->getOperand(1) == Op1) // (X+Y)-Y == X
1107 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
1108 } else if (Op0I->getOpcode() == Instruction::Sub) {
1109 if (Op0I->getOperand(0) == Op1) // (X-Y)-X == -Y
Dan Gohman4ae51262009-08-12 16:23:25 +00001110 return BinaryOperator::CreateNeg(Op0I->getOperand(1),
Owen Anderson0a5372e2009-07-13 04:09:18 +00001111 I.getName());
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00001112 }
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001113 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001114
Chris Lattner50af16a2004-11-13 19:50:12 +00001115 ConstantInt *C1;
Dan Gohman186a6362009-08-12 16:04:34 +00001116 if (Value *X = dyn_castFoldableMul(Op0, C1)) {
Reid Spencer7177c3a2007-03-25 05:33:51 +00001117 if (X == Op1) // X*C - X --> X * (C-1)
Dan Gohman186a6362009-08-12 16:04:34 +00001118 return BinaryOperator::CreateMul(Op1, SubOne(C1));
Chris Lattnerad3448c2003-02-18 19:57:07 +00001119
Chris Lattner50af16a2004-11-13 19:50:12 +00001120 ConstantInt *C2; // X*C1 - X*C2 -> X * (C1-C2)
Dan Gohman186a6362009-08-12 16:04:34 +00001121 if (X == dyn_castFoldableMul(Op1, C2))
Owen Andersonbaf3c402009-07-29 18:55:55 +00001122 return BinaryOperator::CreateMul(X, ConstantExpr::getSub(C1, C2));
Chris Lattner50af16a2004-11-13 19:50:12 +00001123 }
Chris Lattner092543c2009-11-04 08:05:20 +00001124
1125 // Optimize pointer differences into the same array into a size. Consider:
1126 // &A[10] - &A[0]: we should compile this to "10".
1127 if (TD) {
Chris Lattner33767182010-01-01 22:12:03 +00001128 Value *LHSOp, *RHSOp;
Chris Lattnerf2ebc682010-01-01 22:29:12 +00001129 if (match(Op0, m_PtrToInt(m_Value(LHSOp))) &&
1130 match(Op1, m_PtrToInt(m_Value(RHSOp))))
Chris Lattner33767182010-01-01 22:12:03 +00001131 if (Value *Res = OptimizePointerDifference(LHSOp, RHSOp, I.getType()))
1132 return ReplaceInstUsesWith(I, Res);
Chris Lattner092543c2009-11-04 08:05:20 +00001133
1134 // trunc(p)-trunc(q) -> trunc(p-q)
Chris Lattnerf2ebc682010-01-01 22:29:12 +00001135 if (match(Op0, m_Trunc(m_PtrToInt(m_Value(LHSOp)))) &&
1136 match(Op1, m_Trunc(m_PtrToInt(m_Value(RHSOp)))))
1137 if (Value *Res = OptimizePointerDifference(LHSOp, RHSOp, I.getType()))
1138 return ReplaceInstUsesWith(I, Res);
Chris Lattner092543c2009-11-04 08:05:20 +00001139 }
1140
Chris Lattner3f5b8772002-05-06 16:14:14 +00001141 return 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00001142}
1143
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001144Instruction *InstCombiner::visitFSub(BinaryOperator &I) {
1145 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1146
1147 // If this is a 'B = x-(-A)', change to B = x+A...
Dan Gohman186a6362009-08-12 16:04:34 +00001148 if (Value *V = dyn_castFNegVal(Op1))
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001149 return BinaryOperator::CreateFAdd(Op0, V);
1150
1151 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
1152 if (Op1I->getOpcode() == Instruction::FAdd) {
1153 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
Dan Gohman4ae51262009-08-12 16:23:25 +00001154 return BinaryOperator::CreateFNeg(Op1I->getOperand(1),
Owen Anderson0a5372e2009-07-13 04:09:18 +00001155 I.getName());
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001156 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
Dan Gohman4ae51262009-08-12 16:23:25 +00001157 return BinaryOperator::CreateFNeg(Op1I->getOperand(0),
Owen Anderson0a5372e2009-07-13 04:09:18 +00001158 I.getName());
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001159 }
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001160 }
1161
1162 return 0;
1163}
1164
Reid Spencere4d87aa2006-12-23 06:05:41 +00001165/// getICmpCode - Encode a icmp predicate into a three bit mask. These bits
Chris Lattneraa9c1f12003-08-13 20:16:26 +00001166/// are carefully arranged to allow folding of expressions such as:
1167///
1168/// (A < B) | (A > B) --> (A != B)
1169///
Reid Spencere4d87aa2006-12-23 06:05:41 +00001170/// Note that this is only valid if the first and second predicates have the
1171/// same sign. Is illegal to do: (A u< B) | (A s> B)
Chris Lattneraa9c1f12003-08-13 20:16:26 +00001172///
Reid Spencere4d87aa2006-12-23 06:05:41 +00001173/// Three bits are used to represent the condition, as follows:
1174/// 0 A > B
1175/// 1 A == B
1176/// 2 A < B
1177///
1178/// <=> Value Definition
1179/// 000 0 Always false
1180/// 001 1 A > B
1181/// 010 2 A == B
1182/// 011 3 A >= B
1183/// 100 4 A < B
1184/// 101 5 A != B
1185/// 110 6 A <= B
1186/// 111 7 Always true
1187///
1188static unsigned getICmpCode(const ICmpInst *ICI) {
1189 switch (ICI->getPredicate()) {
Chris Lattneraa9c1f12003-08-13 20:16:26 +00001190 // False -> 0
Reid Spencere4d87aa2006-12-23 06:05:41 +00001191 case ICmpInst::ICMP_UGT: return 1; // 001
1192 case ICmpInst::ICMP_SGT: return 1; // 001
1193 case ICmpInst::ICMP_EQ: return 2; // 010
1194 case ICmpInst::ICMP_UGE: return 3; // 011
1195 case ICmpInst::ICMP_SGE: return 3; // 011
1196 case ICmpInst::ICMP_ULT: return 4; // 100
1197 case ICmpInst::ICMP_SLT: return 4; // 100
1198 case ICmpInst::ICMP_NE: return 5; // 101
1199 case ICmpInst::ICMP_ULE: return 6; // 110
1200 case ICmpInst::ICMP_SLE: return 6; // 110
Chris Lattneraa9c1f12003-08-13 20:16:26 +00001201 // True -> 7
1202 default:
Torok Edwinc23197a2009-07-14 16:55:14 +00001203 llvm_unreachable("Invalid ICmp predicate!");
Chris Lattneraa9c1f12003-08-13 20:16:26 +00001204 return 0;
1205 }
1206}
1207
Evan Cheng8db90722008-10-14 17:15:11 +00001208/// getFCmpCode - Similar to getICmpCode but for FCmpInst. This encodes a fcmp
1209/// predicate into a three bit mask. It also returns whether it is an ordered
1210/// predicate by reference.
1211static unsigned getFCmpCode(FCmpInst::Predicate CC, bool &isOrdered) {
1212 isOrdered = false;
1213 switch (CC) {
1214 case FCmpInst::FCMP_ORD: isOrdered = true; return 0; // 000
1215 case FCmpInst::FCMP_UNO: return 0; // 000
Evan Cheng4990b252008-10-14 18:13:38 +00001216 case FCmpInst::FCMP_OGT: isOrdered = true; return 1; // 001
1217 case FCmpInst::FCMP_UGT: return 1; // 001
1218 case FCmpInst::FCMP_OEQ: isOrdered = true; return 2; // 010
1219 case FCmpInst::FCMP_UEQ: return 2; // 010
Evan Cheng8db90722008-10-14 17:15:11 +00001220 case FCmpInst::FCMP_OGE: isOrdered = true; return 3; // 011
1221 case FCmpInst::FCMP_UGE: return 3; // 011
1222 case FCmpInst::FCMP_OLT: isOrdered = true; return 4; // 100
1223 case FCmpInst::FCMP_ULT: return 4; // 100
Evan Cheng4990b252008-10-14 18:13:38 +00001224 case FCmpInst::FCMP_ONE: isOrdered = true; return 5; // 101
1225 case FCmpInst::FCMP_UNE: return 5; // 101
Evan Cheng8db90722008-10-14 17:15:11 +00001226 case FCmpInst::FCMP_OLE: isOrdered = true; return 6; // 110
1227 case FCmpInst::FCMP_ULE: return 6; // 110
Evan Cheng40300622008-10-14 18:44:08 +00001228 // True -> 7
Evan Cheng8db90722008-10-14 17:15:11 +00001229 default:
1230 // Not expecting FCMP_FALSE and FCMP_TRUE;
Torok Edwinc23197a2009-07-14 16:55:14 +00001231 llvm_unreachable("Unexpected FCmp predicate!");
Evan Cheng8db90722008-10-14 17:15:11 +00001232 return 0;
1233 }
1234}
1235
Reid Spencere4d87aa2006-12-23 06:05:41 +00001236/// getICmpValue - This is the complement of getICmpCode, which turns an
1237/// opcode and two operands into either a constant true or false, or a brand
Dan Gohman5d066ff2007-09-17 17:31:57 +00001238/// new ICmp instruction. The sign is passed in to determine which kind
Evan Cheng8db90722008-10-14 17:15:11 +00001239/// of predicate to use in the new icmp instruction.
Chris Lattnera317e042010-01-05 06:59:49 +00001240static Value *getICmpValue(bool Sign, unsigned Code, Value *LHS, Value *RHS) {
1241 switch (Code) {
1242 default: assert(0 && "Illegal ICmp code!");
1243 case 0:
1244 return ConstantInt::getFalse(LHS->getContext());
1245 case 1:
1246 if (Sign)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00001247 return new ICmpInst(ICmpInst::ICMP_SGT, LHS, RHS);
Chris Lattnera317e042010-01-05 06:59:49 +00001248 return new ICmpInst(ICmpInst::ICMP_UGT, LHS, RHS);
1249 case 2:
1250 return new ICmpInst(ICmpInst::ICMP_EQ, LHS, RHS);
1251 case 3:
1252 if (Sign)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00001253 return new ICmpInst(ICmpInst::ICMP_SGE, LHS, RHS);
Chris Lattnera317e042010-01-05 06:59:49 +00001254 return new ICmpInst(ICmpInst::ICMP_UGE, LHS, RHS);
1255 case 4:
1256 if (Sign)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00001257 return new ICmpInst(ICmpInst::ICMP_SLT, LHS, RHS);
Chris Lattnera317e042010-01-05 06:59:49 +00001258 return new ICmpInst(ICmpInst::ICMP_ULT, LHS, RHS);
1259 case 5:
1260 return new ICmpInst(ICmpInst::ICMP_NE, LHS, RHS);
1261 case 6:
1262 if (Sign)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00001263 return new ICmpInst(ICmpInst::ICMP_SLE, LHS, RHS);
Chris Lattnera317e042010-01-05 06:59:49 +00001264 return new ICmpInst(ICmpInst::ICMP_ULE, LHS, RHS);
1265 case 7:
1266 return ConstantInt::getTrue(LHS->getContext());
Chris Lattneraa9c1f12003-08-13 20:16:26 +00001267 }
1268}
1269
Evan Cheng8db90722008-10-14 17:15:11 +00001270/// getFCmpValue - This is the complement of getFCmpCode, which turns an
1271/// opcode and two operands into either a FCmp instruction. isordered is passed
1272/// in to determine which kind of predicate to use in the new fcmp instruction.
1273static Value *getFCmpValue(bool isordered, unsigned code,
Chris Lattner4de84762010-01-04 07:02:48 +00001274 Value *LHS, Value *RHS) {
Evan Cheng8db90722008-10-14 17:15:11 +00001275 switch (code) {
Torok Edwinc23197a2009-07-14 16:55:14 +00001276 default: llvm_unreachable("Illegal FCmp code!");
Evan Cheng8db90722008-10-14 17:15:11 +00001277 case 0:
1278 if (isordered)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00001279 return new FCmpInst(FCmpInst::FCMP_ORD, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00001280 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00001281 return new FCmpInst(FCmpInst::FCMP_UNO, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00001282 case 1:
1283 if (isordered)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00001284 return new FCmpInst(FCmpInst::FCMP_OGT, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00001285 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00001286 return new FCmpInst(FCmpInst::FCMP_UGT, LHS, RHS);
Evan Cheng4990b252008-10-14 18:13:38 +00001287 case 2:
1288 if (isordered)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00001289 return new FCmpInst(FCmpInst::FCMP_OEQ, LHS, RHS);
Evan Cheng4990b252008-10-14 18:13:38 +00001290 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00001291 return new FCmpInst(FCmpInst::FCMP_UEQ, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00001292 case 3:
1293 if (isordered)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00001294 return new FCmpInst(FCmpInst::FCMP_OGE, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00001295 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00001296 return new FCmpInst(FCmpInst::FCMP_UGE, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00001297 case 4:
1298 if (isordered)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00001299 return new FCmpInst(FCmpInst::FCMP_OLT, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00001300 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00001301 return new FCmpInst(FCmpInst::FCMP_ULT, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00001302 case 5:
1303 if (isordered)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00001304 return new FCmpInst(FCmpInst::FCMP_ONE, LHS, RHS);
Evan Cheng4990b252008-10-14 18:13:38 +00001305 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00001306 return new FCmpInst(FCmpInst::FCMP_UNE, LHS, RHS);
Evan Cheng4990b252008-10-14 18:13:38 +00001307 case 6:
1308 if (isordered)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00001309 return new FCmpInst(FCmpInst::FCMP_OLE, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00001310 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00001311 return new FCmpInst(FCmpInst::FCMP_ULE, LHS, RHS);
Chris Lattner4de84762010-01-04 07:02:48 +00001312 case 7: return ConstantInt::getTrue(LHS->getContext());
Evan Cheng8db90722008-10-14 17:15:11 +00001313 }
1314}
1315
Chris Lattnerb9553d62008-11-16 04:55:20 +00001316/// PredicatesFoldable - Return true if both predicates match sign or if at
1317/// least one of them is an equality comparison (which is signless).
Reid Spencere4d87aa2006-12-23 06:05:41 +00001318static bool PredicatesFoldable(ICmpInst::Predicate p1, ICmpInst::Predicate p2) {
Nick Lewycky4a134af2009-10-25 05:20:17 +00001319 return (CmpInst::isSigned(p1) == CmpInst::isSigned(p2)) ||
1320 (CmpInst::isSigned(p1) && ICmpInst::isEquality(p2)) ||
1321 (CmpInst::isSigned(p2) && ICmpInst::isEquality(p1));
Reid Spencere4d87aa2006-12-23 06:05:41 +00001322}
1323
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00001324// OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
1325// the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
Reid Spencer832254e2007-02-02 02:16:23 +00001326// guaranteed to be a binary operator.
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00001327Instruction *InstCombiner::OptAndOp(Instruction *Op,
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00001328 ConstantInt *OpRHS,
1329 ConstantInt *AndRHS,
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00001330 BinaryOperator &TheAnd) {
1331 Value *X = Op->getOperand(0);
Chris Lattner76f7fe22004-01-12 19:47:05 +00001332 Constant *Together = 0;
Reid Spencer832254e2007-02-02 02:16:23 +00001333 if (!Op->isShift())
Owen Andersonbaf3c402009-07-29 18:55:55 +00001334 Together = ConstantExpr::getAnd(AndRHS, OpRHS);
Chris Lattner7c4049c2004-01-12 19:35:11 +00001335
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00001336 switch (Op->getOpcode()) {
1337 case Instruction::Xor:
Chris Lattner6e7ba452005-01-01 16:22:27 +00001338 if (Op->hasOneUse()) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00001339 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
Chris Lattner74381062009-08-30 07:44:24 +00001340 Value *And = Builder->CreateAnd(X, AndRHS);
Chris Lattner6934a042007-02-11 01:23:03 +00001341 And->takeName(Op);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001342 return BinaryOperator::CreateXor(And, Together);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00001343 }
1344 break;
1345 case Instruction::Or:
Chris Lattner6e7ba452005-01-01 16:22:27 +00001346 if (Together == AndRHS) // (X | C) & C --> C
1347 return ReplaceInstUsesWith(TheAnd, AndRHS);
Misha Brukmanfd939082005-04-21 23:48:37 +00001348
Chris Lattner6e7ba452005-01-01 16:22:27 +00001349 if (Op->hasOneUse() && Together != OpRHS) {
1350 // (X | C1) & C2 --> (X | (C1&C2)) & C2
Chris Lattner74381062009-08-30 07:44:24 +00001351 Value *Or = Builder->CreateOr(X, Together);
Chris Lattner6934a042007-02-11 01:23:03 +00001352 Or->takeName(Op);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001353 return BinaryOperator::CreateAnd(Or, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00001354 }
1355 break;
1356 case Instruction::Add:
Chris Lattnerfd059242003-10-15 16:48:29 +00001357 if (Op->hasOneUse()) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00001358 // Adding a one to a single bit bit-field should be turned into an XOR
1359 // of the bit. First thing to check is to see if this AND is with a
1360 // single bit constant.
Chris Lattnerc6334b92010-01-05 06:03:12 +00001361 const APInt &AndRHSV = cast<ConstantInt>(AndRHS)->getValue();
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00001362
Chris Lattnerc6334b92010-01-05 06:03:12 +00001363 // If there is only one bit set.
1364 if (AndRHSV.isPowerOf2()) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00001365 // Ok, at this point, we know that we are masking the result of the
1366 // ADD down to exactly one bit. If the constant we are adding has
1367 // no bits set below this bit, then we can eliminate the ADD.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00001368 const APInt& AddRHS = cast<ConstantInt>(OpRHS)->getValue();
Misha Brukmanfd939082005-04-21 23:48:37 +00001369
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00001370 // Check to see if any bits below the one bit set in AndRHSV are set.
1371 if ((AddRHS & (AndRHSV-1)) == 0) {
1372 // If not, the only thing that can effect the output of the AND is
1373 // the bit specified by AndRHSV. If that bit is set, the effect of
1374 // the XOR is to toggle the bit. If it is clear, then the ADD has
1375 // no effect.
1376 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
1377 TheAnd.setOperand(0, X);
1378 return &TheAnd;
1379 } else {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00001380 // Pull the XOR out of the AND.
Chris Lattner74381062009-08-30 07:44:24 +00001381 Value *NewAnd = Builder->CreateAnd(X, AndRHS);
Chris Lattner6934a042007-02-11 01:23:03 +00001382 NewAnd->takeName(Op);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001383 return BinaryOperator::CreateXor(NewAnd, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00001384 }
1385 }
1386 }
1387 }
1388 break;
Chris Lattner62a355c2003-09-19 19:05:02 +00001389
1390 case Instruction::Shl: {
1391 // We know that the AND will not produce any of the bits shifted in, so if
1392 // the anded constant includes them, clear them now!
1393 //
Zhou Sheng290bec52007-03-29 08:15:12 +00001394 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00001395 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +00001396 APInt ShlMask(APInt::getHighBitsSet(BitWidth, BitWidth-OpRHSVal));
Chris Lattner4de84762010-01-04 07:02:48 +00001397 ConstantInt *CI = ConstantInt::get(AndRHS->getContext(),
1398 AndRHS->getValue() & ShlMask);
Misha Brukmanfd939082005-04-21 23:48:37 +00001399
Zhou Sheng290bec52007-03-29 08:15:12 +00001400 if (CI->getValue() == ShlMask) {
1401 // Masking out bits that the shift already masks
Chris Lattner0c967662004-09-24 15:21:34 +00001402 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
1403 } else if (CI != AndRHS) { // Reducing bits set in and.
Chris Lattner62a355c2003-09-19 19:05:02 +00001404 TheAnd.setOperand(1, CI);
1405 return &TheAnd;
1406 }
1407 break;
Misha Brukmanfd939082005-04-21 23:48:37 +00001408 }
Chris Lattner4de84762010-01-04 07:02:48 +00001409 case Instruction::LShr: {
Chris Lattner62a355c2003-09-19 19:05:02 +00001410 // We know that the AND will not produce any of the bits shifted in, so if
1411 // the anded constant includes them, clear them now! This only applies to
1412 // unsigned shifts, because a signed shr may bring in set bits!
1413 //
Zhou Sheng290bec52007-03-29 08:15:12 +00001414 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00001415 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +00001416 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
Chris Lattner4de84762010-01-04 07:02:48 +00001417 ConstantInt *CI = ConstantInt::get(Op->getContext(),
1418 AndRHS->getValue() & ShrMask);
Chris Lattner0c967662004-09-24 15:21:34 +00001419
Zhou Sheng290bec52007-03-29 08:15:12 +00001420 if (CI->getValue() == ShrMask) {
1421 // Masking out bits that the shift already masks.
Reid Spencer3822ff52006-11-08 06:47:33 +00001422 return ReplaceInstUsesWith(TheAnd, Op);
1423 } else if (CI != AndRHS) {
1424 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
1425 return &TheAnd;
1426 }
1427 break;
1428 }
1429 case Instruction::AShr:
1430 // Signed shr.
1431 // See if this is shifting in some sign extension, then masking it out
1432 // with an and.
1433 if (Op->hasOneUse()) {
Zhou Sheng290bec52007-03-29 08:15:12 +00001434 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00001435 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +00001436 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
Chris Lattner4de84762010-01-04 07:02:48 +00001437 Constant *C = ConstantInt::get(Op->getContext(),
1438 AndRHS->getValue() & ShrMask);
Reid Spencer7eb76382006-12-13 17:19:09 +00001439 if (C == AndRHS) { // Masking out bits shifted in.
Reid Spencer17212df2006-12-12 09:18:51 +00001440 // (Val ashr C1) & C2 -> (Val lshr C1) & C2
Reid Spencer3822ff52006-11-08 06:47:33 +00001441 // Make the argument unsigned.
1442 Value *ShVal = Op->getOperand(0);
Chris Lattner74381062009-08-30 07:44:24 +00001443 ShVal = Builder->CreateLShr(ShVal, OpRHS, Op->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001444 return BinaryOperator::CreateAnd(ShVal, AndRHS, TheAnd.getName());
Chris Lattner0c967662004-09-24 15:21:34 +00001445 }
Chris Lattner62a355c2003-09-19 19:05:02 +00001446 }
1447 break;
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00001448 }
1449 return 0;
1450}
1451
Chris Lattner8b170942002-08-09 23:47:40 +00001452
Chris Lattnera96879a2004-09-29 17:40:11 +00001453/// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
1454/// true, otherwise (V < Lo || V >= Hi). In pratice, we emit the more efficient
Reid Spencere4d87aa2006-12-23 06:05:41 +00001455/// (V-Lo) <u Hi-Lo. This method expects that Lo <= Hi. isSigned indicates
1456/// whether to treat the V, Lo and HI as signed or not. IB is the location to
Chris Lattnera96879a2004-09-29 17:40:11 +00001457/// insert new instructions.
1458Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
Reid Spencere4d87aa2006-12-23 06:05:41 +00001459 bool isSigned, bool Inside,
1460 Instruction &IB) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00001461 assert(cast<ConstantInt>(ConstantExpr::getICmp((isSigned ?
Reid Spencer579dca12007-01-12 04:24:46 +00001462 ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
Chris Lattnera96879a2004-09-29 17:40:11 +00001463 "Lo is not <= Hi in range emission code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00001464
Chris Lattnera96879a2004-09-29 17:40:11 +00001465 if (Inside) {
1466 if (Lo == Hi) // Trivially false.
Dan Gohman1c8a23c2009-08-25 23:17:54 +00001467 return new ICmpInst(ICmpInst::ICMP_NE, V, V);
Misha Brukmanfd939082005-04-21 23:48:37 +00001468
Reid Spencere4d87aa2006-12-23 06:05:41 +00001469 // V >= Min && V < Hi --> V < Hi
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00001470 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
Reid Spencere4e40032007-03-21 23:19:50 +00001471 ICmpInst::Predicate pred = (isSigned ?
Reid Spencere4d87aa2006-12-23 06:05:41 +00001472 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00001473 return new ICmpInst(pred, V, Hi);
Reid Spencere4d87aa2006-12-23 06:05:41 +00001474 }
1475
1476 // Emit V-Lo <u Hi-Lo
Owen Andersonbaf3c402009-07-29 18:55:55 +00001477 Constant *NegLo = ConstantExpr::getNeg(Lo);
Chris Lattner74381062009-08-30 07:44:24 +00001478 Value *Add = Builder->CreateAdd(V, NegLo, V->getName()+".off");
Owen Andersonbaf3c402009-07-29 18:55:55 +00001479 Constant *UpperBound = ConstantExpr::getAdd(NegLo, Hi);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00001480 return new ICmpInst(ICmpInst::ICMP_ULT, Add, UpperBound);
Chris Lattnera96879a2004-09-29 17:40:11 +00001481 }
1482
1483 if (Lo == Hi) // Trivially true.
Dan Gohman1c8a23c2009-08-25 23:17:54 +00001484 return new ICmpInst(ICmpInst::ICMP_EQ, V, V);
Chris Lattnera96879a2004-09-29 17:40:11 +00001485
Reid Spencere4e40032007-03-21 23:19:50 +00001486 // V < Min || V >= Hi -> V > Hi-1
Dan Gohman186a6362009-08-12 16:04:34 +00001487 Hi = SubOne(cast<ConstantInt>(Hi));
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00001488 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00001489 ICmpInst::Predicate pred = (isSigned ?
1490 ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00001491 return new ICmpInst(pred, V, Hi);
Reid Spencere4d87aa2006-12-23 06:05:41 +00001492 }
Reid Spencerb83eb642006-10-20 07:07:24 +00001493
Reid Spencere4e40032007-03-21 23:19:50 +00001494 // Emit V-Lo >u Hi-1-Lo
1495 // Note that Hi has already had one subtracted from it, above.
Owen Andersonbaf3c402009-07-29 18:55:55 +00001496 ConstantInt *NegLo = cast<ConstantInt>(ConstantExpr::getNeg(Lo));
Chris Lattner74381062009-08-30 07:44:24 +00001497 Value *Add = Builder->CreateAdd(V, NegLo, V->getName()+".off");
Owen Andersonbaf3c402009-07-29 18:55:55 +00001498 Constant *LowerBound = ConstantExpr::getAdd(NegLo, Hi);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00001499 return new ICmpInst(ICmpInst::ICMP_UGT, Add, LowerBound);
Chris Lattnera96879a2004-09-29 17:40:11 +00001500}
1501
Chris Lattner7203e152005-09-18 07:22:02 +00001502// isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
1503// any number of 0s on either side. The 1s are allowed to wrap from LSB to
1504// MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs. 0x0F0F0000 is
1505// not, since all 1s are not contiguous.
Zhou Sheng4351c642007-04-02 08:20:41 +00001506static bool isRunOfOnes(ConstantInt *Val, uint32_t &MB, uint32_t &ME) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00001507 const APInt& V = Val->getValue();
Reid Spencerf2442522007-03-24 00:42:08 +00001508 uint32_t BitWidth = Val->getType()->getBitWidth();
1509 if (!APIntOps::isShiftedMask(BitWidth, V)) return false;
Chris Lattner7203e152005-09-18 07:22:02 +00001510
1511 // look for the first zero bit after the run of ones
Reid Spencerf2442522007-03-24 00:42:08 +00001512 MB = BitWidth - ((V - 1) ^ V).countLeadingZeros();
Chris Lattner7203e152005-09-18 07:22:02 +00001513 // look for the first non-zero bit
Reid Spencerf2442522007-03-24 00:42:08 +00001514 ME = V.getActiveBits();
Chris Lattner7203e152005-09-18 07:22:02 +00001515 return true;
1516}
1517
Chris Lattner7203e152005-09-18 07:22:02 +00001518/// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
1519/// where isSub determines whether the operator is a sub. If we can fold one of
1520/// the following xforms:
Chris Lattnerc8e77562005-09-18 04:24:45 +00001521///
1522/// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
1523/// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
1524/// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
1525///
1526/// return (A +/- B).
1527///
1528Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00001529 ConstantInt *Mask, bool isSub,
Chris Lattnerc8e77562005-09-18 04:24:45 +00001530 Instruction &I) {
1531 Instruction *LHSI = dyn_cast<Instruction>(LHS);
1532 if (!LHSI || LHSI->getNumOperands() != 2 ||
1533 !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
1534
1535 ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
1536
1537 switch (LHSI->getOpcode()) {
1538 default: return 0;
1539 case Instruction::And:
Owen Andersonbaf3c402009-07-29 18:55:55 +00001540 if (ConstantExpr::getAnd(N, Mask) == Mask) {
Chris Lattner7203e152005-09-18 07:22:02 +00001541 // If the AndRHS is a power of two minus one (0+1+), this is simple.
Zhou Sheng00f436c2007-03-24 15:34:37 +00001542 if ((Mask->getValue().countLeadingZeros() +
1543 Mask->getValue().countPopulation()) ==
1544 Mask->getValue().getBitWidth())
Chris Lattner7203e152005-09-18 07:22:02 +00001545 break;
1546
1547 // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
1548 // part, we don't need any explicit masks to take them out of A. If that
1549 // is all N is, ignore it.
Zhou Sheng4351c642007-04-02 08:20:41 +00001550 uint32_t MB = 0, ME = 0;
Chris Lattner7203e152005-09-18 07:22:02 +00001551 if (isRunOfOnes(Mask, MB, ME)) { // begin/end bit of run, inclusive
Reid Spencerb35ae032007-03-23 18:46:34 +00001552 uint32_t BitWidth = cast<IntegerType>(RHS->getType())->getBitWidth();
Zhou Sheng290bec52007-03-29 08:15:12 +00001553 APInt Mask(APInt::getLowBitsSet(BitWidth, MB-1));
Chris Lattner3bedbd92006-02-07 07:27:52 +00001554 if (MaskedValueIsZero(RHS, Mask))
Chris Lattner7203e152005-09-18 07:22:02 +00001555 break;
1556 }
1557 }
Chris Lattnerc8e77562005-09-18 04:24:45 +00001558 return 0;
1559 case Instruction::Or:
1560 case Instruction::Xor:
Chris Lattner7203e152005-09-18 07:22:02 +00001561 // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
Zhou Sheng00f436c2007-03-24 15:34:37 +00001562 if ((Mask->getValue().countLeadingZeros() +
1563 Mask->getValue().countPopulation()) == Mask->getValue().getBitWidth()
Owen Andersonbaf3c402009-07-29 18:55:55 +00001564 && ConstantExpr::getAnd(N, Mask)->isNullValue())
Chris Lattnerc8e77562005-09-18 04:24:45 +00001565 break;
1566 return 0;
1567 }
1568
Chris Lattnerc8e77562005-09-18 04:24:45 +00001569 if (isSub)
Chris Lattner74381062009-08-30 07:44:24 +00001570 return Builder->CreateSub(LHSI->getOperand(0), RHS, "fold");
1571 return Builder->CreateAdd(LHSI->getOperand(0), RHS, "fold");
Chris Lattnerc8e77562005-09-18 04:24:45 +00001572}
1573
Chris Lattner29cd5ba2008-11-16 05:06:21 +00001574/// FoldAndOfICmps - Fold (icmp)&(icmp) if possible.
1575Instruction *InstCombiner::FoldAndOfICmps(Instruction &I,
1576 ICmpInst *LHS, ICmpInst *RHS) {
Chris Lattnera317e042010-01-05 06:59:49 +00001577 ICmpInst::Predicate LHSCC = LHS->getPredicate(), RHSCC = RHS->getPredicate();
1578
1579 // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
1580 if (PredicatesFoldable(LHSCC, RHSCC)) {
1581 if (LHS->getOperand(0) == RHS->getOperand(1) &&
1582 LHS->getOperand(1) == RHS->getOperand(0))
1583 LHS->swapOperands();
1584 if (LHS->getOperand(0) == RHS->getOperand(0) &&
1585 LHS->getOperand(1) == RHS->getOperand(1)) {
1586 Value *Op0 = LHS->getOperand(0), *Op1 = LHS->getOperand(1);
1587 unsigned Code = getICmpCode(LHS) & getICmpCode(RHS);
1588 bool isSigned = LHS->isSigned() || RHS->isSigned();
1589 Value *RV = getICmpValue(isSigned, Code, Op0, Op1);
1590 if (Instruction *I = dyn_cast<Instruction>(RV))
1591 return I;
1592 // Otherwise, it's a constant boolean value.
1593 return ReplaceInstUsesWith(I, RV);
1594 }
1595 }
Chris Lattner29cd5ba2008-11-16 05:06:21 +00001596
Chris Lattnerea065fb2008-11-16 05:10:52 +00001597 // This only handles icmp of constants: (icmp1 A, C1) & (icmp2 B, C2).
Chris Lattnera317e042010-01-05 06:59:49 +00001598 Value *Val = LHS->getOperand(0), *Val2 = RHS->getOperand(0);
1599 ConstantInt *LHSCst = dyn_cast<ConstantInt>(LHS->getOperand(1));
1600 ConstantInt *RHSCst = dyn_cast<ConstantInt>(RHS->getOperand(1));
1601 if (LHSCst == 0 || RHSCst == 0) return 0;
Chris Lattnerea065fb2008-11-16 05:10:52 +00001602
Chris Lattner3f40e232009-11-29 00:51:17 +00001603 if (LHSCst == RHSCst && LHSCC == RHSCC) {
1604 // (icmp ult A, C) & (icmp ult B, C) --> (icmp ult (A|B), C)
1605 // where C is a power of 2
1606 if (LHSCC == ICmpInst::ICMP_ULT &&
1607 LHSCst->getValue().isPowerOf2()) {
1608 Value *NewOr = Builder->CreateOr(Val, Val2);
1609 return new ICmpInst(LHSCC, NewOr, LHSCst);
1610 }
1611
1612 // (icmp eq A, 0) & (icmp eq B, 0) --> (icmp eq (A|B), 0)
1613 if (LHSCC == ICmpInst::ICMP_EQ && LHSCst->isZero()) {
1614 Value *NewOr = Builder->CreateOr(Val, Val2);
1615 return new ICmpInst(LHSCC, NewOr, LHSCst);
1616 }
Chris Lattnerea065fb2008-11-16 05:10:52 +00001617 }
1618
1619 // From here on, we only handle:
1620 // (icmp1 A, C1) & (icmp2 A, C2) --> something simpler.
1621 if (Val != Val2) return 0;
1622
Chris Lattner29cd5ba2008-11-16 05:06:21 +00001623 // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
1624 if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
1625 RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
1626 LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
1627 RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
1628 return 0;
1629
1630 // We can't fold (ugt x, C) & (sgt x, C2).
1631 if (!PredicatesFoldable(LHSCC, RHSCC))
1632 return 0;
1633
1634 // Ensure that the larger constant is on the RHS.
Chris Lattneraa3e1572008-11-16 05:14:43 +00001635 bool ShouldSwap;
Nick Lewycky4a134af2009-10-25 05:20:17 +00001636 if (CmpInst::isSigned(LHSCC) ||
Chris Lattner29cd5ba2008-11-16 05:06:21 +00001637 (ICmpInst::isEquality(LHSCC) &&
Nick Lewycky4a134af2009-10-25 05:20:17 +00001638 CmpInst::isSigned(RHSCC)))
Chris Lattneraa3e1572008-11-16 05:14:43 +00001639 ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
Chris Lattner29cd5ba2008-11-16 05:06:21 +00001640 else
Chris Lattneraa3e1572008-11-16 05:14:43 +00001641 ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
1642
1643 if (ShouldSwap) {
Chris Lattner29cd5ba2008-11-16 05:06:21 +00001644 std::swap(LHS, RHS);
1645 std::swap(LHSCst, RHSCst);
1646 std::swap(LHSCC, RHSCC);
1647 }
1648
1649 // At this point, we know we have have two icmp instructions
1650 // comparing a value against two constants and and'ing the result
1651 // together. Because of the above check, we know that we only have
1652 // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know
Chris Lattnera317e042010-01-05 06:59:49 +00001653 // (from the icmp folding check above), that the two constants
Chris Lattner29cd5ba2008-11-16 05:06:21 +00001654 // are not equal and that the larger constant is on the RHS
1655 assert(LHSCst != RHSCst && "Compares not folded above?");
1656
1657 switch (LHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00001658 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00001659 case ICmpInst::ICMP_EQ:
1660 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00001661 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00001662 case ICmpInst::ICMP_EQ: // (X == 13 & X == 15) -> false
1663 case ICmpInst::ICMP_UGT: // (X == 13 & X > 15) -> false
1664 case ICmpInst::ICMP_SGT: // (X == 13 & X > 15) -> false
Chris Lattner4de84762010-01-04 07:02:48 +00001665 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getContext()));
Chris Lattner29cd5ba2008-11-16 05:06:21 +00001666 case ICmpInst::ICMP_NE: // (X == 13 & X != 15) -> X == 13
1667 case ICmpInst::ICMP_ULT: // (X == 13 & X < 15) -> X == 13
1668 case ICmpInst::ICMP_SLT: // (X == 13 & X < 15) -> X == 13
1669 return ReplaceInstUsesWith(I, LHS);
1670 }
1671 case ICmpInst::ICMP_NE:
1672 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00001673 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00001674 case ICmpInst::ICMP_ULT:
Dan Gohman186a6362009-08-12 16:04:34 +00001675 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X u< 14) -> X < 13
Dan Gohman1c8a23c2009-08-25 23:17:54 +00001676 return new ICmpInst(ICmpInst::ICMP_ULT, Val, LHSCst);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00001677 break; // (X != 13 & X u< 15) -> no change
1678 case ICmpInst::ICMP_SLT:
Dan Gohman186a6362009-08-12 16:04:34 +00001679 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X s< 14) -> X < 13
Dan Gohman1c8a23c2009-08-25 23:17:54 +00001680 return new ICmpInst(ICmpInst::ICMP_SLT, Val, LHSCst);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00001681 break; // (X != 13 & X s< 15) -> no change
1682 case ICmpInst::ICMP_EQ: // (X != 13 & X == 15) -> X == 15
1683 case ICmpInst::ICMP_UGT: // (X != 13 & X u> 15) -> X u> 15
1684 case ICmpInst::ICMP_SGT: // (X != 13 & X s> 15) -> X s> 15
1685 return ReplaceInstUsesWith(I, RHS);
1686 case ICmpInst::ICMP_NE:
Dan Gohman186a6362009-08-12 16:04:34 +00001687 if (LHSCst == SubOne(RHSCst)){// (X != 13 & X != 14) -> X-13 >u 1
Owen Andersonbaf3c402009-07-29 18:55:55 +00001688 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
Chris Lattner74381062009-08-30 07:44:24 +00001689 Value *Add = Builder->CreateAdd(Val, AddCST, Val->getName()+".off");
Dan Gohman1c8a23c2009-08-25 23:17:54 +00001690 return new ICmpInst(ICmpInst::ICMP_UGT, Add,
Owen Andersoneed707b2009-07-24 23:12:02 +00001691 ConstantInt::get(Add->getType(), 1));
Chris Lattner29cd5ba2008-11-16 05:06:21 +00001692 }
1693 break; // (X != 13 & X != 15) -> no change
1694 }
1695 break;
1696 case ICmpInst::ICMP_ULT:
1697 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00001698 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00001699 case ICmpInst::ICMP_EQ: // (X u< 13 & X == 15) -> false
1700 case ICmpInst::ICMP_UGT: // (X u< 13 & X u> 15) -> false
Chris Lattner4de84762010-01-04 07:02:48 +00001701 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getContext()));
Chris Lattner29cd5ba2008-11-16 05:06:21 +00001702 case ICmpInst::ICMP_SGT: // (X u< 13 & X s> 15) -> no change
1703 break;
1704 case ICmpInst::ICMP_NE: // (X u< 13 & X != 15) -> X u< 13
1705 case ICmpInst::ICMP_ULT: // (X u< 13 & X u< 15) -> X u< 13
1706 return ReplaceInstUsesWith(I, LHS);
1707 case ICmpInst::ICMP_SLT: // (X u< 13 & X s< 15) -> no change
1708 break;
1709 }
1710 break;
1711 case ICmpInst::ICMP_SLT:
1712 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00001713 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00001714 case ICmpInst::ICMP_EQ: // (X s< 13 & X == 15) -> false
1715 case ICmpInst::ICMP_SGT: // (X s< 13 & X s> 15) -> false
Chris Lattner4de84762010-01-04 07:02:48 +00001716 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getContext()));
Chris Lattner29cd5ba2008-11-16 05:06:21 +00001717 case ICmpInst::ICMP_UGT: // (X s< 13 & X u> 15) -> no change
1718 break;
1719 case ICmpInst::ICMP_NE: // (X s< 13 & X != 15) -> X < 13
1720 case ICmpInst::ICMP_SLT: // (X s< 13 & X s< 15) -> X < 13
1721 return ReplaceInstUsesWith(I, LHS);
1722 case ICmpInst::ICMP_ULT: // (X s< 13 & X u< 15) -> no change
1723 break;
1724 }
1725 break;
1726 case ICmpInst::ICMP_UGT:
1727 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00001728 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00001729 case ICmpInst::ICMP_EQ: // (X u> 13 & X == 15) -> X == 15
1730 case ICmpInst::ICMP_UGT: // (X u> 13 & X u> 15) -> X u> 15
1731 return ReplaceInstUsesWith(I, RHS);
1732 case ICmpInst::ICMP_SGT: // (X u> 13 & X s> 15) -> no change
1733 break;
1734 case ICmpInst::ICMP_NE:
Dan Gohman186a6362009-08-12 16:04:34 +00001735 if (RHSCst == AddOne(LHSCst)) // (X u> 13 & X != 14) -> X u> 14
Dan Gohman1c8a23c2009-08-25 23:17:54 +00001736 return new ICmpInst(LHSCC, Val, RHSCst);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00001737 break; // (X u> 13 & X != 15) -> no change
Chris Lattner69d4ced2008-11-16 05:20:07 +00001738 case ICmpInst::ICMP_ULT: // (X u> 13 & X u< 15) -> (X-14) <u 1
Dan Gohman186a6362009-08-12 16:04:34 +00001739 return InsertRangeTest(Val, AddOne(LHSCst),
Owen Andersond672ecb2009-07-03 00:17:18 +00001740 RHSCst, false, true, I);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00001741 case ICmpInst::ICMP_SLT: // (X u> 13 & X s< 15) -> no change
1742 break;
1743 }
1744 break;
1745 case ICmpInst::ICMP_SGT:
1746 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00001747 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00001748 case ICmpInst::ICMP_EQ: // (X s> 13 & X == 15) -> X == 15
1749 case ICmpInst::ICMP_SGT: // (X s> 13 & X s> 15) -> X s> 15
1750 return ReplaceInstUsesWith(I, RHS);
1751 case ICmpInst::ICMP_UGT: // (X s> 13 & X u> 15) -> no change
1752 break;
1753 case ICmpInst::ICMP_NE:
Dan Gohman186a6362009-08-12 16:04:34 +00001754 if (RHSCst == AddOne(LHSCst)) // (X s> 13 & X != 14) -> X s> 14
Dan Gohman1c8a23c2009-08-25 23:17:54 +00001755 return new ICmpInst(LHSCC, Val, RHSCst);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00001756 break; // (X s> 13 & X != 15) -> no change
Chris Lattner69d4ced2008-11-16 05:20:07 +00001757 case ICmpInst::ICMP_SLT: // (X s> 13 & X s< 15) -> (X-14) s< 1
Dan Gohman186a6362009-08-12 16:04:34 +00001758 return InsertRangeTest(Val, AddOne(LHSCst),
Owen Andersond672ecb2009-07-03 00:17:18 +00001759 RHSCst, true, true, I);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00001760 case ICmpInst::ICMP_ULT: // (X s> 13 & X u< 15) -> no change
1761 break;
1762 }
1763 break;
1764 }
Chris Lattner29cd5ba2008-11-16 05:06:21 +00001765
1766 return 0;
1767}
1768
Chris Lattner42d1be02009-07-23 05:14:02 +00001769Instruction *InstCombiner::FoldAndOfFCmps(Instruction &I, FCmpInst *LHS,
1770 FCmpInst *RHS) {
1771
1772 if (LHS->getPredicate() == FCmpInst::FCMP_ORD &&
1773 RHS->getPredicate() == FCmpInst::FCMP_ORD) {
1774 // (fcmp ord x, c) & (fcmp ord y, c) -> (fcmp ord x, y)
1775 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
1776 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
1777 // If either of the constants are nans, then the whole thing returns
1778 // false.
1779 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Chris Lattner4de84762010-01-04 07:02:48 +00001780 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getContext()));
Dan Gohman1c8a23c2009-08-25 23:17:54 +00001781 return new FCmpInst(FCmpInst::FCMP_ORD,
Chris Lattner42d1be02009-07-23 05:14:02 +00001782 LHS->getOperand(0), RHS->getOperand(0));
1783 }
Chris Lattnerf98d2532009-07-23 05:32:17 +00001784
1785 // Handle vector zeros. This occurs because the canonical form of
1786 // "fcmp ord x,x" is "fcmp ord x, 0".
1787 if (isa<ConstantAggregateZero>(LHS->getOperand(1)) &&
1788 isa<ConstantAggregateZero>(RHS->getOperand(1)))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00001789 return new FCmpInst(FCmpInst::FCMP_ORD,
Chris Lattnerf98d2532009-07-23 05:32:17 +00001790 LHS->getOperand(0), RHS->getOperand(0));
Chris Lattner42d1be02009-07-23 05:14:02 +00001791 return 0;
1792 }
1793
1794 Value *Op0LHS = LHS->getOperand(0), *Op0RHS = LHS->getOperand(1);
1795 Value *Op1LHS = RHS->getOperand(0), *Op1RHS = RHS->getOperand(1);
1796 FCmpInst::Predicate Op0CC = LHS->getPredicate(), Op1CC = RHS->getPredicate();
1797
1798
1799 if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
1800 // Swap RHS operands to match LHS.
1801 Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
1802 std::swap(Op1LHS, Op1RHS);
1803 }
1804
1805 if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
1806 // Simplify (fcmp cc0 x, y) & (fcmp cc1 x, y).
1807 if (Op0CC == Op1CC)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00001808 return new FCmpInst((FCmpInst::Predicate)Op0CC, Op0LHS, Op0RHS);
Chris Lattner42d1be02009-07-23 05:14:02 +00001809
1810 if (Op0CC == FCmpInst::FCMP_FALSE || Op1CC == FCmpInst::FCMP_FALSE)
Chris Lattner4de84762010-01-04 07:02:48 +00001811 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getContext()));
Chris Lattner42d1be02009-07-23 05:14:02 +00001812 if (Op0CC == FCmpInst::FCMP_TRUE)
1813 return ReplaceInstUsesWith(I, RHS);
1814 if (Op1CC == FCmpInst::FCMP_TRUE)
1815 return ReplaceInstUsesWith(I, LHS);
1816
1817 bool Op0Ordered;
1818 bool Op1Ordered;
1819 unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
1820 unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
1821 if (Op1Pred == 0) {
1822 std::swap(LHS, RHS);
1823 std::swap(Op0Pred, Op1Pred);
1824 std::swap(Op0Ordered, Op1Ordered);
1825 }
1826 if (Op0Pred == 0) {
1827 // uno && ueq -> uno && (uno || eq) -> ueq
1828 // ord && olt -> ord && (ord && lt) -> olt
1829 if (Op0Ordered == Op1Ordered)
1830 return ReplaceInstUsesWith(I, RHS);
1831
1832 // uno && oeq -> uno && (ord && eq) -> false
1833 // uno && ord -> false
1834 if (!Op0Ordered)
Chris Lattner4de84762010-01-04 07:02:48 +00001835 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getContext()));
Chris Lattner42d1be02009-07-23 05:14:02 +00001836 // ord && ueq -> ord && (uno || eq) -> oeq
Chris Lattner4de84762010-01-04 07:02:48 +00001837 return cast<Instruction>(getFCmpValue(true, Op1Pred, Op0LHS, Op0RHS));
Chris Lattner42d1be02009-07-23 05:14:02 +00001838 }
1839 }
1840
1841 return 0;
1842}
1843
Chris Lattner29cd5ba2008-11-16 05:06:21 +00001844
Chris Lattner7e708292002-06-25 16:13:24 +00001845Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00001846 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00001847 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00001848
Chris Lattnerd06094f2009-11-10 00:55:12 +00001849 if (Value *V = SimplifyAndInst(Op0, Op1, TD))
1850 return ReplaceInstUsesWith(I, V);
Chris Lattner3f5b8772002-05-06 16:14:14 +00001851
Chris Lattnerf8c36f52006-02-12 08:02:11 +00001852 // See if we can simplify any instructions used by the instruction whose sole
Chris Lattner9ca96412006-02-08 03:25:32 +00001853 // purpose is to compute bits we don't care about.
Dan Gohman6de29f82009-06-15 22:12:54 +00001854 if (SimplifyDemandedInstructionBits(I))
Nick Lewycky546d6312010-01-02 15:25:44 +00001855 return &I;
Dan Gohman6de29f82009-06-15 22:12:54 +00001856
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00001857 if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner7acdf1d2009-10-11 22:00:32 +00001858 const APInt &AndRHSMask = AndRHS->getValue();
Zhou Sheng3a507fd2007-04-01 17:13:37 +00001859 APInt NotAndRHS(~AndRHSMask);
Chris Lattner6e7ba452005-01-01 16:22:27 +00001860
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00001861 // Optimize a variety of ((val OP C1) & C2) combinations...
Chris Lattner7acdf1d2009-10-11 22:00:32 +00001862 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Chris Lattner6e7ba452005-01-01 16:22:27 +00001863 Value *Op0LHS = Op0I->getOperand(0);
1864 Value *Op0RHS = Op0I->getOperand(1);
1865 switch (Op0I->getOpcode()) {
Chris Lattner7acdf1d2009-10-11 22:00:32 +00001866 default: break;
Chris Lattner6e7ba452005-01-01 16:22:27 +00001867 case Instruction::Xor:
1868 case Instruction::Or:
Chris Lattnerad1e3022005-01-23 20:26:55 +00001869 // If the mask is only needed on one incoming arm, push it up.
Chris Lattner7acdf1d2009-10-11 22:00:32 +00001870 if (!Op0I->hasOneUse()) break;
1871
1872 if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
1873 // Not masking anything out for the LHS, move to RHS.
1874 Value *NewRHS = Builder->CreateAnd(Op0RHS, AndRHS,
1875 Op0RHS->getName()+".masked");
1876 return BinaryOperator::Create(Op0I->getOpcode(), Op0LHS, NewRHS);
1877 }
1878 if (!isa<Constant>(Op0RHS) &&
1879 MaskedValueIsZero(Op0RHS, NotAndRHS)) {
1880 // Not masking anything out for the RHS, move to LHS.
1881 Value *NewLHS = Builder->CreateAnd(Op0LHS, AndRHS,
1882 Op0LHS->getName()+".masked");
1883 return BinaryOperator::Create(Op0I->getOpcode(), NewLHS, Op0RHS);
Chris Lattnerad1e3022005-01-23 20:26:55 +00001884 }
1885
Chris Lattner6e7ba452005-01-01 16:22:27 +00001886 break;
Chris Lattnerc8e77562005-09-18 04:24:45 +00001887 case Instruction::Add:
Chris Lattner7203e152005-09-18 07:22:02 +00001888 // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
1889 // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
1890 // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
1891 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001892 return BinaryOperator::CreateAnd(V, AndRHS);
Chris Lattner7203e152005-09-18 07:22:02 +00001893 if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001894 return BinaryOperator::CreateAnd(V, AndRHS); // Add commutes
Chris Lattnerc8e77562005-09-18 04:24:45 +00001895 break;
1896
1897 case Instruction::Sub:
Chris Lattner7203e152005-09-18 07:22:02 +00001898 // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
1899 // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
1900 // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
1901 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001902 return BinaryOperator::CreateAnd(V, AndRHS);
Nick Lewyckyb4d1bc92008-07-09 04:32:37 +00001903
Nick Lewycky5dcc41f2008-07-10 05:51:40 +00001904 // (A - N) & AndRHS -> -N & AndRHS iff A&AndRHS==0 and AndRHS
1905 // has 1's for all bits that the subtraction with A might affect.
1906 if (Op0I->hasOneUse()) {
1907 uint32_t BitWidth = AndRHSMask.getBitWidth();
1908 uint32_t Zeros = AndRHSMask.countLeadingZeros();
1909 APInt Mask = APInt::getLowBitsSet(BitWidth, BitWidth - Zeros);
1910
Nick Lewyckyb4d1bc92008-07-09 04:32:37 +00001911 ConstantInt *A = dyn_cast<ConstantInt>(Op0LHS);
Nick Lewycky5dcc41f2008-07-10 05:51:40 +00001912 if (!(A && A->isZero()) && // avoid infinite recursion.
1913 MaskedValueIsZero(Op0LHS, Mask)) {
Chris Lattner74381062009-08-30 07:44:24 +00001914 Value *NewNeg = Builder->CreateNeg(Op0RHS);
Nick Lewyckyb4d1bc92008-07-09 04:32:37 +00001915 return BinaryOperator::CreateAnd(NewNeg, AndRHS);
1916 }
1917 }
Chris Lattnerc8e77562005-09-18 04:24:45 +00001918 break;
Nick Lewyckyd1f77bf2008-07-09 05:20:13 +00001919
1920 case Instruction::Shl:
1921 case Instruction::LShr:
1922 // (1 << x) & 1 --> zext(x == 0)
1923 // (1 >> x) & 1 --> zext(x == 0)
Nick Lewyckyd8ad4922008-07-09 07:35:26 +00001924 if (AndRHSMask == 1 && Op0LHS == AndRHS) {
Chris Lattner74381062009-08-30 07:44:24 +00001925 Value *NewICmp =
1926 Builder->CreateICmpEQ(Op0RHS, Constant::getNullValue(I.getType()));
Nick Lewyckyd1f77bf2008-07-09 05:20:13 +00001927 return new ZExtInst(NewICmp, I.getType());
1928 }
1929 break;
Chris Lattner6e7ba452005-01-01 16:22:27 +00001930 }
1931
Chris Lattner58403262003-07-23 19:25:52 +00001932 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattner6e7ba452005-01-01 16:22:27 +00001933 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00001934 return Res;
Chris Lattner6e7ba452005-01-01 16:22:27 +00001935 } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
Chris Lattner2b83af22005-08-07 07:03:10 +00001936 // If this is an integer truncation or change from signed-to-unsigned, and
1937 // if the source is an and/or with immediate, transform it. This
1938 // frequently occurs for bitfield accesses.
1939 if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
Reid Spencer3da59db2006-11-27 01:05:10 +00001940 if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
Chris Lattner2b83af22005-08-07 07:03:10 +00001941 CastOp->getNumOperands() == 2)
Chris Lattner48b59ec2009-10-26 15:40:07 +00001942 if (ConstantInt *AndCI =dyn_cast<ConstantInt>(CastOp->getOperand(1))){
Chris Lattner2b83af22005-08-07 07:03:10 +00001943 if (CastOp->getOpcode() == Instruction::And) {
1944 // Change: and (cast (and X, C1) to T), C2
Reid Spencer3da59db2006-11-27 01:05:10 +00001945 // into : and (cast X to T), trunc_or_bitcast(C1)&C2
1946 // This will fold the two constants together, which may allow
1947 // other simplifications.
Chris Lattner74381062009-08-30 07:44:24 +00001948 Value *NewCast = Builder->CreateTruncOrBitCast(
Reid Spencerd977d862006-12-12 23:36:14 +00001949 CastOp->getOperand(0), I.getType(),
1950 CastOp->getName()+".shrunk");
Reid Spencer3da59db2006-11-27 01:05:10 +00001951 // trunc_or_bitcast(C1)&C2
Chris Lattner74381062009-08-30 07:44:24 +00001952 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
Owen Andersonbaf3c402009-07-29 18:55:55 +00001953 C3 = ConstantExpr::getAnd(C3, AndRHS);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001954 return BinaryOperator::CreateAnd(NewCast, C3);
Chris Lattner2b83af22005-08-07 07:03:10 +00001955 } else if (CastOp->getOpcode() == Instruction::Or) {
1956 // Change: and (cast (or X, C1) to T), C2
1957 // into : trunc(C1)&C2 iff trunc(C1)&C2 == C2
Chris Lattner74381062009-08-30 07:44:24 +00001958 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
Owen Andersonbaf3c402009-07-29 18:55:55 +00001959 if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS)
Owen Andersond672ecb2009-07-03 00:17:18 +00001960 // trunc(C1)&C2
Chris Lattner2b83af22005-08-07 07:03:10 +00001961 return ReplaceInstUsesWith(I, AndRHS);
1962 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00001963 }
Chris Lattner2b83af22005-08-07 07:03:10 +00001964 }
Chris Lattner06782f82003-07-23 19:36:21 +00001965 }
Chris Lattner2eefe512004-04-09 19:05:30 +00001966
1967 // Try to fold constant and into select arguments.
1968 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner80f43d32010-01-04 07:53:58 +00001969 if (Instruction *R = FoldOpIntoSelect(I, SI))
Chris Lattner2eefe512004-04-09 19:05:30 +00001970 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00001971 if (isa<PHINode>(Op0))
1972 if (Instruction *NV = FoldOpIntoPhi(I))
1973 return NV;
Chris Lattnerc6a8aff2003-07-23 17:57:01 +00001974 }
1975
Chris Lattner5b62aa72004-06-18 06:07:51 +00001976
Misha Brukmancb6267b2004-07-30 12:50:08 +00001977 // (~A & ~B) == (~(A | B)) - De Morgan's Law
Chris Lattnerd06094f2009-11-10 00:55:12 +00001978 if (Value *Op0NotVal = dyn_castNotVal(Op0))
1979 if (Value *Op1NotVal = dyn_castNotVal(Op1))
1980 if (Op0->hasOneUse() && Op1->hasOneUse()) {
1981 Value *Or = Builder->CreateOr(Op0NotVal, Op1NotVal,
1982 I.getName()+".demorgan");
1983 return BinaryOperator::CreateNot(Or);
1984 }
1985
Chris Lattner2082ad92006-02-13 23:07:23 +00001986 {
Chris Lattner003b6202007-06-15 05:58:24 +00001987 Value *A = 0, *B = 0, *C = 0, *D = 0;
Chris Lattnerd06094f2009-11-10 00:55:12 +00001988 // (A|B) & ~(A&B) -> A^B
1989 if (match(Op0, m_Or(m_Value(A), m_Value(B))) &&
1990 match(Op1, m_Not(m_And(m_Value(C), m_Value(D)))) &&
1991 ((A == C && B == D) || (A == D && B == C)))
1992 return BinaryOperator::CreateXor(A, B);
Chris Lattner003b6202007-06-15 05:58:24 +00001993
Chris Lattnerd06094f2009-11-10 00:55:12 +00001994 // ~(A&B) & (A|B) -> A^B
1995 if (match(Op1, m_Or(m_Value(A), m_Value(B))) &&
1996 match(Op0, m_Not(m_And(m_Value(C), m_Value(D)))) &&
1997 ((A == C && B == D) || (A == D && B == C)))
1998 return BinaryOperator::CreateXor(A, B);
Chris Lattner64daab52006-04-01 08:03:55 +00001999
2000 if (Op0->hasOneUse() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00002001 match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
Chris Lattner64daab52006-04-01 08:03:55 +00002002 if (A == Op1) { // (A^B)&A -> A&(A^B)
2003 I.swapOperands(); // Simplify below
2004 std::swap(Op0, Op1);
2005 } else if (B == Op1) { // (A^B)&B -> B&(B^A)
2006 cast<BinaryOperator>(Op0)->swapOperands();
2007 I.swapOperands(); // Simplify below
2008 std::swap(Op0, Op1);
2009 }
2010 }
Bill Wendling7f0ef6b2008-11-30 13:08:13 +00002011
Chris Lattner64daab52006-04-01 08:03:55 +00002012 if (Op1->hasOneUse() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00002013 match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
Chris Lattner64daab52006-04-01 08:03:55 +00002014 if (B == Op0) { // B&(A^B) -> B&(B^A)
2015 cast<BinaryOperator>(Op1)->swapOperands();
2016 std::swap(A, B);
2017 }
Chris Lattner74381062009-08-30 07:44:24 +00002018 if (A == Op0) // A&(A^B) -> A & ~B
2019 return BinaryOperator::CreateAnd(A, Builder->CreateNot(B, "tmp"));
Chris Lattner64daab52006-04-01 08:03:55 +00002020 }
Bill Wendling7f0ef6b2008-11-30 13:08:13 +00002021
2022 // (A&((~A)|B)) -> A&B
Dan Gohman4ae51262009-08-12 16:23:25 +00002023 if (match(Op0, m_Or(m_Not(m_Specific(Op1)), m_Value(A))) ||
2024 match(Op0, m_Or(m_Value(A), m_Not(m_Specific(Op1)))))
Chris Lattnerd8aafcb2008-12-01 05:16:26 +00002025 return BinaryOperator::CreateAnd(A, Op1);
Dan Gohman4ae51262009-08-12 16:23:25 +00002026 if (match(Op1, m_Or(m_Not(m_Specific(Op0)), m_Value(A))) ||
2027 match(Op1, m_Or(m_Value(A), m_Not(m_Specific(Op0)))))
Chris Lattnerd8aafcb2008-12-01 05:16:26 +00002028 return BinaryOperator::CreateAnd(A, Op0);
Chris Lattner2082ad92006-02-13 23:07:23 +00002029 }
2030
Chris Lattnera317e042010-01-05 06:59:49 +00002031 if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1))
Chris Lattner29cd5ba2008-11-16 05:06:21 +00002032 if (ICmpInst *LHS = dyn_cast<ICmpInst>(Op0))
2033 if (Instruction *Res = FoldAndOfICmps(I, LHS, RHS))
2034 return Res;
Chris Lattner955f3312004-09-28 21:48:02 +00002035
Chris Lattner6fc205f2006-05-05 06:39:07 +00002036 // fold (and (cast A), (cast B)) -> (cast (and A, B))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00002037 if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
2038 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
2039 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind ?
2040 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattnerf98d2532009-07-23 05:32:17 +00002041 if (SrcTy == Op1C->getOperand(0)->getType() &&
2042 SrcTy->isIntOrIntVector() &&
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00002043 // Only do this if the casts both really cause code to be generated.
Chris Lattner80f43d32010-01-04 07:53:58 +00002044 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
2045 I.getType()) &&
Reid Spencere4d87aa2006-12-23 06:05:41 +00002046 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
Chris Lattner80f43d32010-01-04 07:53:58 +00002047 I.getType())) {
Chris Lattner74381062009-08-30 07:44:24 +00002048 Value *NewOp = Builder->CreateAnd(Op0C->getOperand(0),
2049 Op1C->getOperand(0), I.getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002050 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00002051 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00002052 }
Chris Lattnere511b742006-11-14 07:46:50 +00002053
2054 // (X >> Z) & (Y >> Z) -> (X&Y) >> Z for all shifts.
Reid Spencer832254e2007-02-02 02:16:23 +00002055 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
2056 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
2057 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
Chris Lattnere511b742006-11-14 07:46:50 +00002058 SI0->getOperand(1) == SI1->getOperand(1) &&
2059 (SI0->hasOneUse() || SI1->hasOneUse())) {
Chris Lattner74381062009-08-30 07:44:24 +00002060 Value *NewOp =
2061 Builder->CreateAnd(SI0->getOperand(0), SI1->getOperand(0),
2062 SI0->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002063 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
Reid Spencer832254e2007-02-02 02:16:23 +00002064 SI1->getOperand(1));
Chris Lattnere511b742006-11-14 07:46:50 +00002065 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00002066 }
2067
Evan Cheng8db90722008-10-14 17:15:11 +00002068 // If and'ing two fcmp, try combine them into one.
Chris Lattner99c65742007-10-24 05:38:08 +00002069 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
Chris Lattner42d1be02009-07-23 05:14:02 +00002070 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
2071 if (Instruction *Res = FoldAndOfFCmps(I, LHS, RHS))
2072 return Res;
Chris Lattner99c65742007-10-24 05:38:08 +00002073 }
Nick Lewyckyb4d1bc92008-07-09 04:32:37 +00002074
Chris Lattner7e708292002-06-25 16:13:24 +00002075 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00002076}
2077
Chris Lattner8c34cd22008-10-05 02:13:19 +00002078/// CollectBSwapParts - Analyze the specified subexpression and see if it is
2079/// capable of providing pieces of a bswap. The subexpression provides pieces
2080/// of a bswap if it is proven that each of the non-zero bytes in the output of
2081/// the expression came from the corresponding "byte swapped" byte in some other
2082/// value. For example, if the current subexpression is "(shl i32 %X, 24)" then
2083/// we know that the expression deposits the low byte of %X into the high byte
2084/// of the bswap result and that all other bytes are zero. This expression is
2085/// accepted, the high byte of ByteValues is set to X to indicate a correct
2086/// match.
2087///
2088/// This function returns true if the match was unsuccessful and false if so.
2089/// On entry to the function the "OverallLeftShift" is a signed integer value
2090/// indicating the number of bytes that the subexpression is later shifted. For
2091/// example, if the expression is later right shifted by 16 bits, the
2092/// OverallLeftShift value would be -2 on entry. This is used to specify which
2093/// byte of ByteValues is actually being set.
2094///
2095/// Similarly, ByteMask is a bitmask where a bit is clear if its corresponding
2096/// byte is masked to zero by a user. For example, in (X & 255), X will be
2097/// processed with a bytemask of 1. Because bytemask is 32-bits, this limits
2098/// this function to working on up to 32-byte (256 bit) values. ByteMask is
2099/// always in the local (OverallLeftShift) coordinate space.
2100///
2101static bool CollectBSwapParts(Value *V, int OverallLeftShift, uint32_t ByteMask,
2102 SmallVector<Value*, 8> &ByteValues) {
2103 if (Instruction *I = dyn_cast<Instruction>(V)) {
2104 // If this is an or instruction, it may be an inner node of the bswap.
2105 if (I->getOpcode() == Instruction::Or) {
2106 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
2107 ByteValues) ||
2108 CollectBSwapParts(I->getOperand(1), OverallLeftShift, ByteMask,
2109 ByteValues);
Chris Lattnerafe91a52006-06-15 19:07:26 +00002110 }
Chris Lattner8c34cd22008-10-05 02:13:19 +00002111
2112 // If this is a logical shift by a constant multiple of 8, recurse with
2113 // OverallLeftShift and ByteMask adjusted.
2114 if (I->isLogicalShift() && isa<ConstantInt>(I->getOperand(1))) {
2115 unsigned ShAmt =
2116 cast<ConstantInt>(I->getOperand(1))->getLimitedValue(~0U);
2117 // Ensure the shift amount is defined and of a byte value.
2118 if ((ShAmt & 7) || (ShAmt > 8*ByteValues.size()))
2119 return true;
2120
2121 unsigned ByteShift = ShAmt >> 3;
2122 if (I->getOpcode() == Instruction::Shl) {
2123 // X << 2 -> collect(X, +2)
2124 OverallLeftShift += ByteShift;
2125 ByteMask >>= ByteShift;
2126 } else {
2127 // X >>u 2 -> collect(X, -2)
2128 OverallLeftShift -= ByteShift;
2129 ByteMask <<= ByteShift;
Chris Lattnerde17ddc2008-10-08 06:42:28 +00002130 ByteMask &= (~0U >> (32-ByteValues.size()));
Chris Lattner8c34cd22008-10-05 02:13:19 +00002131 }
2132
2133 if (OverallLeftShift >= (int)ByteValues.size()) return true;
2134 if (OverallLeftShift <= -(int)ByteValues.size()) return true;
2135
2136 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
2137 ByteValues);
2138 }
2139
2140 // If this is a logical 'and' with a mask that clears bytes, clear the
2141 // corresponding bytes in ByteMask.
2142 if (I->getOpcode() == Instruction::And &&
2143 isa<ConstantInt>(I->getOperand(1))) {
2144 // Scan every byte of the and mask, seeing if the byte is either 0 or 255.
2145 unsigned NumBytes = ByteValues.size();
2146 APInt Byte(I->getType()->getPrimitiveSizeInBits(), 255);
2147 const APInt &AndMask = cast<ConstantInt>(I->getOperand(1))->getValue();
2148
2149 for (unsigned i = 0; i != NumBytes; ++i, Byte <<= 8) {
2150 // If this byte is masked out by a later operation, we don't care what
2151 // the and mask is.
2152 if ((ByteMask & (1 << i)) == 0)
2153 continue;
2154
2155 // If the AndMask is all zeros for this byte, clear the bit.
2156 APInt MaskB = AndMask & Byte;
2157 if (MaskB == 0) {
2158 ByteMask &= ~(1U << i);
2159 continue;
2160 }
2161
2162 // If the AndMask is not all ones for this byte, it's not a bytezap.
2163 if (MaskB != Byte)
2164 return true;
2165
2166 // Otherwise, this byte is kept.
2167 }
2168
2169 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
2170 ByteValues);
2171 }
Chris Lattnerafe91a52006-06-15 19:07:26 +00002172 }
2173
Chris Lattner8c34cd22008-10-05 02:13:19 +00002174 // Okay, we got to something that isn't a shift, 'or' or 'and'. This must be
2175 // the input value to the bswap. Some observations: 1) if more than one byte
2176 // is demanded from this input, then it could not be successfully assembled
2177 // into a byteswap. At least one of the two bytes would not be aligned with
2178 // their ultimate destination.
2179 if (!isPowerOf2_32(ByteMask)) return true;
2180 unsigned InputByteNo = CountTrailingZeros_32(ByteMask);
Chris Lattnerafe91a52006-06-15 19:07:26 +00002181
Chris Lattner8c34cd22008-10-05 02:13:19 +00002182 // 2) The input and ultimate destinations must line up: if byte 3 of an i32
2183 // is demanded, it needs to go into byte 0 of the result. This means that the
2184 // byte needs to be shifted until it lands in the right byte bucket. The
2185 // shift amount depends on the position: if the byte is coming from the high
2186 // part of the value (e.g. byte 3) then it must be shifted right. If from the
2187 // low part, it must be shifted left.
2188 unsigned DestByteNo = InputByteNo + OverallLeftShift;
2189 if (InputByteNo < ByteValues.size()/2) {
2190 if (ByteValues.size()-1-DestByteNo != InputByteNo)
2191 return true;
2192 } else {
2193 if (ByteValues.size()-1-DestByteNo != InputByteNo)
2194 return true;
2195 }
Chris Lattnerafe91a52006-06-15 19:07:26 +00002196
2197 // If the destination byte value is already defined, the values are or'd
2198 // together, which isn't a bswap (unless it's an or of the same bits).
Chris Lattner8c34cd22008-10-05 02:13:19 +00002199 if (ByteValues[DestByteNo] && ByteValues[DestByteNo] != V)
Chris Lattnerafe91a52006-06-15 19:07:26 +00002200 return true;
Chris Lattner8c34cd22008-10-05 02:13:19 +00002201 ByteValues[DestByteNo] = V;
Chris Lattnerafe91a52006-06-15 19:07:26 +00002202 return false;
2203}
2204
2205/// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
2206/// If so, insert the new bswap intrinsic and return it.
2207Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
Chris Lattner55fc8c42007-04-01 20:57:36 +00002208 const IntegerType *ITy = dyn_cast<IntegerType>(I.getType());
Chris Lattner8c34cd22008-10-05 02:13:19 +00002209 if (!ITy || ITy->getBitWidth() % 16 ||
2210 // ByteMask only allows up to 32-byte values.
2211 ITy->getBitWidth() > 32*8)
Chris Lattner55fc8c42007-04-01 20:57:36 +00002212 return 0; // Can only bswap pairs of bytes. Can't do vectors.
Chris Lattnerafe91a52006-06-15 19:07:26 +00002213
2214 /// ByteValues - For each byte of the result, we keep track of which value
2215 /// defines each byte.
Chris Lattner535014f2007-02-15 22:52:10 +00002216 SmallVector<Value*, 8> ByteValues;
Chris Lattner55fc8c42007-04-01 20:57:36 +00002217 ByteValues.resize(ITy->getBitWidth()/8);
Chris Lattnerafe91a52006-06-15 19:07:26 +00002218
2219 // Try to find all the pieces corresponding to the bswap.
Chris Lattner8c34cd22008-10-05 02:13:19 +00002220 uint32_t ByteMask = ~0U >> (32-ByteValues.size());
2221 if (CollectBSwapParts(&I, 0, ByteMask, ByteValues))
Chris Lattnerafe91a52006-06-15 19:07:26 +00002222 return 0;
2223
2224 // Check to see if all of the bytes come from the same value.
2225 Value *V = ByteValues[0];
2226 if (V == 0) return 0; // Didn't find a byte? Must be zero.
2227
2228 // Check to make sure that all of the bytes come from the same value.
2229 for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
2230 if (ByteValues[i] != V)
2231 return 0;
Chandler Carruth69940402007-08-04 01:51:18 +00002232 const Type *Tys[] = { ITy };
Chris Lattnerafe91a52006-06-15 19:07:26 +00002233 Module *M = I.getParent()->getParent()->getParent();
Chandler Carruth69940402007-08-04 01:51:18 +00002234 Function *F = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 1);
Gabor Greif051a9502008-04-06 20:25:17 +00002235 return CallInst::Create(F, V);
Chris Lattnerafe91a52006-06-15 19:07:26 +00002236}
2237
Chris Lattnerfaaf9512008-11-16 04:24:12 +00002238/// MatchSelectFromAndOr - We have an expression of the form (A&C)|(B&D). Check
2239/// If A is (cond?-1:0) and either B or D is ~(cond?-1,0) or (cond?0,-1), then
2240/// we can simplify this expression to "cond ? C : D or B".
2241static Instruction *MatchSelectFromAndOr(Value *A, Value *B,
Chris Lattner4de84762010-01-04 07:02:48 +00002242 Value *C, Value *D) {
Chris Lattnera6a474d2008-11-16 04:26:55 +00002243 // If A is not a select of -1/0, this cannot match.
Chris Lattner6046fb72008-11-16 04:46:19 +00002244 Value *Cond = 0;
Dan Gohman4ae51262009-08-12 16:23:25 +00002245 if (!match(A, m_SelectCst<-1, 0>(m_Value(Cond))))
Chris Lattnerfaaf9512008-11-16 04:24:12 +00002246 return 0;
2247
Chris Lattnera6a474d2008-11-16 04:26:55 +00002248 // ((cond?-1:0)&C) | (B&(cond?0:-1)) -> cond ? C : B.
Dan Gohman4ae51262009-08-12 16:23:25 +00002249 if (match(D, m_SelectCst<0, -1>(m_Specific(Cond))))
Chris Lattnera6a474d2008-11-16 04:26:55 +00002250 return SelectInst::Create(Cond, C, B);
Dan Gohman4ae51262009-08-12 16:23:25 +00002251 if (match(D, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond)))))
Chris Lattnera6a474d2008-11-16 04:26:55 +00002252 return SelectInst::Create(Cond, C, B);
2253 // ((cond?-1:0)&C) | ((cond?0:-1)&D) -> cond ? C : D.
Dan Gohman4ae51262009-08-12 16:23:25 +00002254 if (match(B, m_SelectCst<0, -1>(m_Specific(Cond))))
Chris Lattnera6a474d2008-11-16 04:26:55 +00002255 return SelectInst::Create(Cond, C, D);
Dan Gohman4ae51262009-08-12 16:23:25 +00002256 if (match(B, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond)))))
Chris Lattnera6a474d2008-11-16 04:26:55 +00002257 return SelectInst::Create(Cond, C, D);
Chris Lattnerfaaf9512008-11-16 04:24:12 +00002258 return 0;
2259}
Chris Lattnerafe91a52006-06-15 19:07:26 +00002260
Chris Lattner69d4ced2008-11-16 05:20:07 +00002261/// FoldOrOfICmps - Fold (icmp)|(icmp) if possible.
2262Instruction *InstCombiner::FoldOrOfICmps(Instruction &I,
2263 ICmpInst *LHS, ICmpInst *RHS) {
Chris Lattnera317e042010-01-05 06:59:49 +00002264 ICmpInst::Predicate LHSCC = LHS->getPredicate(), RHSCC = RHS->getPredicate();
2265
2266 // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
2267 if (PredicatesFoldable(LHSCC, RHSCC)) {
2268 if (LHS->getOperand(0) == RHS->getOperand(1) &&
2269 LHS->getOperand(1) == RHS->getOperand(0))
2270 LHS->swapOperands();
2271 if (LHS->getOperand(0) == RHS->getOperand(0) &&
2272 LHS->getOperand(1) == RHS->getOperand(1)) {
2273 Value *Op0 = LHS->getOperand(0), *Op1 = LHS->getOperand(1);
2274 unsigned Code = getICmpCode(LHS) | getICmpCode(RHS);
2275 bool isSigned = LHS->isSigned() || RHS->isSigned();
2276 Value *RV = getICmpValue(isSigned, Code, Op0, Op1);
2277 if (Instruction *I = dyn_cast<Instruction>(RV))
2278 return I;
2279 // Otherwise, it's a constant boolean value.
2280 return ReplaceInstUsesWith(I, RV);
2281 }
2282 }
Chris Lattner69d4ced2008-11-16 05:20:07 +00002283
2284 // This only handles icmp of constants: (icmp1 A, C1) | (icmp2 B, C2).
Chris Lattnera317e042010-01-05 06:59:49 +00002285 Value *Val = LHS->getOperand(0), *Val2 = RHS->getOperand(0);
2286 ConstantInt *LHSCst = dyn_cast<ConstantInt>(LHS->getOperand(1));
2287 ConstantInt *RHSCst = dyn_cast<ConstantInt>(RHS->getOperand(1));
2288 if (LHSCst == 0 || RHSCst == 0) return 0;
Chris Lattner3f40e232009-11-29 00:51:17 +00002289
Chris Lattner3f40e232009-11-29 00:51:17 +00002290 // (icmp ne A, 0) | (icmp ne B, 0) --> (icmp ne (A|B), 0)
2291 if (LHSCst == RHSCst && LHSCC == RHSCC &&
2292 LHSCC == ICmpInst::ICMP_NE && LHSCst->isZero()) {
2293 Value *NewOr = Builder->CreateOr(Val, Val2);
2294 return new ICmpInst(LHSCC, NewOr, LHSCst);
2295 }
Chris Lattner69d4ced2008-11-16 05:20:07 +00002296
2297 // From here on, we only handle:
2298 // (icmp1 A, C1) | (icmp2 A, C2) --> something simpler.
2299 if (Val != Val2) return 0;
2300
2301 // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
2302 if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
2303 RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
2304 LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
2305 RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
2306 return 0;
2307
2308 // We can't fold (ugt x, C) | (sgt x, C2).
2309 if (!PredicatesFoldable(LHSCC, RHSCC))
2310 return 0;
2311
2312 // Ensure that the larger constant is on the RHS.
2313 bool ShouldSwap;
Nick Lewycky4a134af2009-10-25 05:20:17 +00002314 if (CmpInst::isSigned(LHSCC) ||
Chris Lattner69d4ced2008-11-16 05:20:07 +00002315 (ICmpInst::isEquality(LHSCC) &&
Nick Lewycky4a134af2009-10-25 05:20:17 +00002316 CmpInst::isSigned(RHSCC)))
Chris Lattner69d4ced2008-11-16 05:20:07 +00002317 ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
2318 else
2319 ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
2320
2321 if (ShouldSwap) {
2322 std::swap(LHS, RHS);
2323 std::swap(LHSCst, RHSCst);
2324 std::swap(LHSCC, RHSCC);
2325 }
2326
2327 // At this point, we know we have have two icmp instructions
2328 // comparing a value against two constants and or'ing the result
2329 // together. Because of the above check, we know that we only have
2330 // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
Chris Lattnera317e042010-01-05 06:59:49 +00002331 // icmp folding check above), that the two constants are not
Chris Lattner69d4ced2008-11-16 05:20:07 +00002332 // equal.
2333 assert(LHSCst != RHSCst && "Compares not folded above?");
2334
2335 switch (LHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00002336 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00002337 case ICmpInst::ICMP_EQ:
2338 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00002339 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00002340 case ICmpInst::ICMP_EQ:
Dan Gohman186a6362009-08-12 16:04:34 +00002341 if (LHSCst == SubOne(RHSCst)) {
Owen Andersond672ecb2009-07-03 00:17:18 +00002342 // (X == 13 | X == 14) -> X-13 <u 2
Owen Andersonbaf3c402009-07-29 18:55:55 +00002343 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
Chris Lattner74381062009-08-30 07:44:24 +00002344 Value *Add = Builder->CreateAdd(Val, AddCST, Val->getName()+".off");
Dan Gohman186a6362009-08-12 16:04:34 +00002345 AddCST = ConstantExpr::getSub(AddOne(RHSCst), LHSCst);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00002346 return new ICmpInst(ICmpInst::ICMP_ULT, Add, AddCST);
Chris Lattner69d4ced2008-11-16 05:20:07 +00002347 }
2348 break; // (X == 13 | X == 15) -> no change
2349 case ICmpInst::ICMP_UGT: // (X == 13 | X u> 14) -> no change
2350 case ICmpInst::ICMP_SGT: // (X == 13 | X s> 14) -> no change
2351 break;
2352 case ICmpInst::ICMP_NE: // (X == 13 | X != 15) -> X != 15
2353 case ICmpInst::ICMP_ULT: // (X == 13 | X u< 15) -> X u< 15
2354 case ICmpInst::ICMP_SLT: // (X == 13 | X s< 15) -> X s< 15
2355 return ReplaceInstUsesWith(I, RHS);
2356 }
2357 break;
2358 case ICmpInst::ICMP_NE:
2359 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00002360 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00002361 case ICmpInst::ICMP_EQ: // (X != 13 | X == 15) -> X != 13
2362 case ICmpInst::ICMP_UGT: // (X != 13 | X u> 15) -> X != 13
2363 case ICmpInst::ICMP_SGT: // (X != 13 | X s> 15) -> X != 13
2364 return ReplaceInstUsesWith(I, LHS);
2365 case ICmpInst::ICMP_NE: // (X != 13 | X != 15) -> true
2366 case ICmpInst::ICMP_ULT: // (X != 13 | X u< 15) -> true
2367 case ICmpInst::ICMP_SLT: // (X != 13 | X s< 15) -> true
Chris Lattner4de84762010-01-04 07:02:48 +00002368 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getContext()));
Chris Lattner69d4ced2008-11-16 05:20:07 +00002369 }
2370 break;
2371 case ICmpInst::ICMP_ULT:
2372 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00002373 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00002374 case ICmpInst::ICMP_EQ: // (X u< 13 | X == 14) -> no change
2375 break;
2376 case ICmpInst::ICMP_UGT: // (X u< 13 | X u> 15) -> (X-13) u> 2
2377 // If RHSCst is [us]MAXINT, it is always false. Not handling
2378 // this can cause overflow.
2379 if (RHSCst->isMaxValue(false))
2380 return ReplaceInstUsesWith(I, LHS);
Dan Gohman186a6362009-08-12 16:04:34 +00002381 return InsertRangeTest(Val, LHSCst, AddOne(RHSCst),
Owen Andersond672ecb2009-07-03 00:17:18 +00002382 false, false, I);
Chris Lattner69d4ced2008-11-16 05:20:07 +00002383 case ICmpInst::ICMP_SGT: // (X u< 13 | X s> 15) -> no change
2384 break;
2385 case ICmpInst::ICMP_NE: // (X u< 13 | X != 15) -> X != 15
2386 case ICmpInst::ICMP_ULT: // (X u< 13 | X u< 15) -> X u< 15
2387 return ReplaceInstUsesWith(I, RHS);
2388 case ICmpInst::ICMP_SLT: // (X u< 13 | X s< 15) -> no change
2389 break;
2390 }
2391 break;
2392 case ICmpInst::ICMP_SLT:
2393 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00002394 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00002395 case ICmpInst::ICMP_EQ: // (X s< 13 | X == 14) -> no change
2396 break;
2397 case ICmpInst::ICMP_SGT: // (X s< 13 | X s> 15) -> (X-13) s> 2
2398 // If RHSCst is [us]MAXINT, it is always false. Not handling
2399 // this can cause overflow.
2400 if (RHSCst->isMaxValue(true))
2401 return ReplaceInstUsesWith(I, LHS);
Dan Gohman186a6362009-08-12 16:04:34 +00002402 return InsertRangeTest(Val, LHSCst, AddOne(RHSCst),
Owen Andersond672ecb2009-07-03 00:17:18 +00002403 true, false, I);
Chris Lattner69d4ced2008-11-16 05:20:07 +00002404 case ICmpInst::ICMP_UGT: // (X s< 13 | X u> 15) -> no change
2405 break;
2406 case ICmpInst::ICMP_NE: // (X s< 13 | X != 15) -> X != 15
2407 case ICmpInst::ICMP_SLT: // (X s< 13 | X s< 15) -> X s< 15
2408 return ReplaceInstUsesWith(I, RHS);
2409 case ICmpInst::ICMP_ULT: // (X s< 13 | X u< 15) -> no change
2410 break;
2411 }
2412 break;
2413 case ICmpInst::ICMP_UGT:
2414 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00002415 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00002416 case ICmpInst::ICMP_EQ: // (X u> 13 | X == 15) -> X u> 13
2417 case ICmpInst::ICMP_UGT: // (X u> 13 | X u> 15) -> X u> 13
2418 return ReplaceInstUsesWith(I, LHS);
2419 case ICmpInst::ICMP_SGT: // (X u> 13 | X s> 15) -> no change
2420 break;
2421 case ICmpInst::ICMP_NE: // (X u> 13 | X != 15) -> true
2422 case ICmpInst::ICMP_ULT: // (X u> 13 | X u< 15) -> true
Chris Lattner4de84762010-01-04 07:02:48 +00002423 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getContext()));
Chris Lattner69d4ced2008-11-16 05:20:07 +00002424 case ICmpInst::ICMP_SLT: // (X u> 13 | X s< 15) -> no change
2425 break;
2426 }
2427 break;
2428 case ICmpInst::ICMP_SGT:
2429 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00002430 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00002431 case ICmpInst::ICMP_EQ: // (X s> 13 | X == 15) -> X > 13
2432 case ICmpInst::ICMP_SGT: // (X s> 13 | X s> 15) -> X > 13
2433 return ReplaceInstUsesWith(I, LHS);
2434 case ICmpInst::ICMP_UGT: // (X s> 13 | X u> 15) -> no change
2435 break;
2436 case ICmpInst::ICMP_NE: // (X s> 13 | X != 15) -> true
2437 case ICmpInst::ICMP_SLT: // (X s> 13 | X s< 15) -> true
Chris Lattner4de84762010-01-04 07:02:48 +00002438 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getContext()));
Chris Lattner69d4ced2008-11-16 05:20:07 +00002439 case ICmpInst::ICMP_ULT: // (X s> 13 | X u< 15) -> no change
2440 break;
2441 }
2442 break;
2443 }
2444 return 0;
2445}
2446
Chris Lattner5414cc52009-07-23 05:46:22 +00002447Instruction *InstCombiner::FoldOrOfFCmps(Instruction &I, FCmpInst *LHS,
2448 FCmpInst *RHS) {
2449 if (LHS->getPredicate() == FCmpInst::FCMP_UNO &&
2450 RHS->getPredicate() == FCmpInst::FCMP_UNO &&
2451 LHS->getOperand(0)->getType() == RHS->getOperand(0)->getType()) {
2452 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
2453 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
2454 // If either of the constants are nans, then the whole thing returns
2455 // true.
2456 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Chris Lattner4de84762010-01-04 07:02:48 +00002457 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getContext()));
Chris Lattner5414cc52009-07-23 05:46:22 +00002458
2459 // Otherwise, no need to compare the two constants, compare the
2460 // rest.
Dan Gohman1c8a23c2009-08-25 23:17:54 +00002461 return new FCmpInst(FCmpInst::FCMP_UNO,
Chris Lattner5414cc52009-07-23 05:46:22 +00002462 LHS->getOperand(0), RHS->getOperand(0));
2463 }
2464
2465 // Handle vector zeros. This occurs because the canonical form of
2466 // "fcmp uno x,x" is "fcmp uno x, 0".
2467 if (isa<ConstantAggregateZero>(LHS->getOperand(1)) &&
2468 isa<ConstantAggregateZero>(RHS->getOperand(1)))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00002469 return new FCmpInst(FCmpInst::FCMP_UNO,
Chris Lattner5414cc52009-07-23 05:46:22 +00002470 LHS->getOperand(0), RHS->getOperand(0));
2471
2472 return 0;
2473 }
2474
2475 Value *Op0LHS = LHS->getOperand(0), *Op0RHS = LHS->getOperand(1);
2476 Value *Op1LHS = RHS->getOperand(0), *Op1RHS = RHS->getOperand(1);
2477 FCmpInst::Predicate Op0CC = LHS->getPredicate(), Op1CC = RHS->getPredicate();
2478
2479 if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
2480 // Swap RHS operands to match LHS.
2481 Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
2482 std::swap(Op1LHS, Op1RHS);
2483 }
2484 if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
2485 // Simplify (fcmp cc0 x, y) | (fcmp cc1 x, y).
2486 if (Op0CC == Op1CC)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00002487 return new FCmpInst((FCmpInst::Predicate)Op0CC,
Chris Lattner5414cc52009-07-23 05:46:22 +00002488 Op0LHS, Op0RHS);
2489 if (Op0CC == FCmpInst::FCMP_TRUE || Op1CC == FCmpInst::FCMP_TRUE)
Chris Lattner4de84762010-01-04 07:02:48 +00002490 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getContext()));
Chris Lattner5414cc52009-07-23 05:46:22 +00002491 if (Op0CC == FCmpInst::FCMP_FALSE)
2492 return ReplaceInstUsesWith(I, RHS);
2493 if (Op1CC == FCmpInst::FCMP_FALSE)
2494 return ReplaceInstUsesWith(I, LHS);
2495 bool Op0Ordered;
2496 bool Op1Ordered;
2497 unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
2498 unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
2499 if (Op0Ordered == Op1Ordered) {
2500 // If both are ordered or unordered, return a new fcmp with
2501 // or'ed predicates.
Chris Lattner4de84762010-01-04 07:02:48 +00002502 Value *RV = getFCmpValue(Op0Ordered, Op0Pred|Op1Pred, Op0LHS, Op0RHS);
Chris Lattner5414cc52009-07-23 05:46:22 +00002503 if (Instruction *I = dyn_cast<Instruction>(RV))
2504 return I;
2505 // Otherwise, it's a constant boolean value...
2506 return ReplaceInstUsesWith(I, RV);
2507 }
2508 }
2509 return 0;
2510}
2511
Bill Wendlinga698a472008-12-01 08:23:25 +00002512/// FoldOrWithConstants - This helper function folds:
2513///
Bill Wendlinga8bb13f2008-12-02 05:09:00 +00002514/// ((A | B) & C1) | (B & C2)
Bill Wendlinga698a472008-12-01 08:23:25 +00002515///
2516/// into:
2517///
Bill Wendlinga8bb13f2008-12-02 05:09:00 +00002518/// (A & C1) | B
Bill Wendlingd54d8602008-12-01 08:32:40 +00002519///
Bill Wendlinga8bb13f2008-12-02 05:09:00 +00002520/// when the XOR of the two constants is "all ones" (-1).
Bill Wendlingd54d8602008-12-01 08:32:40 +00002521Instruction *InstCombiner::FoldOrWithConstants(BinaryOperator &I, Value *Op,
Bill Wendlinga698a472008-12-01 08:23:25 +00002522 Value *A, Value *B, Value *C) {
Bill Wendlingdda74e02008-12-02 05:06:43 +00002523 ConstantInt *CI1 = dyn_cast<ConstantInt>(C);
2524 if (!CI1) return 0;
Bill Wendlinga698a472008-12-01 08:23:25 +00002525
Bill Wendling286a0542008-12-02 06:24:20 +00002526 Value *V1 = 0;
2527 ConstantInt *CI2 = 0;
Dan Gohman4ae51262009-08-12 16:23:25 +00002528 if (!match(Op, m_And(m_Value(V1), m_ConstantInt(CI2)))) return 0;
Bill Wendlinga698a472008-12-01 08:23:25 +00002529
Bill Wendling29976b92008-12-02 06:18:11 +00002530 APInt Xor = CI1->getValue() ^ CI2->getValue();
2531 if (!Xor.isAllOnesValue()) return 0;
2532
Bill Wendling286a0542008-12-02 06:24:20 +00002533 if (V1 == A || V1 == B) {
Chris Lattner74381062009-08-30 07:44:24 +00002534 Value *NewOp = Builder->CreateAnd((V1 == A) ? B : A, CI1);
Bill Wendlingd16c6e92008-12-02 06:22:04 +00002535 return BinaryOperator::CreateOr(NewOp, V1);
Bill Wendlinga698a472008-12-01 08:23:25 +00002536 }
2537
2538 return 0;
2539}
2540
Chris Lattner7e708292002-06-25 16:13:24 +00002541Instruction *InstCombiner::visitOr(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00002542 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00002543 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00002544
Chris Lattnerd06094f2009-11-10 00:55:12 +00002545 if (Value *V = SimplifyOrInst(Op0, Op1, TD))
2546 return ReplaceInstUsesWith(I, V);
2547
2548
Chris Lattnerf8c36f52006-02-12 08:02:11 +00002549 // See if we can simplify any instructions used by the instruction whose sole
2550 // purpose is to compute bits we don't care about.
Dan Gohman6de29f82009-06-15 22:12:54 +00002551 if (SimplifyDemandedInstructionBits(I))
2552 return &I;
Chris Lattner041a6c92007-06-15 05:26:55 +00002553
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002554 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner4f637d42006-01-06 17:59:59 +00002555 ConstantInt *C1 = 0; Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002556 // (X & C1) | C2 --> (X | C2) & (C1|C2)
Dan Gohman4ae51262009-08-12 16:23:25 +00002557 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00002558 isOnlyUse(Op0)) {
Chris Lattner74381062009-08-30 07:44:24 +00002559 Value *Or = Builder->CreateOr(X, RHS);
Chris Lattner6934a042007-02-11 01:23:03 +00002560 Or->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002561 return BinaryOperator::CreateAnd(Or,
Chris Lattner4de84762010-01-04 07:02:48 +00002562 ConstantInt::get(I.getContext(),
2563 RHS->getValue() | C1->getValue()));
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002564 }
Chris Lattnerad44ebf2003-07-23 18:29:44 +00002565
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002566 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
Dan Gohman4ae51262009-08-12 16:23:25 +00002567 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00002568 isOnlyUse(Op0)) {
Chris Lattner74381062009-08-30 07:44:24 +00002569 Value *Or = Builder->CreateOr(X, RHS);
Chris Lattner6934a042007-02-11 01:23:03 +00002570 Or->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002571 return BinaryOperator::CreateXor(Or,
Chris Lattner4de84762010-01-04 07:02:48 +00002572 ConstantInt::get(I.getContext(),
2573 C1->getValue() & ~RHS->getValue()));
Chris Lattnerad44ebf2003-07-23 18:29:44 +00002574 }
Chris Lattner2eefe512004-04-09 19:05:30 +00002575
2576 // Try to fold constant and into select arguments.
2577 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner80f43d32010-01-04 07:53:58 +00002578 if (Instruction *R = FoldOpIntoSelect(I, SI))
Chris Lattner2eefe512004-04-09 19:05:30 +00002579 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00002580 if (isa<PHINode>(Op0))
2581 if (Instruction *NV = FoldOpIntoPhi(I))
2582 return NV;
Chris Lattnerad44ebf2003-07-23 18:29:44 +00002583 }
2584
Chris Lattner4f637d42006-01-06 17:59:59 +00002585 Value *A = 0, *B = 0;
2586 ConstantInt *C1 = 0, *C2 = 0;
Chris Lattnerf4d4c872005-05-07 23:49:08 +00002587
Chris Lattner6423d4c2006-07-10 20:25:24 +00002588 // (A | B) | C and A | (B | C) -> bswap if possible.
2589 // (A >> B) | (C << D) and (A << B) | (B >> C) -> bswap if possible.
Dan Gohman4ae51262009-08-12 16:23:25 +00002590 if (match(Op0, m_Or(m_Value(), m_Value())) ||
2591 match(Op1, m_Or(m_Value(), m_Value())) ||
2592 (match(Op0, m_Shift(m_Value(), m_Value())) &&
2593 match(Op1, m_Shift(m_Value(), m_Value())))) {
Chris Lattnerafe91a52006-06-15 19:07:26 +00002594 if (Instruction *BSwap = MatchBSwap(I))
2595 return BSwap;
2596 }
2597
Chris Lattner6e4c6492005-05-09 04:58:36 +00002598 // (X^C)|Y -> (X|Y)^C iff Y&C == 0
Owen Andersonc7d2ce72009-07-10 17:35:01 +00002599 if (Op0->hasOneUse() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00002600 match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Reid Spencera03d45f2007-03-22 22:19:58 +00002601 MaskedValueIsZero(Op1, C1->getValue())) {
Chris Lattner74381062009-08-30 07:44:24 +00002602 Value *NOr = Builder->CreateOr(A, Op1);
Chris Lattner6934a042007-02-11 01:23:03 +00002603 NOr->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002604 return BinaryOperator::CreateXor(NOr, C1);
Chris Lattner6e4c6492005-05-09 04:58:36 +00002605 }
2606
2607 // Y|(X^C) -> (X|Y)^C iff Y&C == 0
Owen Andersonc7d2ce72009-07-10 17:35:01 +00002608 if (Op1->hasOneUse() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00002609 match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Reid Spencera03d45f2007-03-22 22:19:58 +00002610 MaskedValueIsZero(Op0, C1->getValue())) {
Chris Lattner74381062009-08-30 07:44:24 +00002611 Value *NOr = Builder->CreateOr(A, Op0);
Chris Lattner6934a042007-02-11 01:23:03 +00002612 NOr->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002613 return BinaryOperator::CreateXor(NOr, C1);
Chris Lattner6e4c6492005-05-09 04:58:36 +00002614 }
2615
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00002616 // (A & C)|(B & D)
Chris Lattner2384d7b2007-06-19 05:43:49 +00002617 Value *C = 0, *D = 0;
Dan Gohman4ae51262009-08-12 16:23:25 +00002618 if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
2619 match(Op1, m_And(m_Value(B), m_Value(D)))) {
Chris Lattner6cae0e02007-04-08 07:55:22 +00002620 Value *V1 = 0, *V2 = 0, *V3 = 0;
2621 C1 = dyn_cast<ConstantInt>(C);
2622 C2 = dyn_cast<ConstantInt>(D);
2623 if (C1 && C2) { // (A & C1)|(B & C2)
2624 // If we have: ((V + N) & C1) | (V & C2)
2625 // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
2626 // replace with V+N.
2627 if (C1->getValue() == ~C2->getValue()) {
2628 if ((C2->getValue() & (C2->getValue()+1)) == 0 && // C2 == 0+1+
Dan Gohman4ae51262009-08-12 16:23:25 +00002629 match(A, m_Add(m_Value(V1), m_Value(V2)))) {
Chris Lattner6cae0e02007-04-08 07:55:22 +00002630 // Add commutes, try both ways.
2631 if (V1 == B && MaskedValueIsZero(V2, C2->getValue()))
2632 return ReplaceInstUsesWith(I, A);
2633 if (V2 == B && MaskedValueIsZero(V1, C2->getValue()))
2634 return ReplaceInstUsesWith(I, A);
2635 }
2636 // Or commutes, try both ways.
2637 if ((C1->getValue() & (C1->getValue()+1)) == 0 &&
Dan Gohman4ae51262009-08-12 16:23:25 +00002638 match(B, m_Add(m_Value(V1), m_Value(V2)))) {
Chris Lattner6cae0e02007-04-08 07:55:22 +00002639 // Add commutes, try both ways.
2640 if (V1 == A && MaskedValueIsZero(V2, C1->getValue()))
2641 return ReplaceInstUsesWith(I, B);
2642 if (V2 == A && MaskedValueIsZero(V1, C1->getValue()))
2643 return ReplaceInstUsesWith(I, B);
2644 }
2645 }
Chris Lattnere4412c12010-01-04 06:03:59 +00002646
2647 // ((V | N) & C1) | (V & C2) --> (V|N) & (C1|C2)
2648 // iff (C1&C2) == 0 and (N&~C1) == 0
2649 if ((C1->getValue() & C2->getValue()) == 0) {
2650 if (match(A, m_Or(m_Value(V1), m_Value(V2))) &&
2651 ((V1 == B && MaskedValueIsZero(V2, ~C1->getValue())) || // (V|N)
2652 (V2 == B && MaskedValueIsZero(V1, ~C1->getValue())))) // (N|V)
2653 return BinaryOperator::CreateAnd(A,
2654 ConstantInt::get(A->getContext(),
2655 C1->getValue()|C2->getValue()));
2656 // Or commutes, try both ways.
2657 if (match(B, m_Or(m_Value(V1), m_Value(V2))) &&
2658 ((V1 == A && MaskedValueIsZero(V2, ~C2->getValue())) || // (V|N)
2659 (V2 == A && MaskedValueIsZero(V1, ~C2->getValue())))) // (N|V)
2660 return BinaryOperator::CreateAnd(B,
2661 ConstantInt::get(B->getContext(),
2662 C1->getValue()|C2->getValue()));
2663 }
Chris Lattner6cae0e02007-04-08 07:55:22 +00002664 }
2665
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00002666 // Check to see if we have any common things being and'ed. If so, find the
2667 // terms for V1 & (V2|V3).
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00002668 if (isOnlyUse(Op0) || isOnlyUse(Op1)) {
Chris Lattnere4412c12010-01-04 06:03:59 +00002669 V1 = 0;
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00002670 if (A == B) // (A & C)|(A & D) == A & (C|D)
2671 V1 = A, V2 = C, V3 = D;
2672 else if (A == D) // (A & C)|(B & A) == A & (B|C)
2673 V1 = A, V2 = B, V3 = C;
2674 else if (C == B) // (A & C)|(C & D) == C & (A|D)
2675 V1 = C, V2 = A, V3 = D;
2676 else if (C == D) // (A & C)|(B & C) == C & (A|B)
2677 V1 = C, V2 = A, V3 = B;
2678
2679 if (V1) {
Chris Lattner74381062009-08-30 07:44:24 +00002680 Value *Or = Builder->CreateOr(V2, V3, "tmp");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002681 return BinaryOperator::CreateAnd(V1, Or);
Chris Lattner0b7c0bf2005-09-18 06:02:59 +00002682 }
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00002683 }
Dan Gohmanb493b272008-10-28 22:38:57 +00002684
Dan Gohman1975d032008-10-30 20:40:10 +00002685 // (A & (C0?-1:0)) | (B & ~(C0?-1:0)) -> C0 ? A : B, and commuted variants
Chris Lattner4de84762010-01-04 07:02:48 +00002686 if (Instruction *Match = MatchSelectFromAndOr(A, B, C, D))
Chris Lattnerfaaf9512008-11-16 04:24:12 +00002687 return Match;
Chris Lattner4de84762010-01-04 07:02:48 +00002688 if (Instruction *Match = MatchSelectFromAndOr(B, A, D, C))
Chris Lattnerfaaf9512008-11-16 04:24:12 +00002689 return Match;
Chris Lattner4de84762010-01-04 07:02:48 +00002690 if (Instruction *Match = MatchSelectFromAndOr(C, B, A, D))
Chris Lattnerfaaf9512008-11-16 04:24:12 +00002691 return Match;
Chris Lattner4de84762010-01-04 07:02:48 +00002692 if (Instruction *Match = MatchSelectFromAndOr(D, A, B, C))
Chris Lattnerfaaf9512008-11-16 04:24:12 +00002693 return Match;
Bill Wendlingb01865c2008-11-30 13:52:49 +00002694
Bill Wendlingb01865c2008-11-30 13:52:49 +00002695 // ((A&~B)|(~A&B)) -> A^B
Dan Gohman4ae51262009-08-12 16:23:25 +00002696 if ((match(C, m_Not(m_Specific(D))) &&
2697 match(B, m_Not(m_Specific(A)))))
Bill Wendling03aae5f2008-12-01 08:09:47 +00002698 return BinaryOperator::CreateXor(A, D);
Bill Wendlingb01865c2008-11-30 13:52:49 +00002699 // ((~B&A)|(~A&B)) -> A^B
Dan Gohman4ae51262009-08-12 16:23:25 +00002700 if ((match(A, m_Not(m_Specific(D))) &&
2701 match(B, m_Not(m_Specific(C)))))
Bill Wendling03aae5f2008-12-01 08:09:47 +00002702 return BinaryOperator::CreateXor(C, D);
Bill Wendlingb01865c2008-11-30 13:52:49 +00002703 // ((A&~B)|(B&~A)) -> A^B
Dan Gohman4ae51262009-08-12 16:23:25 +00002704 if ((match(C, m_Not(m_Specific(B))) &&
2705 match(D, m_Not(m_Specific(A)))))
Bill Wendling03aae5f2008-12-01 08:09:47 +00002706 return BinaryOperator::CreateXor(A, B);
Bill Wendlingb01865c2008-11-30 13:52:49 +00002707 // ((~B&A)|(B&~A)) -> A^B
Dan Gohman4ae51262009-08-12 16:23:25 +00002708 if ((match(A, m_Not(m_Specific(B))) &&
2709 match(D, m_Not(m_Specific(C)))))
Bill Wendling03aae5f2008-12-01 08:09:47 +00002710 return BinaryOperator::CreateXor(C, B);
Chris Lattnere9bed7d2005-09-18 03:42:07 +00002711 }
Chris Lattnere511b742006-11-14 07:46:50 +00002712
2713 // (X >> Z) | (Y >> Z) -> (X|Y) >> Z for all shifts.
Reid Spencer832254e2007-02-02 02:16:23 +00002714 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
2715 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
2716 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
Chris Lattnere511b742006-11-14 07:46:50 +00002717 SI0->getOperand(1) == SI1->getOperand(1) &&
2718 (SI0->hasOneUse() || SI1->hasOneUse())) {
Chris Lattner74381062009-08-30 07:44:24 +00002719 Value *NewOp = Builder->CreateOr(SI0->getOperand(0), SI1->getOperand(0),
2720 SI0->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002721 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
Reid Spencer832254e2007-02-02 02:16:23 +00002722 SI1->getOperand(1));
Chris Lattnere511b742006-11-14 07:46:50 +00002723 }
2724 }
Chris Lattner67ca7682003-08-12 19:11:07 +00002725
Bill Wendlingb3833d12008-12-01 01:07:11 +00002726 // ((A|B)&1)|(B&-2) -> (A&1) | B
Dan Gohman4ae51262009-08-12 16:23:25 +00002727 if (match(Op0, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C))) ||
2728 match(Op0, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))))) {
Bill Wendlingd54d8602008-12-01 08:32:40 +00002729 Instruction *Ret = FoldOrWithConstants(I, Op1, A, B, C);
Bill Wendlinga698a472008-12-01 08:23:25 +00002730 if (Ret) return Ret;
Bill Wendlingb3833d12008-12-01 01:07:11 +00002731 }
2732 // (B&-2)|((A|B)&1) -> (A&1) | B
Dan Gohman4ae51262009-08-12 16:23:25 +00002733 if (match(Op1, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C))) ||
2734 match(Op1, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))))) {
Bill Wendlingd54d8602008-12-01 08:32:40 +00002735 Instruction *Ret = FoldOrWithConstants(I, Op0, A, B, C);
Bill Wendlinga698a472008-12-01 08:23:25 +00002736 if (Ret) return Ret;
Bill Wendlingb3833d12008-12-01 01:07:11 +00002737 }
2738
Chris Lattnerd06094f2009-11-10 00:55:12 +00002739 // (~A | ~B) == (~(A & B)) - De Morgan's Law
2740 if (Value *Op0NotVal = dyn_castNotVal(Op0))
2741 if (Value *Op1NotVal = dyn_castNotVal(Op1))
2742 if (Op0->hasOneUse() && Op1->hasOneUse()) {
2743 Value *And = Builder->CreateAnd(Op0NotVal, Op1NotVal,
2744 I.getName()+".demorgan");
2745 return BinaryOperator::CreateNot(And);
2746 }
Chris Lattnera2881962003-02-18 19:28:33 +00002747
Chris Lattnera317e042010-01-05 06:59:49 +00002748 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
Chris Lattner69d4ced2008-11-16 05:20:07 +00002749 if (ICmpInst *LHS = dyn_cast<ICmpInst>(I.getOperand(0)))
2750 if (Instruction *Res = FoldOrOfICmps(I, LHS, RHS))
2751 return Res;
Chris Lattner6fc205f2006-05-05 06:39:07 +00002752
2753 // fold (or (cast A), (cast B)) -> (cast (or A, B))
Chris Lattner99c65742007-10-24 05:38:08 +00002754 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Chris Lattner6fc205f2006-05-05 06:39:07 +00002755 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00002756 if (Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
Evan Chengb98a10e2008-03-24 00:21:34 +00002757 if (!isa<ICmpInst>(Op0C->getOperand(0)) ||
2758 !isa<ICmpInst>(Op1C->getOperand(0))) {
2759 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattnerf98d2532009-07-23 05:32:17 +00002760 if (SrcTy == Op1C->getOperand(0)->getType() &&
2761 SrcTy->isIntOrIntVector() &&
Evan Chengb98a10e2008-03-24 00:21:34 +00002762 // Only do this if the casts both really cause code to be
2763 // generated.
2764 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
Chris Lattner80f43d32010-01-04 07:53:58 +00002765 I.getType()) &&
Evan Chengb98a10e2008-03-24 00:21:34 +00002766 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
Chris Lattner80f43d32010-01-04 07:53:58 +00002767 I.getType())) {
Chris Lattner74381062009-08-30 07:44:24 +00002768 Value *NewOp = Builder->CreateOr(Op0C->getOperand(0),
2769 Op1C->getOperand(0), I.getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002770 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Evan Chengb98a10e2008-03-24 00:21:34 +00002771 }
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00002772 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00002773 }
Chris Lattner99c65742007-10-24 05:38:08 +00002774 }
2775
2776
2777 // (fcmp uno x, c) | (fcmp uno y, c) -> (fcmp uno x, y)
2778 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
Chris Lattner5414cc52009-07-23 05:46:22 +00002779 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
2780 if (Instruction *Res = FoldOrOfFCmps(I, LHS, RHS))
2781 return Res;
Chris Lattner99c65742007-10-24 05:38:08 +00002782 }
Chris Lattnere9bed7d2005-09-18 03:42:07 +00002783
Chris Lattner7e708292002-06-25 16:13:24 +00002784 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00002785}
2786
Chris Lattner7e708292002-06-25 16:13:24 +00002787Instruction *InstCombiner::visitXor(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00002788 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00002789 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00002790
Evan Chengd34af782008-03-25 20:07:13 +00002791 if (isa<UndefValue>(Op1)) {
2792 if (isa<UndefValue>(Op0))
2793 // Handle undef ^ undef -> 0 special case. This is a common
2794 // idiom (misuse).
Owen Andersona7235ea2009-07-31 20:28:14 +00002795 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00002796 return ReplaceInstUsesWith(I, Op1); // X ^ undef -> undef
Evan Chengd34af782008-03-25 20:07:13 +00002797 }
Chris Lattnere87597f2004-10-16 18:11:37 +00002798
Chris Lattnerdea34da2010-01-05 07:01:16 +00002799 // xor X, X = 0
2800 if (Op0 == Op1)
Owen Andersona7235ea2009-07-31 20:28:14 +00002801 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerf8c36f52006-02-12 08:02:11 +00002802
2803 // See if we can simplify any instructions used by the instruction whose sole
2804 // purpose is to compute bits we don't care about.
Dan Gohman6de29f82009-06-15 22:12:54 +00002805 if (SimplifyDemandedInstructionBits(I))
2806 return &I;
2807 if (isa<VectorType>(I.getType()))
2808 if (isa<ConstantAggregateZero>(Op1))
2809 return ReplaceInstUsesWith(I, Op0); // X ^ <0,0> -> X
Chris Lattner3f5b8772002-05-06 16:14:14 +00002810
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00002811 // Is this a ~ operation?
Dan Gohman186a6362009-08-12 16:04:34 +00002812 if (Value *NotOp = dyn_castNotVal(&I)) {
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00002813 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(NotOp)) {
2814 if (Op0I->getOpcode() == Instruction::And ||
2815 Op0I->getOpcode() == Instruction::Or) {
Chris Lattner48b59ec2009-10-26 15:40:07 +00002816 // ~(~X & Y) --> (X | ~Y) - De Morgan's Law
2817 // ~(~X | Y) === (X & ~Y) - De Morgan's Law
2818 if (dyn_castNotVal(Op0I->getOperand(1)))
2819 Op0I->swapOperands();
Dan Gohman186a6362009-08-12 16:04:34 +00002820 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
Chris Lattner74381062009-08-30 07:44:24 +00002821 Value *NotY =
2822 Builder->CreateNot(Op0I->getOperand(1),
2823 Op0I->getOperand(1)->getName()+".not");
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00002824 if (Op0I->getOpcode() == Instruction::And)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002825 return BinaryOperator::CreateOr(Op0NotVal, NotY);
Chris Lattner74381062009-08-30 07:44:24 +00002826 return BinaryOperator::CreateAnd(Op0NotVal, NotY);
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00002827 }
Chris Lattner48b59ec2009-10-26 15:40:07 +00002828
2829 // ~(X & Y) --> (~X | ~Y) - De Morgan's Law
2830 // ~(X | Y) === (~X & ~Y) - De Morgan's Law
2831 if (isFreeToInvert(Op0I->getOperand(0)) &&
2832 isFreeToInvert(Op0I->getOperand(1))) {
2833 Value *NotX =
2834 Builder->CreateNot(Op0I->getOperand(0), "notlhs");
2835 Value *NotY =
2836 Builder->CreateNot(Op0I->getOperand(1), "notrhs");
2837 if (Op0I->getOpcode() == Instruction::And)
2838 return BinaryOperator::CreateOr(NotX, NotY);
2839 return BinaryOperator::CreateAnd(NotX, NotY);
2840 }
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00002841 }
2842 }
2843 }
2844
2845
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002846 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner7acdf1d2009-10-11 22:00:32 +00002847 if (RHS->isOne() && Op0->hasOneUse()) {
Bill Wendling3479be92009-01-01 01:18:23 +00002848 // xor (cmp A, B), true = not (cmp A, B) = !cmp A, B
Nick Lewyckyf947b3e2007-08-06 20:04:16 +00002849 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Op0))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00002850 return new ICmpInst(ICI->getInversePredicate(),
Reid Spencere4d87aa2006-12-23 06:05:41 +00002851 ICI->getOperand(0), ICI->getOperand(1));
Chris Lattnerad5b4fb2003-11-04 23:50:51 +00002852
Nick Lewyckyf947b3e2007-08-06 20:04:16 +00002853 if (FCmpInst *FCI = dyn_cast<FCmpInst>(Op0))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00002854 return new FCmpInst(FCI->getInversePredicate(),
Nick Lewyckyf947b3e2007-08-06 20:04:16 +00002855 FCI->getOperand(0), FCI->getOperand(1));
2856 }
2857
Nick Lewycky517e1f52008-05-31 19:01:33 +00002858 // fold (xor(zext(cmp)), 1) and (xor(sext(cmp)), -1) to ext(!cmp).
2859 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
2860 if (CmpInst *CI = dyn_cast<CmpInst>(Op0C->getOperand(0))) {
2861 if (CI->hasOneUse() && Op0C->hasOneUse()) {
2862 Instruction::CastOps Opcode = Op0C->getOpcode();
Chris Lattner74381062009-08-30 07:44:24 +00002863 if ((Opcode == Instruction::ZExt || Opcode == Instruction::SExt) &&
2864 (RHS == ConstantExpr::getCast(Opcode,
Chris Lattner4de84762010-01-04 07:02:48 +00002865 ConstantInt::getTrue(I.getContext()),
Chris Lattner74381062009-08-30 07:44:24 +00002866 Op0C->getDestTy()))) {
2867 CI->setPredicate(CI->getInversePredicate());
2868 return CastInst::Create(Opcode, CI, Op0C->getType());
Nick Lewycky517e1f52008-05-31 19:01:33 +00002869 }
2870 }
2871 }
2872 }
2873
Reid Spencere4d87aa2006-12-23 06:05:41 +00002874 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Chris Lattnerd65460f2003-11-05 01:06:05 +00002875 // ~(c-X) == X-c-1 == X+(-c-1)
Chris Lattner7c4049c2004-01-12 19:35:11 +00002876 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
2877 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00002878 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
2879 Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
Owen Andersoneed707b2009-07-24 23:12:02 +00002880 ConstantInt::get(I.getType(), 1));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002881 return BinaryOperator::CreateAdd(Op0I->getOperand(1), ConstantRHS);
Chris Lattner7c4049c2004-01-12 19:35:11 +00002882 }
Chris Lattner5c6e2db2007-04-02 05:36:22 +00002883
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00002884 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
Chris Lattnerf8c36f52006-02-12 08:02:11 +00002885 if (Op0I->getOpcode() == Instruction::Add) {
Chris Lattner689d24b2003-11-04 23:37:10 +00002886 // ~(X-c) --> (-c-1)-X
Chris Lattner7c4049c2004-01-12 19:35:11 +00002887 if (RHS->isAllOnesValue()) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00002888 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002889 return BinaryOperator::CreateSub(
Owen Andersonbaf3c402009-07-29 18:55:55 +00002890 ConstantExpr::getSub(NegOp0CI,
Owen Andersoneed707b2009-07-24 23:12:02 +00002891 ConstantInt::get(I.getType(), 1)),
Owen Andersond672ecb2009-07-03 00:17:18 +00002892 Op0I->getOperand(0));
Chris Lattneracf4e072007-04-02 05:42:22 +00002893 } else if (RHS->getValue().isSignBit()) {
Chris Lattner5c6e2db2007-04-02 05:36:22 +00002894 // (X + C) ^ signbit -> (X + C + signbit)
Chris Lattner4de84762010-01-04 07:02:48 +00002895 Constant *C = ConstantInt::get(I.getContext(),
Owen Andersoneed707b2009-07-24 23:12:02 +00002896 RHS->getValue() + Op0CI->getValue());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002897 return BinaryOperator::CreateAdd(Op0I->getOperand(0), C);
Chris Lattnercd1d6d52007-04-02 05:48:58 +00002898
Chris Lattner7c4049c2004-01-12 19:35:11 +00002899 }
Chris Lattner02bd1b32006-02-26 19:57:54 +00002900 } else if (Op0I->getOpcode() == Instruction::Or) {
2901 // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
Reid Spencera03d45f2007-03-22 22:19:58 +00002902 if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue())) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00002903 Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
Chris Lattner02bd1b32006-02-26 19:57:54 +00002904 // Anything in both C1 and C2 is known to be zero, remove it from
2905 // NewRHS.
Owen Andersonbaf3c402009-07-29 18:55:55 +00002906 Constant *CommonBits = ConstantExpr::getAnd(Op0CI, RHS);
2907 NewRHS = ConstantExpr::getAnd(NewRHS,
2908 ConstantExpr::getNot(CommonBits));
Chris Lattner7a1e9242009-08-30 06:13:40 +00002909 Worklist.Add(Op0I);
Chris Lattner02bd1b32006-02-26 19:57:54 +00002910 I.setOperand(0, Op0I->getOperand(0));
2911 I.setOperand(1, NewRHS);
2912 return &I;
2913 }
Chris Lattnereca0c5c2003-07-23 21:37:07 +00002914 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00002915 }
Chris Lattner05bd1b22002-08-20 18:24:26 +00002916 }
Chris Lattner2eefe512004-04-09 19:05:30 +00002917
2918 // Try to fold constant and into select arguments.
2919 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner80f43d32010-01-04 07:53:58 +00002920 if (Instruction *R = FoldOpIntoSelect(I, SI))
Chris Lattner2eefe512004-04-09 19:05:30 +00002921 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00002922 if (isa<PHINode>(Op0))
2923 if (Instruction *NV = FoldOpIntoPhi(I))
2924 return NV;
Chris Lattner3f5b8772002-05-06 16:14:14 +00002925 }
2926
Dan Gohman186a6362009-08-12 16:04:34 +00002927 if (Value *X = dyn_castNotVal(Op0)) // ~A ^ A == -1
Chris Lattnera2881962003-02-18 19:28:33 +00002928 if (X == Op1)
Owen Andersona7235ea2009-07-31 20:28:14 +00002929 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00002930
Dan Gohman186a6362009-08-12 16:04:34 +00002931 if (Value *X = dyn_castNotVal(Op1)) // A ^ ~A == -1
Chris Lattnera2881962003-02-18 19:28:33 +00002932 if (X == Op0)
Owen Andersona7235ea2009-07-31 20:28:14 +00002933 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00002934
Chris Lattner318bf792007-03-18 22:51:34 +00002935
2936 BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1);
2937 if (Op1I) {
2938 Value *A, *B;
Dan Gohman4ae51262009-08-12 16:23:25 +00002939 if (match(Op1I, m_Or(m_Value(A), m_Value(B)))) {
Chris Lattner318bf792007-03-18 22:51:34 +00002940 if (A == Op0) { // B^(B|A) == (A|B)^B
Chris Lattner64daab52006-04-01 08:03:55 +00002941 Op1I->swapOperands();
Chris Lattnercb40a372003-03-10 18:24:17 +00002942 I.swapOperands();
2943 std::swap(Op0, Op1);
Chris Lattner318bf792007-03-18 22:51:34 +00002944 } else if (B == Op0) { // B^(A|B) == (A|B)^B
Chris Lattner64daab52006-04-01 08:03:55 +00002945 I.swapOperands(); // Simplified below.
Chris Lattnercb40a372003-03-10 18:24:17 +00002946 std::swap(Op0, Op1);
Misha Brukmanfd939082005-04-21 23:48:37 +00002947 }
Dan Gohman4ae51262009-08-12 16:23:25 +00002948 } else if (match(Op1I, m_Xor(m_Specific(Op0), m_Value(B)))) {
Chris Lattnercb504b92008-11-16 05:38:51 +00002949 return ReplaceInstUsesWith(I, B); // A^(A^B) == B
Dan Gohman4ae51262009-08-12 16:23:25 +00002950 } else if (match(Op1I, m_Xor(m_Value(A), m_Specific(Op0)))) {
Chris Lattnercb504b92008-11-16 05:38:51 +00002951 return ReplaceInstUsesWith(I, A); // A^(B^A) == B
Dan Gohman4ae51262009-08-12 16:23:25 +00002952 } else if (match(Op1I, m_And(m_Value(A), m_Value(B))) &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00002953 Op1I->hasOneUse()){
Chris Lattner6abbdf92007-04-01 05:36:37 +00002954 if (A == Op0) { // A^(A&B) -> A^(B&A)
Chris Lattner64daab52006-04-01 08:03:55 +00002955 Op1I->swapOperands();
Chris Lattner6abbdf92007-04-01 05:36:37 +00002956 std::swap(A, B);
2957 }
Chris Lattner318bf792007-03-18 22:51:34 +00002958 if (B == Op0) { // A^(B&A) -> (B&A)^A
Chris Lattner64daab52006-04-01 08:03:55 +00002959 I.swapOperands(); // Simplified below.
2960 std::swap(Op0, Op1);
2961 }
Chris Lattner26ca7e12004-02-16 03:54:20 +00002962 }
Chris Lattner318bf792007-03-18 22:51:34 +00002963 }
2964
2965 BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0);
2966 if (Op0I) {
2967 Value *A, *B;
Dan Gohman4ae51262009-08-12 16:23:25 +00002968 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00002969 Op0I->hasOneUse()) {
Chris Lattner318bf792007-03-18 22:51:34 +00002970 if (A == Op1) // (B|A)^B == (A|B)^B
2971 std::swap(A, B);
Chris Lattner74381062009-08-30 07:44:24 +00002972 if (B == Op1) // (A|B)^B == A & ~B
2973 return BinaryOperator::CreateAnd(A, Builder->CreateNot(Op1, "tmp"));
Dan Gohman4ae51262009-08-12 16:23:25 +00002974 } else if (match(Op0I, m_Xor(m_Specific(Op1), m_Value(B)))) {
Chris Lattnercb504b92008-11-16 05:38:51 +00002975 return ReplaceInstUsesWith(I, B); // (A^B)^A == B
Dan Gohman4ae51262009-08-12 16:23:25 +00002976 } else if (match(Op0I, m_Xor(m_Value(A), m_Specific(Op1)))) {
Chris Lattnercb504b92008-11-16 05:38:51 +00002977 return ReplaceInstUsesWith(I, A); // (B^A)^A == B
Dan Gohman4ae51262009-08-12 16:23:25 +00002978 } else if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00002979 Op0I->hasOneUse()){
Chris Lattner318bf792007-03-18 22:51:34 +00002980 if (A == Op1) // (A&B)^A -> (B&A)^A
2981 std::swap(A, B);
2982 if (B == Op1 && // (B&A)^A == ~B & A
Chris Lattnerae1ab392006-04-01 22:05:01 +00002983 !isa<ConstantInt>(Op1)) { // Canonical form is (B&C)^C
Chris Lattner74381062009-08-30 07:44:24 +00002984 return BinaryOperator::CreateAnd(Builder->CreateNot(A, "tmp"), Op1);
Chris Lattner64daab52006-04-01 08:03:55 +00002985 }
Chris Lattnercb40a372003-03-10 18:24:17 +00002986 }
Chris Lattner318bf792007-03-18 22:51:34 +00002987 }
2988
2989 // (X >> Z) ^ (Y >> Z) -> (X^Y) >> Z for all shifts.
2990 if (Op0I && Op1I && Op0I->isShift() &&
2991 Op0I->getOpcode() == Op1I->getOpcode() &&
2992 Op0I->getOperand(1) == Op1I->getOperand(1) &&
2993 (Op1I->hasOneUse() || Op1I->hasOneUse())) {
Chris Lattner74381062009-08-30 07:44:24 +00002994 Value *NewOp =
2995 Builder->CreateXor(Op0I->getOperand(0), Op1I->getOperand(0),
2996 Op0I->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002997 return BinaryOperator::Create(Op1I->getOpcode(), NewOp,
Chris Lattner318bf792007-03-18 22:51:34 +00002998 Op1I->getOperand(1));
2999 }
3000
3001 if (Op0I && Op1I) {
3002 Value *A, *B, *C, *D;
3003 // (A & B)^(A | B) -> A ^ B
Dan Gohman4ae51262009-08-12 16:23:25 +00003004 if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
3005 match(Op1I, m_Or(m_Value(C), m_Value(D)))) {
Chris Lattner318bf792007-03-18 22:51:34 +00003006 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003007 return BinaryOperator::CreateXor(A, B);
Chris Lattner318bf792007-03-18 22:51:34 +00003008 }
3009 // (A | B)^(A & B) -> A ^ B
Dan Gohman4ae51262009-08-12 16:23:25 +00003010 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
3011 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
Chris Lattner318bf792007-03-18 22:51:34 +00003012 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003013 return BinaryOperator::CreateXor(A, B);
Chris Lattner318bf792007-03-18 22:51:34 +00003014 }
3015
3016 // (A & B)^(C & D)
3017 if ((Op0I->hasOneUse() || Op1I->hasOneUse()) &&
Dan Gohman4ae51262009-08-12 16:23:25 +00003018 match(Op0I, m_And(m_Value(A), m_Value(B))) &&
3019 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
Chris Lattner318bf792007-03-18 22:51:34 +00003020 // (X & Y)^(X & Y) -> (Y^Z) & X
3021 Value *X = 0, *Y = 0, *Z = 0;
3022 if (A == C)
3023 X = A, Y = B, Z = D;
3024 else if (A == D)
3025 X = A, Y = B, Z = C;
3026 else if (B == C)
3027 X = B, Y = A, Z = D;
3028 else if (B == D)
3029 X = B, Y = A, Z = C;
3030
3031 if (X) {
Chris Lattner74381062009-08-30 07:44:24 +00003032 Value *NewOp = Builder->CreateXor(Y, Z, Op0->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003033 return BinaryOperator::CreateAnd(NewOp, X);
Chris Lattner318bf792007-03-18 22:51:34 +00003034 }
3035 }
3036 }
3037
Reid Spencere4d87aa2006-12-23 06:05:41 +00003038 // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
3039 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
Chris Lattnera317e042010-01-05 06:59:49 +00003040 if (ICmpInst *LHS = dyn_cast<ICmpInst>(I.getOperand(0)))
3041 if (PredicatesFoldable(LHS->getPredicate(), RHS->getPredicate())) {
3042 if (LHS->getOperand(0) == RHS->getOperand(1) &&
3043 LHS->getOperand(1) == RHS->getOperand(0))
3044 LHS->swapOperands();
3045 if (LHS->getOperand(0) == RHS->getOperand(0) &&
3046 LHS->getOperand(1) == RHS->getOperand(1)) {
3047 Value *Op0 = LHS->getOperand(0), *Op1 = LHS->getOperand(1);
3048 unsigned Code = getICmpCode(LHS) ^ getICmpCode(RHS);
3049 bool isSigned = LHS->isSigned() || RHS->isSigned();
3050 Value *RV = getICmpValue(isSigned, Code, Op0, Op1);
3051 if (Instruction *I = dyn_cast<Instruction>(RV))
3052 return I;
3053 // Otherwise, it's a constant boolean value.
3054 return ReplaceInstUsesWith(I, RV);
3055 }
3056 }
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003057
Chris Lattner6fc205f2006-05-05 06:39:07 +00003058 // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
Chris Lattner99c65742007-10-24 05:38:08 +00003059 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Chris Lattner6fc205f2006-05-05 06:39:07 +00003060 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00003061 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
3062 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner42a75512007-01-15 02:27:26 +00003063 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00003064 // Only do this if the casts both really cause code to be generated.
Reid Spencere4d87aa2006-12-23 06:05:41 +00003065 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
Chris Lattner80f43d32010-01-04 07:53:58 +00003066 I.getType()) &&
Reid Spencere4d87aa2006-12-23 06:05:41 +00003067 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
Chris Lattner80f43d32010-01-04 07:53:58 +00003068 I.getType())) {
Chris Lattner74381062009-08-30 07:44:24 +00003069 Value *NewOp = Builder->CreateXor(Op0C->getOperand(0),
3070 Op1C->getOperand(0), I.getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003071 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00003072 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00003073 }
Chris Lattner99c65742007-10-24 05:38:08 +00003074 }
Nick Lewycky517e1f52008-05-31 19:01:33 +00003075
Chris Lattner7e708292002-06-25 16:13:24 +00003076 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00003077}
3078
Chris Lattner3f5b8772002-05-06 16:14:14 +00003079
Reid Spencer832254e2007-02-02 02:16:23 +00003080Instruction *InstCombiner::visitShl(BinaryOperator &I) {
3081 return commonShiftTransforms(I);
3082}
3083
3084Instruction *InstCombiner::visitLShr(BinaryOperator &I) {
3085 return commonShiftTransforms(I);
3086}
3087
3088Instruction *InstCombiner::visitAShr(BinaryOperator &I) {
Chris Lattner348f6652007-12-06 01:59:46 +00003089 if (Instruction *R = commonShiftTransforms(I))
3090 return R;
3091
3092 Value *Op0 = I.getOperand(0);
3093
3094 // ashr int -1, X = -1 (for any arithmetic shift rights of ~0)
3095 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
3096 if (CSI->isAllOnesValue())
3097 return ReplaceInstUsesWith(I, CSI);
Dan Gohman0001e562009-02-24 02:00:40 +00003098
Dan Gohmanc6ac3222009-06-16 19:55:29 +00003099 // See if we can turn a signed shr into an unsigned shr.
3100 if (MaskedValueIsZero(Op0,
3101 APInt::getSignBit(I.getType()->getScalarSizeInBits())))
3102 return BinaryOperator::CreateLShr(Op0, I.getOperand(1));
3103
3104 // Arithmetic shifting an all-sign-bit value is a no-op.
3105 unsigned NumSignBits = ComputeNumSignBits(Op0);
3106 if (NumSignBits == Op0->getType()->getScalarSizeInBits())
3107 return ReplaceInstUsesWith(I, Op0);
Dan Gohman0001e562009-02-24 02:00:40 +00003108
Chris Lattner348f6652007-12-06 01:59:46 +00003109 return 0;
Reid Spencer832254e2007-02-02 02:16:23 +00003110}
3111
3112Instruction *InstCombiner::commonShiftTransforms(BinaryOperator &I) {
3113 assert(I.getOperand(1)->getType() == I.getOperand(0)->getType());
Chris Lattner7e708292002-06-25 16:13:24 +00003114 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00003115
3116 // shl X, 0 == X and shr X, 0 == X
3117 // shl 0, X == 0 and shr 0, X == 0
Owen Andersona7235ea2009-07-31 20:28:14 +00003118 if (Op1 == Constant::getNullValue(Op1->getType()) ||
3119 Op0 == Constant::getNullValue(Op0->getType()))
Chris Lattner233f7dc2002-08-12 21:17:25 +00003120 return ReplaceInstUsesWith(I, Op0);
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00003121
Reid Spencere4d87aa2006-12-23 06:05:41 +00003122 if (isa<UndefValue>(Op0)) {
3123 if (I.getOpcode() == Instruction::AShr) // undef >>s X -> undef
Chris Lattner79a564c2004-10-16 23:28:04 +00003124 return ReplaceInstUsesWith(I, Op0);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003125 else // undef << X -> 0, undef >>u X -> 0
Owen Andersona7235ea2009-07-31 20:28:14 +00003126 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00003127 }
3128 if (isa<UndefValue>(Op1)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00003129 if (I.getOpcode() == Instruction::AShr) // X >>s undef -> X
3130 return ReplaceInstUsesWith(I, Op0);
3131 else // X << undef, X >>u undef -> 0
Owen Andersona7235ea2009-07-31 20:28:14 +00003132 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00003133 }
3134
Dan Gohman9004c8a2009-05-21 02:28:33 +00003135 // See if we can fold away this shift.
Dan Gohman6de29f82009-06-15 22:12:54 +00003136 if (SimplifyDemandedInstructionBits(I))
Dan Gohman9004c8a2009-05-21 02:28:33 +00003137 return &I;
3138
Chris Lattner2eefe512004-04-09 19:05:30 +00003139 // Try to fold constant and into select arguments.
3140 if (isa<Constant>(Op0))
3141 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner80f43d32010-01-04 07:53:58 +00003142 if (Instruction *R = FoldOpIntoSelect(I, SI))
Chris Lattner2eefe512004-04-09 19:05:30 +00003143 return R;
3144
Reid Spencerb83eb642006-10-20 07:07:24 +00003145 if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
Reid Spencerc5b206b2006-12-31 05:48:39 +00003146 if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
3147 return Res;
Chris Lattner4d5542c2006-01-06 07:12:35 +00003148 return 0;
3149}
3150
Reid Spencerb83eb642006-10-20 07:07:24 +00003151Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
Reid Spencer832254e2007-02-02 02:16:23 +00003152 BinaryOperator &I) {
Chris Lattner4598c942009-01-31 08:24:16 +00003153 bool isLeftShift = I.getOpcode() == Instruction::Shl;
Chris Lattner4d5542c2006-01-06 07:12:35 +00003154
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00003155 // See if we can simplify any instructions used by the instruction whose sole
3156 // purpose is to compute bits we don't care about.
Dan Gohmanc6ac3222009-06-16 19:55:29 +00003157 uint32_t TypeBits = Op0->getType()->getScalarSizeInBits();
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00003158
Dan Gohmana119de82009-06-14 23:30:43 +00003159 // shl i32 X, 32 = 0 and srl i8 Y, 9 = 0, ... just don't eliminate
3160 // a signed shift.
Chris Lattner4d5542c2006-01-06 07:12:35 +00003161 //
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003162 if (Op1->uge(TypeBits)) {
Chris Lattner0737c242007-02-02 05:29:55 +00003163 if (I.getOpcode() != Instruction::AShr)
Owen Andersona7235ea2009-07-31 20:28:14 +00003164 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
Chris Lattner4d5542c2006-01-06 07:12:35 +00003165 else {
Owen Andersoneed707b2009-07-24 23:12:02 +00003166 I.setOperand(1, ConstantInt::get(I.getType(), TypeBits-1));
Chris Lattner4d5542c2006-01-06 07:12:35 +00003167 return &I;
Chris Lattner8adac752004-02-23 20:30:06 +00003168 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00003169 }
3170
3171 // ((X*C1) << C2) == (X * (C1 << C2))
3172 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
3173 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
3174 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003175 return BinaryOperator::CreateMul(BO->getOperand(0),
Owen Andersonbaf3c402009-07-29 18:55:55 +00003176 ConstantExpr::getShl(BOOp, Op1));
Chris Lattner4d5542c2006-01-06 07:12:35 +00003177
3178 // Try to fold constant and into select arguments.
3179 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner80f43d32010-01-04 07:53:58 +00003180 if (Instruction *R = FoldOpIntoSelect(I, SI))
Chris Lattner4d5542c2006-01-06 07:12:35 +00003181 return R;
3182 if (isa<PHINode>(Op0))
3183 if (Instruction *NV = FoldOpIntoPhi(I))
3184 return NV;
3185
Chris Lattner8999dd32007-12-22 09:07:47 +00003186 // Fold shift2(trunc(shift1(x,c1)), c2) -> trunc(shift2(shift1(x,c1),c2))
3187 if (TruncInst *TI = dyn_cast<TruncInst>(Op0)) {
3188 Instruction *TrOp = dyn_cast<Instruction>(TI->getOperand(0));
3189 // If 'shift2' is an ashr, we would have to get the sign bit into a funny
3190 // place. Don't try to do this transformation in this case. Also, we
3191 // require that the input operand is a shift-by-constant so that we have
3192 // confidence that the shifts will get folded together. We could do this
3193 // xform in more cases, but it is unlikely to be profitable.
3194 if (TrOp && I.isLogicalShift() && TrOp->isShift() &&
3195 isa<ConstantInt>(TrOp->getOperand(1))) {
3196 // Okay, we'll do this xform. Make the shift of shift.
Owen Andersonbaf3c402009-07-29 18:55:55 +00003197 Constant *ShAmt = ConstantExpr::getZExt(Op1, TrOp->getType());
Chris Lattner74381062009-08-30 07:44:24 +00003198 // (shift2 (shift1 & 0x00FF), c2)
3199 Value *NSh = Builder->CreateBinOp(I.getOpcode(), TrOp, ShAmt,I.getName());
Chris Lattner8999dd32007-12-22 09:07:47 +00003200
3201 // For logical shifts, the truncation has the effect of making the high
3202 // part of the register be zeros. Emulate this by inserting an AND to
3203 // clear the top bits as needed. This 'and' will usually be zapped by
3204 // other xforms later if dead.
Dan Gohmanc6ac3222009-06-16 19:55:29 +00003205 unsigned SrcSize = TrOp->getType()->getScalarSizeInBits();
3206 unsigned DstSize = TI->getType()->getScalarSizeInBits();
Chris Lattner8999dd32007-12-22 09:07:47 +00003207 APInt MaskV(APInt::getLowBitsSet(SrcSize, DstSize));
3208
3209 // The mask we constructed says what the trunc would do if occurring
3210 // between the shifts. We want to know the effect *after* the second
3211 // shift. We know that it is a logical shift by a constant, so adjust the
3212 // mask as appropriate.
3213 if (I.getOpcode() == Instruction::Shl)
3214 MaskV <<= Op1->getZExtValue();
3215 else {
3216 assert(I.getOpcode() == Instruction::LShr && "Unknown logical shift");
3217 MaskV = MaskV.lshr(Op1->getZExtValue());
3218 }
3219
Chris Lattner74381062009-08-30 07:44:24 +00003220 // shift1 & 0x00FF
Chris Lattner4de84762010-01-04 07:02:48 +00003221 Value *And = Builder->CreateAnd(NSh,
3222 ConstantInt::get(I.getContext(), MaskV),
Chris Lattner74381062009-08-30 07:44:24 +00003223 TI->getName());
Chris Lattner8999dd32007-12-22 09:07:47 +00003224
3225 // Return the value truncated to the interesting size.
3226 return new TruncInst(And, I.getType());
3227 }
3228 }
3229
Chris Lattner4d5542c2006-01-06 07:12:35 +00003230 if (Op0->hasOneUse()) {
Chris Lattner4d5542c2006-01-06 07:12:35 +00003231 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
3232 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
3233 Value *V1, *V2;
3234 ConstantInt *CC;
3235 switch (Op0BO->getOpcode()) {
Chris Lattner11021cb2005-09-18 05:12:10 +00003236 default: break;
3237 case Instruction::Add:
3238 case Instruction::And:
3239 case Instruction::Or:
Reid Spencera07cb7d2007-02-02 14:41:37 +00003240 case Instruction::Xor: {
Chris Lattner11021cb2005-09-18 05:12:10 +00003241 // These operators commute.
3242 // Turn (Y + (X >> C)) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00003243 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00003244 match(Op0BO->getOperand(1), m_Shr(m_Value(V1),
Chris Lattnerf925cbd2009-08-30 18:50:58 +00003245 m_Specific(Op1)))) {
3246 Value *YS = // (Y << C)
3247 Builder->CreateShl(Op0BO->getOperand(0), Op1, Op0BO->getName());
3248 // (X + (Y << C))
3249 Value *X = Builder->CreateBinOp(Op0BO->getOpcode(), YS, V1,
3250 Op0BO->getOperand(1)->getName());
Zhou Sheng302748d2007-03-30 17:20:39 +00003251 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
Chris Lattner4de84762010-01-04 07:02:48 +00003252 return BinaryOperator::CreateAnd(X, ConstantInt::get(I.getContext(),
Zhou Sheng90b96812007-03-30 05:45:18 +00003253 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
Chris Lattner150f12a2005-09-18 06:30:59 +00003254 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00003255
Chris Lattner150f12a2005-09-18 06:30:59 +00003256 // Turn (Y + ((X >> C) & CC)) << C -> ((X & (CC << C)) + (Y << C))
Reid Spencera07cb7d2007-02-02 14:41:37 +00003257 Value *Op0BOOp1 = Op0BO->getOperand(1);
Chris Lattner3c698492007-03-05 00:11:19 +00003258 if (isLeftShift && Op0BOOp1->hasOneUse() &&
Reid Spencera07cb7d2007-02-02 14:41:37 +00003259 match(Op0BOOp1,
Chris Lattnercb504b92008-11-16 05:38:51 +00003260 m_And(m_Shr(m_Value(V1), m_Specific(Op1)),
Dan Gohman4ae51262009-08-12 16:23:25 +00003261 m_ConstantInt(CC))) &&
Chris Lattnercb504b92008-11-16 05:38:51 +00003262 cast<BinaryOperator>(Op0BOOp1)->getOperand(0)->hasOneUse()) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +00003263 Value *YS = // (Y << C)
3264 Builder->CreateShl(Op0BO->getOperand(0), Op1,
3265 Op0BO->getName());
3266 // X & (CC << C)
3267 Value *XM = Builder->CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
3268 V1->getName()+".mask");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003269 return BinaryOperator::Create(Op0BO->getOpcode(), YS, XM);
Chris Lattner150f12a2005-09-18 06:30:59 +00003270 }
Reid Spencera07cb7d2007-02-02 14:41:37 +00003271 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00003272
Reid Spencera07cb7d2007-02-02 14:41:37 +00003273 // FALL THROUGH.
3274 case Instruction::Sub: {
Chris Lattner11021cb2005-09-18 05:12:10 +00003275 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00003276 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00003277 match(Op0BO->getOperand(0), m_Shr(m_Value(V1),
Dan Gohman4ae51262009-08-12 16:23:25 +00003278 m_Specific(Op1)))) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +00003279 Value *YS = // (Y << C)
3280 Builder->CreateShl(Op0BO->getOperand(1), Op1, Op0BO->getName());
3281 // (X + (Y << C))
3282 Value *X = Builder->CreateBinOp(Op0BO->getOpcode(), V1, YS,
3283 Op0BO->getOperand(0)->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 Lattner13d4ab42006-05-31 21:14:00 +00003289 // Turn (((X >> C)&CC) + Y) << C -> (X + (Y << C)) & (CC << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00003290 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
3291 match(Op0BO->getOperand(0),
3292 m_And(m_Shr(m_Value(V1), m_Value(V2)),
Dan Gohman4ae51262009-08-12 16:23:25 +00003293 m_ConstantInt(CC))) && V2 == Op1 &&
Chris Lattner9a4cacb2006-02-09 07:41:14 +00003294 cast<BinaryOperator>(Op0BO->getOperand(0))
3295 ->getOperand(0)->hasOneUse()) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +00003296 Value *YS = // (Y << C)
3297 Builder->CreateShl(Op0BO->getOperand(1), Op1, Op0BO->getName());
3298 // X & (CC << C)
3299 Value *XM = Builder->CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
3300 V1->getName()+".mask");
Chris Lattner150f12a2005-09-18 06:30:59 +00003301
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003302 return BinaryOperator::Create(Op0BO->getOpcode(), XM, YS);
Chris Lattner150f12a2005-09-18 06:30:59 +00003303 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00003304
Chris Lattner11021cb2005-09-18 05:12:10 +00003305 break;
Reid Spencera07cb7d2007-02-02 14:41:37 +00003306 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00003307 }
3308
3309
3310 // If the operand is an bitwise operator with a constant RHS, and the
3311 // shift is the only use, we can pull it out of the shift.
3312 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
3313 bool isValid = true; // Valid only for And, Or, Xor
3314 bool highBitSet = false; // Transform if high bit of constant set?
3315
3316 switch (Op0BO->getOpcode()) {
Chris Lattnerdf17af12003-08-12 21:53:41 +00003317 default: isValid = false; break; // Do not perform transform!
Chris Lattner1f7e1602004-10-08 03:46:20 +00003318 case Instruction::Add:
3319 isValid = isLeftShift;
3320 break;
Chris Lattnerdf17af12003-08-12 21:53:41 +00003321 case Instruction::Or:
3322 case Instruction::Xor:
3323 highBitSet = false;
3324 break;
3325 case Instruction::And:
3326 highBitSet = true;
3327 break;
Chris Lattner4d5542c2006-01-06 07:12:35 +00003328 }
3329
3330 // If this is a signed shift right, and the high bit is modified
3331 // by the logical operation, do not perform the transformation.
3332 // The highBitSet boolean indicates the value of the high bit of
3333 // the constant which would cause it to be modified for this
3334 // operation.
3335 //
Chris Lattnerc95ba442007-12-06 06:25:04 +00003336 if (isValid && I.getOpcode() == Instruction::AShr)
Zhou Shenge9e03f62007-03-28 15:02:20 +00003337 isValid = Op0C->getValue()[TypeBits-1] == highBitSet;
Chris Lattner4d5542c2006-01-06 07:12:35 +00003338
3339 if (isValid) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00003340 Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
Chris Lattner4d5542c2006-01-06 07:12:35 +00003341
Chris Lattnerf925cbd2009-08-30 18:50:58 +00003342 Value *NewShift =
3343 Builder->CreateBinOp(I.getOpcode(), Op0BO->getOperand(0), Op1);
Chris Lattner6934a042007-02-11 01:23:03 +00003344 NewShift->takeName(Op0BO);
Chris Lattner4d5542c2006-01-06 07:12:35 +00003345
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003346 return BinaryOperator::Create(Op0BO->getOpcode(), NewShift,
Chris Lattner4d5542c2006-01-06 07:12:35 +00003347 NewRHS);
3348 }
3349 }
3350 }
3351 }
3352
Chris Lattnerad0124c2006-01-06 07:52:12 +00003353 // Find out if this is a shift of a shift by a constant.
Reid Spencer832254e2007-02-02 02:16:23 +00003354 BinaryOperator *ShiftOp = dyn_cast<BinaryOperator>(Op0);
3355 if (ShiftOp && !ShiftOp->isShift())
3356 ShiftOp = 0;
Chris Lattnerad0124c2006-01-06 07:52:12 +00003357
Reid Spencerb83eb642006-10-20 07:07:24 +00003358 if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
Reid Spencerb83eb642006-10-20 07:07:24 +00003359 ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003360 uint32_t ShiftAmt1 = ShiftAmt1C->getLimitedValue(TypeBits);
3361 uint32_t ShiftAmt2 = Op1->getLimitedValue(TypeBits);
Chris Lattnerb87056f2007-02-05 00:57:54 +00003362 assert(ShiftAmt2 != 0 && "Should have been simplified earlier");
3363 if (ShiftAmt1 == 0) return 0; // Will be simplified in the future.
3364 Value *X = ShiftOp->getOperand(0);
Chris Lattnerad0124c2006-01-06 07:52:12 +00003365
Zhou Sheng4351c642007-04-02 08:20:41 +00003366 uint32_t AmtSum = ShiftAmt1+ShiftAmt2; // Fold into one big shift.
Chris Lattnerb87056f2007-02-05 00:57:54 +00003367
3368 const IntegerType *Ty = cast<IntegerType>(I.getType());
3369
3370 // Check for (X << c1) << c2 and (X >> c1) >> c2
Chris Lattner7f3da2d2007-02-03 23:28:07 +00003371 if (I.getOpcode() == ShiftOp->getOpcode()) {
Chris Lattner344c7c52009-03-20 22:41:15 +00003372 // If this is oversized composite shift, then unsigned shifts get 0, ashr
3373 // saturates.
3374 if (AmtSum >= TypeBits) {
3375 if (I.getOpcode() != Instruction::AShr)
Owen Andersona7235ea2009-07-31 20:28:14 +00003376 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner344c7c52009-03-20 22:41:15 +00003377 AmtSum = TypeBits-1; // Saturate to 31 for i32 ashr.
3378 }
3379
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003380 return BinaryOperator::Create(I.getOpcode(), X,
Owen Andersoneed707b2009-07-24 23:12:02 +00003381 ConstantInt::get(Ty, AmtSum));
Chris Lattnerf925cbd2009-08-30 18:50:58 +00003382 }
3383
3384 if (ShiftOp->getOpcode() == Instruction::LShr &&
3385 I.getOpcode() == Instruction::AShr) {
Chris Lattner344c7c52009-03-20 22:41:15 +00003386 if (AmtSum >= TypeBits)
Owen Andersona7235ea2009-07-31 20:28:14 +00003387 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner344c7c52009-03-20 22:41:15 +00003388
Chris Lattnerb87056f2007-02-05 00:57:54 +00003389 // ((X >>u C1) >>s C2) -> (X >>u (C1+C2)) since C1 != 0.
Owen Andersoneed707b2009-07-24 23:12:02 +00003390 return BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, AmtSum));
Chris Lattnerf925cbd2009-08-30 18:50:58 +00003391 }
3392
3393 if (ShiftOp->getOpcode() == Instruction::AShr &&
3394 I.getOpcode() == Instruction::LShr) {
Chris Lattnerb87056f2007-02-05 00:57:54 +00003395 // ((X >>s C1) >>u C2) -> ((X >>s (C1+C2)) & mask) since C1 != 0.
Chris Lattner344c7c52009-03-20 22:41:15 +00003396 if (AmtSum >= TypeBits)
3397 AmtSum = TypeBits-1;
3398
Chris Lattnerf925cbd2009-08-30 18:50:58 +00003399 Value *Shift = Builder->CreateAShr(X, ConstantInt::get(Ty, AmtSum));
Chris Lattnerb87056f2007-02-05 00:57:54 +00003400
Zhou Shenge9e03f62007-03-28 15:02:20 +00003401 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Chris Lattner4de84762010-01-04 07:02:48 +00003402 return BinaryOperator::CreateAnd(Shift,
3403 ConstantInt::get(I.getContext(), Mask));
Chris Lattnerad0124c2006-01-06 07:52:12 +00003404 }
3405
Chris Lattnerb87056f2007-02-05 00:57:54 +00003406 // Okay, if we get here, one shift must be left, and the other shift must be
3407 // right. See if the amounts are equal.
3408 if (ShiftAmt1 == ShiftAmt2) {
3409 // If we have ((X >>? C) << C), turn this into X & (-1 << C).
3410 if (I.getOpcode() == Instruction::Shl) {
Reid Spencer55702aa2007-03-25 21:11:44 +00003411 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt1));
Chris Lattner4de84762010-01-04 07:02:48 +00003412 return BinaryOperator::CreateAnd(X,
3413 ConstantInt::get(I.getContext(),Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00003414 }
3415 // If we have ((X << C) >>u C), turn this into X & (-1 >>u C).
3416 if (I.getOpcode() == Instruction::LShr) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003417 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt1));
Chris Lattner4de84762010-01-04 07:02:48 +00003418 return BinaryOperator::CreateAnd(X,
3419 ConstantInt::get(I.getContext(), Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00003420 }
3421 // We can simplify ((X << C) >>s C) into a trunc + sext.
3422 // NOTE: we could do this for any C, but that would make 'unusual' integer
3423 // types. For now, just stick to ones well-supported by the code
3424 // generators.
3425 const Type *SExtType = 0;
3426 switch (Ty->getBitWidth() - ShiftAmt1) {
Zhou Shenge9e03f62007-03-28 15:02:20 +00003427 case 1 :
3428 case 8 :
3429 case 16 :
3430 case 32 :
3431 case 64 :
3432 case 128:
Chris Lattner4de84762010-01-04 07:02:48 +00003433 SExtType = IntegerType::get(I.getContext(),
3434 Ty->getBitWidth() - ShiftAmt1);
Zhou Shenge9e03f62007-03-28 15:02:20 +00003435 break;
Chris Lattnerb87056f2007-02-05 00:57:54 +00003436 default: break;
3437 }
Chris Lattnerf925cbd2009-08-30 18:50:58 +00003438 if (SExtType)
3439 return new SExtInst(Builder->CreateTrunc(X, SExtType, "sext"), Ty);
Chris Lattnerb87056f2007-02-05 00:57:54 +00003440 // Otherwise, we can't handle it yet.
3441 } else if (ShiftAmt1 < ShiftAmt2) {
Zhou Sheng4351c642007-04-02 08:20:41 +00003442 uint32_t ShiftDiff = ShiftAmt2-ShiftAmt1;
Chris Lattnerad0124c2006-01-06 07:52:12 +00003443
Chris Lattnerb0b991a2007-02-05 05:57:49 +00003444 // (X >>? C1) << C2 --> X << (C2-C1) & (-1 << C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00003445 if (I.getOpcode() == Instruction::Shl) {
3446 assert(ShiftOp->getOpcode() == Instruction::LShr ||
3447 ShiftOp->getOpcode() == Instruction::AShr);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00003448 Value *Shift = Builder->CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
Chris Lattnere8d56c52006-01-07 01:32:28 +00003449
Reid Spencer55702aa2007-03-25 21:11:44 +00003450 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersoneed707b2009-07-24 23:12:02 +00003451 return BinaryOperator::CreateAnd(Shift,
Chris Lattner4de84762010-01-04 07:02:48 +00003452 ConstantInt::get(I.getContext(),Mask));
Chris Lattnerad0124c2006-01-06 07:52:12 +00003453 }
Chris Lattnerb87056f2007-02-05 00:57:54 +00003454
Chris Lattnerb0b991a2007-02-05 05:57:49 +00003455 // (X << C1) >>u C2 --> X >>u (C2-C1) & (-1 >> C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00003456 if (I.getOpcode() == Instruction::LShr) {
3457 assert(ShiftOp->getOpcode() == Instruction::Shl);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00003458 Value *Shift = Builder->CreateLShr(X, ConstantInt::get(Ty, ShiftDiff));
Chris Lattnerad0124c2006-01-06 07:52:12 +00003459
Reid Spencerd5e30f02007-03-26 17:18:58 +00003460 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersoneed707b2009-07-24 23:12:02 +00003461 return BinaryOperator::CreateAnd(Shift,
Chris Lattner4de84762010-01-04 07:02:48 +00003462 ConstantInt::get(I.getContext(),Mask));
Chris Lattner11021cb2005-09-18 05:12:10 +00003463 }
Chris Lattnerb87056f2007-02-05 00:57:54 +00003464
3465 // We can't handle (X << C1) >>s C2, it shifts arbitrary bits in.
3466 } else {
3467 assert(ShiftAmt2 < ShiftAmt1);
Zhou Sheng4351c642007-04-02 08:20:41 +00003468 uint32_t ShiftDiff = ShiftAmt1-ShiftAmt2;
Chris Lattnerb87056f2007-02-05 00:57:54 +00003469
Chris Lattnerb0b991a2007-02-05 05:57:49 +00003470 // (X >>? C1) << C2 --> X >>? (C1-C2) & (-1 << C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00003471 if (I.getOpcode() == Instruction::Shl) {
3472 assert(ShiftOp->getOpcode() == Instruction::LShr ||
3473 ShiftOp->getOpcode() == Instruction::AShr);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00003474 Value *Shift = Builder->CreateBinOp(ShiftOp->getOpcode(), X,
3475 ConstantInt::get(Ty, ShiftDiff));
Chris Lattnerb87056f2007-02-05 00:57:54 +00003476
Reid Spencer55702aa2007-03-25 21:11:44 +00003477 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersoneed707b2009-07-24 23:12:02 +00003478 return BinaryOperator::CreateAnd(Shift,
Chris Lattner4de84762010-01-04 07:02:48 +00003479 ConstantInt::get(I.getContext(),Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00003480 }
3481
Chris Lattnerb0b991a2007-02-05 05:57:49 +00003482 // (X << C1) >>u C2 --> X << (C1-C2) & (-1 >> C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00003483 if (I.getOpcode() == Instruction::LShr) {
3484 assert(ShiftOp->getOpcode() == Instruction::Shl);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00003485 Value *Shift = Builder->CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
Chris Lattnerb87056f2007-02-05 00:57:54 +00003486
Reid Spencer68d27cf2007-03-26 23:45:51 +00003487 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersoneed707b2009-07-24 23:12:02 +00003488 return BinaryOperator::CreateAnd(Shift,
Chris Lattner4de84762010-01-04 07:02:48 +00003489 ConstantInt::get(I.getContext(),Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00003490 }
3491
3492 // We can't handle (X << C1) >>a C2, it shifts arbitrary bits in.
Chris Lattner6e7ba452005-01-01 16:22:27 +00003493 }
Chris Lattnerad0124c2006-01-06 07:52:12 +00003494 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00003495 return 0;
3496}
3497
Chris Lattnera1be5662002-05-02 17:06:02 +00003498
Reid Spencer3da59db2006-11-27 01:05:10 +00003499
Chris Lattner46cd5a12009-01-09 05:44:56 +00003500/// FindElementAtOffset - Given a type and a constant offset, determine whether
3501/// or not there is a sequence of GEP indices into the type that will land us at
Chris Lattner3914f722009-01-24 01:00:13 +00003502/// the specified offset. If so, fill them into NewIndices and return the
3503/// resultant element type, otherwise return null.
Chris Lattner80f43d32010-01-04 07:53:58 +00003504const Type *InstCombiner::FindElementAtOffset(const Type *Ty, int64_t Offset,
3505 SmallVectorImpl<Value*> &NewIndices) {
Dan Gohmance9fe9f2009-07-21 23:21:54 +00003506 if (!TD) return 0;
Chris Lattner3914f722009-01-24 01:00:13 +00003507 if (!Ty->isSized()) return 0;
Chris Lattner46cd5a12009-01-09 05:44:56 +00003508
3509 // Start with the index over the outer type. Note that the type size
3510 // might be zero (even if the offset isn't zero) if the indexed type
3511 // is something like [0 x {int, int}]
Chris Lattner4de84762010-01-04 07:02:48 +00003512 const Type *IntPtrTy = TD->getIntPtrType(Ty->getContext());
Chris Lattner46cd5a12009-01-09 05:44:56 +00003513 int64_t FirstIdx = 0;
Duncan Sands777d2302009-05-09 07:06:46 +00003514 if (int64_t TySize = TD->getTypeAllocSize(Ty)) {
Chris Lattner46cd5a12009-01-09 05:44:56 +00003515 FirstIdx = Offset/TySize;
Chris Lattner31a69cb2009-01-11 20:41:36 +00003516 Offset -= FirstIdx*TySize;
Chris Lattner46cd5a12009-01-09 05:44:56 +00003517
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00003518 // Handle hosts where % returns negative instead of values [0..TySize).
Chris Lattner46cd5a12009-01-09 05:44:56 +00003519 if (Offset < 0) {
3520 --FirstIdx;
3521 Offset += TySize;
3522 assert(Offset >= 0);
3523 }
3524 assert((uint64_t)Offset < (uint64_t)TySize && "Out of range offset");
3525 }
3526
Owen Andersoneed707b2009-07-24 23:12:02 +00003527 NewIndices.push_back(ConstantInt::get(IntPtrTy, FirstIdx));
Chris Lattner46cd5a12009-01-09 05:44:56 +00003528
3529 // Index into the types. If we fail, set OrigBase to null.
3530 while (Offset) {
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00003531 // Indexing into tail padding between struct/array elements.
3532 if (uint64_t(Offset*8) >= TD->getTypeSizeInBits(Ty))
Chris Lattner3914f722009-01-24 01:00:13 +00003533 return 0;
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00003534
Chris Lattner46cd5a12009-01-09 05:44:56 +00003535 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
3536 const StructLayout *SL = TD->getStructLayout(STy);
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00003537 assert(Offset < (int64_t)SL->getSizeInBytes() &&
3538 "Offset must stay within the indexed type");
3539
Chris Lattner46cd5a12009-01-09 05:44:56 +00003540 unsigned Elt = SL->getElementContainingOffset(Offset);
Chris Lattner4de84762010-01-04 07:02:48 +00003541 NewIndices.push_back(ConstantInt::get(Type::getInt32Ty(Ty->getContext()),
3542 Elt));
Chris Lattner46cd5a12009-01-09 05:44:56 +00003543
3544 Offset -= SL->getElementOffset(Elt);
3545 Ty = STy->getElementType(Elt);
Chris Lattner1c412d92009-01-11 20:23:52 +00003546 } else if (const ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
Duncan Sands777d2302009-05-09 07:06:46 +00003547 uint64_t EltSize = TD->getTypeAllocSize(AT->getElementType());
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00003548 assert(EltSize && "Cannot index into a zero-sized array");
Owen Andersoneed707b2009-07-24 23:12:02 +00003549 NewIndices.push_back(ConstantInt::get(IntPtrTy,Offset/EltSize));
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00003550 Offset %= EltSize;
Chris Lattner1c412d92009-01-11 20:23:52 +00003551 Ty = AT->getElementType();
Chris Lattner46cd5a12009-01-09 05:44:56 +00003552 } else {
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00003553 // Otherwise, we can't index into the middle of this atomic type, bail.
Chris Lattner3914f722009-01-24 01:00:13 +00003554 return 0;
Chris Lattner46cd5a12009-01-09 05:44:56 +00003555 }
3556 }
3557
Chris Lattner3914f722009-01-24 01:00:13 +00003558 return Ty;
Chris Lattner46cd5a12009-01-09 05:44:56 +00003559}
3560
Chris Lattner8a2a3112001-12-14 16:52:21 +00003561
Dan Gohmaneee962e2008-04-10 18:43:06 +00003562/// EnforceKnownAlignment - If the specified pointer points to an object that
3563/// we control, modify the object's alignment to PrefAlign. This isn't
3564/// often possible though. If alignment is important, a more reliable approach
3565/// is to simply align all global variables and allocation instructions to
3566/// their preferred alignment from the beginning.
3567///
3568static unsigned EnforceKnownAlignment(Value *V,
3569 unsigned Align, unsigned PrefAlign) {
Chris Lattnerf2369f22007-08-09 19:05:49 +00003570
Dan Gohmaneee962e2008-04-10 18:43:06 +00003571 User *U = dyn_cast<User>(V);
3572 if (!U) return Align;
3573
Dan Gohmanca178902009-07-17 20:47:02 +00003574 switch (Operator::getOpcode(U)) {
Dan Gohmaneee962e2008-04-10 18:43:06 +00003575 default: break;
3576 case Instruction::BitCast:
3577 return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
3578 case Instruction::GetElementPtr: {
Chris Lattner95a959d2006-03-06 20:18:44 +00003579 // If all indexes are zero, it is just the alignment of the base pointer.
3580 bool AllZeroOperands = true;
Gabor Greif52ed3632008-06-12 21:51:29 +00003581 for (User::op_iterator i = U->op_begin() + 1, e = U->op_end(); i != e; ++i)
Gabor Greif177dd3f2008-06-12 21:37:33 +00003582 if (!isa<Constant>(*i) ||
3583 !cast<Constant>(*i)->isNullValue()) {
Chris Lattner95a959d2006-03-06 20:18:44 +00003584 AllZeroOperands = false;
3585 break;
3586 }
Chris Lattnerf2369f22007-08-09 19:05:49 +00003587
3588 if (AllZeroOperands) {
3589 // Treat this like a bitcast.
Dan Gohmaneee962e2008-04-10 18:43:06 +00003590 return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
Chris Lattnerf2369f22007-08-09 19:05:49 +00003591 }
Dan Gohmaneee962e2008-04-10 18:43:06 +00003592 break;
Chris Lattner95a959d2006-03-06 20:18:44 +00003593 }
Dan Gohmaneee962e2008-04-10 18:43:06 +00003594 }
3595
3596 if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
3597 // If there is a large requested alignment and we can, bump up the alignment
3598 // of the global.
3599 if (!GV->isDeclaration()) {
Dan Gohmanecd0fb52009-02-16 23:02:21 +00003600 if (GV->getAlignment() >= PrefAlign)
3601 Align = GV->getAlignment();
3602 else {
3603 GV->setAlignment(PrefAlign);
3604 Align = PrefAlign;
3605 }
Dan Gohmaneee962e2008-04-10 18:43:06 +00003606 }
Chris Lattner42ebefa2009-09-27 21:42:46 +00003607 } else if (AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
3608 // If there is a requested alignment and if this is an alloca, round up.
3609 if (AI->getAlignment() >= PrefAlign)
3610 Align = AI->getAlignment();
3611 else {
3612 AI->setAlignment(PrefAlign);
3613 Align = PrefAlign;
Dan Gohmaneee962e2008-04-10 18:43:06 +00003614 }
3615 }
3616
3617 return Align;
3618}
3619
3620/// GetOrEnforceKnownAlignment - If the specified pointer has an alignment that
3621/// we can determine, return it, otherwise return 0. If PrefAlign is specified,
3622/// and it is more than the alignment of the ultimate object, see if we can
3623/// increase the alignment of the ultimate object, making this check succeed.
3624unsigned InstCombiner::GetOrEnforceKnownAlignment(Value *V,
3625 unsigned PrefAlign) {
3626 unsigned BitWidth = TD ? TD->getTypeSizeInBits(V->getType()) :
3627 sizeof(PrefAlign) * CHAR_BIT;
3628 APInt Mask = APInt::getAllOnesValue(BitWidth);
3629 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
3630 ComputeMaskedBits(V, Mask, KnownZero, KnownOne);
3631 unsigned TrailZ = KnownZero.countTrailingOnes();
3632 unsigned Align = 1u << std::min(BitWidth - 1, TrailZ);
3633
3634 if (PrefAlign > Align)
3635 Align = EnforceKnownAlignment(V, Align, PrefAlign);
3636
3637 // We don't need to make any adjustment.
3638 return Align;
Chris Lattner95a959d2006-03-06 20:18:44 +00003639}
3640
Chris Lattnerf497b022008-01-13 23:50:23 +00003641Instruction *InstCombiner::SimplifyMemTransfer(MemIntrinsic *MI) {
Dan Gohmaneee962e2008-04-10 18:43:06 +00003642 unsigned DstAlign = GetOrEnforceKnownAlignment(MI->getOperand(1));
Dan Gohmanbc989d42009-02-22 18:06:32 +00003643 unsigned SrcAlign = GetOrEnforceKnownAlignment(MI->getOperand(2));
Chris Lattnerf497b022008-01-13 23:50:23 +00003644 unsigned MinAlign = std::min(DstAlign, SrcAlign);
Chris Lattnerdfe964c2009-03-08 03:59:00 +00003645 unsigned CopyAlign = MI->getAlignment();
Chris Lattnerf497b022008-01-13 23:50:23 +00003646
3647 if (CopyAlign < MinAlign) {
Owen Andersoneed707b2009-07-24 23:12:02 +00003648 MI->setAlignment(ConstantInt::get(MI->getAlignmentType(),
Owen Andersona547b472009-07-09 18:36:20 +00003649 MinAlign, false));
Chris Lattnerf497b022008-01-13 23:50:23 +00003650 return MI;
3651 }
3652
3653 // If MemCpyInst length is 1/2/4/8 bytes then replace memcpy with
3654 // load/store.
3655 ConstantInt *MemOpLength = dyn_cast<ConstantInt>(MI->getOperand(3));
3656 if (MemOpLength == 0) return 0;
3657
Chris Lattner37ac6082008-01-14 00:28:35 +00003658 // Source and destination pointer types are always "i8*" for intrinsic. See
3659 // if the size is something we can handle with a single primitive load/store.
3660 // A single load+store correctly handles overlapping memory in the memmove
3661 // case.
Chris Lattnerf497b022008-01-13 23:50:23 +00003662 unsigned Size = MemOpLength->getZExtValue();
Chris Lattner69ea9d22008-04-30 06:39:11 +00003663 if (Size == 0) return MI; // Delete this mem transfer.
3664
3665 if (Size > 8 || (Size&(Size-1)))
Chris Lattner37ac6082008-01-14 00:28:35 +00003666 return 0; // If not 1/2/4/8 bytes, exit.
Chris Lattnerf497b022008-01-13 23:50:23 +00003667
Chris Lattner37ac6082008-01-14 00:28:35 +00003668 // Use an integer load+store unless we can find something better.
Owen Andersond672ecb2009-07-03 00:17:18 +00003669 Type *NewPtrTy =
Chris Lattner4de84762010-01-04 07:02:48 +00003670 PointerType::getUnqual(IntegerType::get(MI->getContext(), Size<<3));
Chris Lattner37ac6082008-01-14 00:28:35 +00003671
3672 // Memcpy forces the use of i8* for the source and destination. That means
3673 // that if you're using memcpy to move one double around, you'll get a cast
3674 // from double* to i8*. We'd much rather use a double load+store rather than
3675 // an i64 load+store, here because this improves the odds that the source or
3676 // dest address will be promotable. See if we can find a better type than the
3677 // integer datatype.
3678 if (Value *Op = getBitCastOperand(MI->getOperand(1))) {
3679 const Type *SrcETy = cast<PointerType>(Op->getType())->getElementType();
Dan Gohmance9fe9f2009-07-21 23:21:54 +00003680 if (TD && SrcETy->isSized() && TD->getTypeStoreSize(SrcETy) == Size) {
Chris Lattner37ac6082008-01-14 00:28:35 +00003681 // The SrcETy might be something like {{{double}}} or [1 x double]. Rip
3682 // down through these levels if so.
Dan Gohman8f8e2692008-05-23 01:52:21 +00003683 while (!SrcETy->isSingleValueType()) {
Chris Lattner37ac6082008-01-14 00:28:35 +00003684 if (const StructType *STy = dyn_cast<StructType>(SrcETy)) {
3685 if (STy->getNumElements() == 1)
3686 SrcETy = STy->getElementType(0);
3687 else
3688 break;
3689 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcETy)) {
3690 if (ATy->getNumElements() == 1)
3691 SrcETy = ATy->getElementType();
3692 else
3693 break;
3694 } else
3695 break;
3696 }
3697
Dan Gohman8f8e2692008-05-23 01:52:21 +00003698 if (SrcETy->isSingleValueType())
Owen Andersondebcb012009-07-29 22:17:13 +00003699 NewPtrTy = PointerType::getUnqual(SrcETy);
Chris Lattner37ac6082008-01-14 00:28:35 +00003700 }
3701 }
3702
3703
Chris Lattnerf497b022008-01-13 23:50:23 +00003704 // If the memcpy/memmove provides better alignment info than we can
3705 // infer, use it.
3706 SrcAlign = std::max(SrcAlign, CopyAlign);
3707 DstAlign = std::max(DstAlign, CopyAlign);
3708
Chris Lattner08142f22009-08-30 19:47:22 +00003709 Value *Src = Builder->CreateBitCast(MI->getOperand(2), NewPtrTy);
3710 Value *Dest = Builder->CreateBitCast(MI->getOperand(1), NewPtrTy);
Chris Lattner37ac6082008-01-14 00:28:35 +00003711 Instruction *L = new LoadInst(Src, "tmp", false, SrcAlign);
3712 InsertNewInstBefore(L, *MI);
3713 InsertNewInstBefore(new StoreInst(L, Dest, false, DstAlign), *MI);
3714
3715 // Set the size of the copy to 0, it will be deleted on the next iteration.
Owen Andersona7235ea2009-07-31 20:28:14 +00003716 MI->setOperand(3, Constant::getNullValue(MemOpLength->getType()));
Chris Lattner37ac6082008-01-14 00:28:35 +00003717 return MI;
Chris Lattnerf497b022008-01-13 23:50:23 +00003718}
Chris Lattner3d69f462004-03-12 05:52:32 +00003719
Chris Lattner69ea9d22008-04-30 06:39:11 +00003720Instruction *InstCombiner::SimplifyMemSet(MemSetInst *MI) {
3721 unsigned Alignment = GetOrEnforceKnownAlignment(MI->getDest());
Chris Lattnerdfe964c2009-03-08 03:59:00 +00003722 if (MI->getAlignment() < Alignment) {
Owen Andersoneed707b2009-07-24 23:12:02 +00003723 MI->setAlignment(ConstantInt::get(MI->getAlignmentType(),
Owen Andersona547b472009-07-09 18:36:20 +00003724 Alignment, false));
Chris Lattner69ea9d22008-04-30 06:39:11 +00003725 return MI;
3726 }
3727
3728 // Extract the length and alignment and fill if they are constant.
3729 ConstantInt *LenC = dyn_cast<ConstantInt>(MI->getLength());
3730 ConstantInt *FillC = dyn_cast<ConstantInt>(MI->getValue());
Chris Lattner4de84762010-01-04 07:02:48 +00003731 if (!LenC || !FillC || FillC->getType() != Type::getInt8Ty(MI->getContext()))
Chris Lattner69ea9d22008-04-30 06:39:11 +00003732 return 0;
3733 uint64_t Len = LenC->getZExtValue();
Chris Lattnerdfe964c2009-03-08 03:59:00 +00003734 Alignment = MI->getAlignment();
Chris Lattner69ea9d22008-04-30 06:39:11 +00003735
3736 // If the length is zero, this is a no-op
3737 if (Len == 0) return MI; // memset(d,c,0,a) -> noop
3738
3739 // memset(s,c,n) -> store s, c (for n=1,2,4,8)
3740 if (Len <= 8 && isPowerOf2_32((uint32_t)Len)) {
Chris Lattner4de84762010-01-04 07:02:48 +00003741 const Type *ITy = IntegerType::get(MI->getContext(), Len*8); // n=1 -> i8.
Chris Lattner69ea9d22008-04-30 06:39:11 +00003742
3743 Value *Dest = MI->getDest();
Chris Lattner08142f22009-08-30 19:47:22 +00003744 Dest = Builder->CreateBitCast(Dest, PointerType::getUnqual(ITy));
Chris Lattner69ea9d22008-04-30 06:39:11 +00003745
3746 // Alignment 0 is identity for alignment 1 for memset, but not store.
3747 if (Alignment == 0) Alignment = 1;
3748
3749 // Extract the fill value and store.
3750 uint64_t Fill = FillC->getZExtValue()*0x0101010101010101ULL;
Owen Andersoneed707b2009-07-24 23:12:02 +00003751 InsertNewInstBefore(new StoreInst(ConstantInt::get(ITy, Fill),
Owen Andersond672ecb2009-07-03 00:17:18 +00003752 Dest, false, Alignment), *MI);
Chris Lattner69ea9d22008-04-30 06:39:11 +00003753
3754 // Set the size of the copy to 0, it will be deleted on the next iteration.
Owen Andersona7235ea2009-07-31 20:28:14 +00003755 MI->setLength(Constant::getNullValue(LenC->getType()));
Chris Lattner69ea9d22008-04-30 06:39:11 +00003756 return MI;
3757 }
3758
3759 return 0;
3760}
3761
3762
Chris Lattner8b0ea312006-01-13 20:11:04 +00003763/// visitCallInst - CallInst simplification. This mostly only handles folding
3764/// of intrinsic instructions. For normal calls, it allows visitCallSite to do
3765/// the heavy lifting.
3766///
Chris Lattner9fe38862003-06-19 17:00:31 +00003767Instruction *InstCombiner::visitCallInst(CallInst &CI) {
Victor Hernandez66284e02009-10-24 04:23:03 +00003768 if (isFreeCall(&CI))
3769 return visitFree(CI);
3770
Chris Lattneraab6ec42009-05-13 17:39:14 +00003771 // If the caller function is nounwind, mark the call as nounwind, even if the
3772 // callee isn't.
3773 if (CI.getParent()->getParent()->doesNotThrow() &&
3774 !CI.doesNotThrow()) {
3775 CI.setDoesNotThrow();
3776 return &CI;
3777 }
3778
Chris Lattner8b0ea312006-01-13 20:11:04 +00003779 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
3780 if (!II) return visitCallSite(&CI);
3781
Chris Lattner7bcc0e72004-02-28 05:22:00 +00003782 // Intrinsics cannot occur in an invoke, so handle them here instead of in
3783 // visitCallSite.
Chris Lattner8b0ea312006-01-13 20:11:04 +00003784 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
Chris Lattner35b9e482004-10-12 04:52:52 +00003785 bool Changed = false;
3786
3787 // memmove/cpy/set of zero bytes is a noop.
3788 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
3789 if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
3790
Chris Lattner35b9e482004-10-12 04:52:52 +00003791 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
Reid Spencerb83eb642006-10-20 07:07:24 +00003792 if (CI->getZExtValue() == 1) {
Chris Lattner35b9e482004-10-12 04:52:52 +00003793 // Replace the instruction with just byte operations. We would
3794 // transform other cases to loads/stores, but we don't know if
3795 // alignment is sufficient.
3796 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +00003797 }
3798
Chris Lattner35b9e482004-10-12 04:52:52 +00003799 // If we have a memmove and the source operation is a constant global,
3800 // then the source and dest pointers can't alias, so we can change this
3801 // into a call to memcpy.
Chris Lattnerf497b022008-01-13 23:50:23 +00003802 if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI)) {
Chris Lattner35b9e482004-10-12 04:52:52 +00003803 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
3804 if (GVSrc->isConstant()) {
3805 Module *M = CI.getParent()->getParent()->getParent();
Chris Lattner824b9582008-11-21 16:42:48 +00003806 Intrinsic::ID MemCpyID = Intrinsic::memcpy;
3807 const Type *Tys[1];
3808 Tys[0] = CI.getOperand(3)->getType();
3809 CI.setOperand(0,
3810 Intrinsic::getDeclaration(M, MemCpyID, Tys, 1));
Chris Lattner35b9e482004-10-12 04:52:52 +00003811 Changed = true;
3812 }
Eli Friedman0c826d92009-12-17 21:07:31 +00003813 }
Chris Lattnera935db82008-05-28 05:30:41 +00003814
Eli Friedman0c826d92009-12-17 21:07:31 +00003815 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(MI)) {
Chris Lattnera935db82008-05-28 05:30:41 +00003816 // memmove(x,x,size) -> noop.
Eli Friedman0c826d92009-12-17 21:07:31 +00003817 if (MTI->getSource() == MTI->getDest())
Chris Lattnera935db82008-05-28 05:30:41 +00003818 return EraseInstFromFunction(CI);
Chris Lattner95a959d2006-03-06 20:18:44 +00003819 }
Chris Lattner35b9e482004-10-12 04:52:52 +00003820
Chris Lattner95a959d2006-03-06 20:18:44 +00003821 // If we can determine a pointer alignment that is bigger than currently
3822 // set, update the alignment.
Chris Lattner3ce5e882009-03-08 03:37:16 +00003823 if (isa<MemTransferInst>(MI)) {
Chris Lattnerf497b022008-01-13 23:50:23 +00003824 if (Instruction *I = SimplifyMemTransfer(MI))
3825 return I;
Chris Lattner69ea9d22008-04-30 06:39:11 +00003826 } else if (MemSetInst *MSI = dyn_cast<MemSetInst>(MI)) {
3827 if (Instruction *I = SimplifyMemSet(MSI))
3828 return I;
Chris Lattner95a959d2006-03-06 20:18:44 +00003829 }
3830
Chris Lattner8b0ea312006-01-13 20:11:04 +00003831 if (Changed) return II;
Chris Lattner0521e3c2008-06-18 04:33:20 +00003832 }
3833
3834 switch (II->getIntrinsicID()) {
3835 default: break;
3836 case Intrinsic::bswap:
3837 // bswap(bswap(x)) -> x
3838 if (IntrinsicInst *Operand = dyn_cast<IntrinsicInst>(II->getOperand(1)))
3839 if (Operand->getIntrinsicID() == Intrinsic::bswap)
3840 return ReplaceInstUsesWith(CI, Operand->getOperand(1));
Chris Lattnere33d4132010-01-01 18:34:40 +00003841
3842 // bswap(trunc(bswap(x))) -> trunc(lshr(x, c))
3843 if (TruncInst *TI = dyn_cast<TruncInst>(II->getOperand(1))) {
3844 if (IntrinsicInst *Operand = dyn_cast<IntrinsicInst>(TI->getOperand(0)))
3845 if (Operand->getIntrinsicID() == Intrinsic::bswap) {
3846 unsigned C = Operand->getType()->getPrimitiveSizeInBits() -
3847 TI->getType()->getPrimitiveSizeInBits();
3848 Value *CV = ConstantInt::get(Operand->getType(), C);
3849 Value *V = Builder->CreateLShr(Operand->getOperand(1), CV);
3850 return new TruncInst(V, TI->getType());
3851 }
3852 }
3853
Chris Lattner0521e3c2008-06-18 04:33:20 +00003854 break;
Chris Lattnerd27f9112010-01-01 01:52:15 +00003855 case Intrinsic::powi:
3856 if (ConstantInt *Power = dyn_cast<ConstantInt>(II->getOperand(2))) {
3857 // powi(x, 0) -> 1.0
3858 if (Power->isZero())
3859 return ReplaceInstUsesWith(CI, ConstantFP::get(CI.getType(), 1.0));
3860 // powi(x, 1) -> x
3861 if (Power->isOne())
3862 return ReplaceInstUsesWith(CI, II->getOperand(1));
3863 // powi(x, -1) -> 1/x
Chris Lattnerf9ead872010-01-01 01:54:08 +00003864 if (Power->isAllOnesValue())
3865 return BinaryOperator::CreateFDiv(ConstantFP::get(CI.getType(), 1.0),
3866 II->getOperand(1));
Chris Lattnerd27f9112010-01-01 01:52:15 +00003867 }
3868 break;
3869
Chris Lattner2bbac752009-11-26 21:42:47 +00003870 case Intrinsic::uadd_with_overflow: {
3871 Value *LHS = II->getOperand(1), *RHS = II->getOperand(2);
3872 const IntegerType *IT = cast<IntegerType>(II->getOperand(1)->getType());
3873 uint32_t BitWidth = IT->getBitWidth();
3874 APInt Mask = APInt::getSignBit(BitWidth);
Chris Lattner998e25a2009-11-26 22:08:06 +00003875 APInt LHSKnownZero(BitWidth, 0);
3876 APInt LHSKnownOne(BitWidth, 0);
Chris Lattner2bbac752009-11-26 21:42:47 +00003877 ComputeMaskedBits(LHS, Mask, LHSKnownZero, LHSKnownOne);
3878 bool LHSKnownNegative = LHSKnownOne[BitWidth - 1];
3879 bool LHSKnownPositive = LHSKnownZero[BitWidth - 1];
3880
3881 if (LHSKnownNegative || LHSKnownPositive) {
Chris Lattner998e25a2009-11-26 22:08:06 +00003882 APInt RHSKnownZero(BitWidth, 0);
3883 APInt RHSKnownOne(BitWidth, 0);
Chris Lattner2bbac752009-11-26 21:42:47 +00003884 ComputeMaskedBits(RHS, Mask, RHSKnownZero, RHSKnownOne);
3885 bool RHSKnownNegative = RHSKnownOne[BitWidth - 1];
3886 bool RHSKnownPositive = RHSKnownZero[BitWidth - 1];
3887 if (LHSKnownNegative && RHSKnownNegative) {
3888 // The sign bit is set in both cases: this MUST overflow.
3889 // Create a simple add instruction, and insert it into the struct.
3890 Instruction *Add = BinaryOperator::CreateAdd(LHS, RHS, "", &CI);
3891 Worklist.Add(Add);
Chris Lattnercd188e92009-11-29 02:57:29 +00003892 Constant *V[] = {
Chris Lattner4de84762010-01-04 07:02:48 +00003893 UndefValue::get(LHS->getType()),ConstantInt::getTrue(II->getContext())
Chris Lattnercd188e92009-11-29 02:57:29 +00003894 };
Chris Lattner4de84762010-01-04 07:02:48 +00003895 Constant *Struct = ConstantStruct::get(II->getContext(), V, 2, false);
Chris Lattner2bbac752009-11-26 21:42:47 +00003896 return InsertValueInst::Create(Struct, Add, 0);
3897 }
3898
3899 if (LHSKnownPositive && RHSKnownPositive) {
3900 // The sign bit is clear in both cases: this CANNOT overflow.
3901 // Create a simple add instruction, and insert it into the struct.
3902 Instruction *Add = BinaryOperator::CreateNUWAdd(LHS, RHS, "", &CI);
3903 Worklist.Add(Add);
Chris Lattnercd188e92009-11-29 02:57:29 +00003904 Constant *V[] = {
Chris Lattner4de84762010-01-04 07:02:48 +00003905 UndefValue::get(LHS->getType()),
3906 ConstantInt::getFalse(II->getContext())
Chris Lattnercd188e92009-11-29 02:57:29 +00003907 };
Chris Lattner4de84762010-01-04 07:02:48 +00003908 Constant *Struct = ConstantStruct::get(II->getContext(), V, 2, false);
Chris Lattner2bbac752009-11-26 21:42:47 +00003909 return InsertValueInst::Create(Struct, Add, 0);
3910 }
3911 }
3912 }
3913 // FALL THROUGH uadd into sadd
3914 case Intrinsic::sadd_with_overflow:
3915 // Canonicalize constants into the RHS.
3916 if (isa<Constant>(II->getOperand(1)) &&
3917 !isa<Constant>(II->getOperand(2))) {
3918 Value *LHS = II->getOperand(1);
3919 II->setOperand(1, II->getOperand(2));
3920 II->setOperand(2, LHS);
3921 return II;
3922 }
3923
3924 // X + undef -> undef
3925 if (isa<UndefValue>(II->getOperand(2)))
3926 return ReplaceInstUsesWith(CI, UndefValue::get(II->getType()));
3927
3928 if (ConstantInt *RHS = dyn_cast<ConstantInt>(II->getOperand(2))) {
3929 // X + 0 -> {X, false}
3930 if (RHS->isZero()) {
3931 Constant *V[] = {
Chris Lattnercd188e92009-11-29 02:57:29 +00003932 UndefValue::get(II->getOperand(0)->getType()),
Chris Lattner4de84762010-01-04 07:02:48 +00003933 ConstantInt::getFalse(II->getContext())
Chris Lattner2bbac752009-11-26 21:42:47 +00003934 };
Chris Lattner4de84762010-01-04 07:02:48 +00003935 Constant *Struct = ConstantStruct::get(II->getContext(), V, 2, false);
Chris Lattner2bbac752009-11-26 21:42:47 +00003936 return InsertValueInst::Create(Struct, II->getOperand(1), 0);
3937 }
3938 }
3939 break;
3940 case Intrinsic::usub_with_overflow:
3941 case Intrinsic::ssub_with_overflow:
3942 // undef - X -> undef
3943 // X - undef -> undef
3944 if (isa<UndefValue>(II->getOperand(1)) ||
3945 isa<UndefValue>(II->getOperand(2)))
3946 return ReplaceInstUsesWith(CI, UndefValue::get(II->getType()));
3947
3948 if (ConstantInt *RHS = dyn_cast<ConstantInt>(II->getOperand(2))) {
3949 // X - 0 -> {X, false}
3950 if (RHS->isZero()) {
3951 Constant *V[] = {
Chris Lattnercd188e92009-11-29 02:57:29 +00003952 UndefValue::get(II->getOperand(1)->getType()),
Chris Lattner4de84762010-01-04 07:02:48 +00003953 ConstantInt::getFalse(II->getContext())
Chris Lattner2bbac752009-11-26 21:42:47 +00003954 };
Chris Lattner4de84762010-01-04 07:02:48 +00003955 Constant *Struct = ConstantStruct::get(II->getContext(), V, 2, false);
Chris Lattner2bbac752009-11-26 21:42:47 +00003956 return InsertValueInst::Create(Struct, II->getOperand(1), 0);
3957 }
3958 }
3959 break;
3960 case Intrinsic::umul_with_overflow:
3961 case Intrinsic::smul_with_overflow:
3962 // Canonicalize constants into the RHS.
3963 if (isa<Constant>(II->getOperand(1)) &&
3964 !isa<Constant>(II->getOperand(2))) {
3965 Value *LHS = II->getOperand(1);
3966 II->setOperand(1, II->getOperand(2));
3967 II->setOperand(2, LHS);
3968 return II;
3969 }
3970
3971 // X * undef -> undef
3972 if (isa<UndefValue>(II->getOperand(2)))
3973 return ReplaceInstUsesWith(CI, UndefValue::get(II->getType()));
3974
3975 if (ConstantInt *RHSI = dyn_cast<ConstantInt>(II->getOperand(2))) {
3976 // X*0 -> {0, false}
3977 if (RHSI->isZero())
3978 return ReplaceInstUsesWith(CI, Constant::getNullValue(II->getType()));
3979
3980 // X * 1 -> {X, false}
3981 if (RHSI->equalsInt(1)) {
Chris Lattnercd188e92009-11-29 02:57:29 +00003982 Constant *V[] = {
3983 UndefValue::get(II->getOperand(1)->getType()),
Chris Lattner4de84762010-01-04 07:02:48 +00003984 ConstantInt::getFalse(II->getContext())
Chris Lattnercd188e92009-11-29 02:57:29 +00003985 };
Chris Lattner4de84762010-01-04 07:02:48 +00003986 Constant *Struct = ConstantStruct::get(II->getContext(), V, 2, false);
Chris Lattnercd188e92009-11-29 02:57:29 +00003987 return InsertValueInst::Create(Struct, II->getOperand(1), 0);
Chris Lattner2bbac752009-11-26 21:42:47 +00003988 }
3989 }
3990 break;
Chris Lattner0521e3c2008-06-18 04:33:20 +00003991 case Intrinsic::ppc_altivec_lvx:
3992 case Intrinsic::ppc_altivec_lvxl:
3993 case Intrinsic::x86_sse_loadu_ps:
3994 case Intrinsic::x86_sse2_loadu_pd:
3995 case Intrinsic::x86_sse2_loadu_dq:
3996 // Turn PPC lvx -> load if the pointer is known aligned.
3997 // Turn X86 loadups -> load if the pointer is known aligned.
3998 if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
Chris Lattner08142f22009-08-30 19:47:22 +00003999 Value *Ptr = Builder->CreateBitCast(II->getOperand(1),
4000 PointerType::getUnqual(II->getType()));
Chris Lattner0521e3c2008-06-18 04:33:20 +00004001 return new LoadInst(Ptr);
Chris Lattner867b99f2006-10-05 06:55:50 +00004002 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00004003 break;
4004 case Intrinsic::ppc_altivec_stvx:
4005 case Intrinsic::ppc_altivec_stvxl:
4006 // Turn stvx -> store if the pointer is known aligned.
4007 if (GetOrEnforceKnownAlignment(II->getOperand(2), 16) >= 16) {
4008 const Type *OpPtrTy =
Owen Andersondebcb012009-07-29 22:17:13 +00004009 PointerType::getUnqual(II->getOperand(1)->getType());
Chris Lattner08142f22009-08-30 19:47:22 +00004010 Value *Ptr = Builder->CreateBitCast(II->getOperand(2), OpPtrTy);
Chris Lattner0521e3c2008-06-18 04:33:20 +00004011 return new StoreInst(II->getOperand(1), Ptr);
4012 }
4013 break;
4014 case Intrinsic::x86_sse_storeu_ps:
4015 case Intrinsic::x86_sse2_storeu_pd:
4016 case Intrinsic::x86_sse2_storeu_dq:
Chris Lattner0521e3c2008-06-18 04:33:20 +00004017 // Turn X86 storeu -> store if the pointer is known aligned.
4018 if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
4019 const Type *OpPtrTy =
Owen Andersondebcb012009-07-29 22:17:13 +00004020 PointerType::getUnqual(II->getOperand(2)->getType());
Chris Lattner08142f22009-08-30 19:47:22 +00004021 Value *Ptr = Builder->CreateBitCast(II->getOperand(1), OpPtrTy);
Chris Lattner0521e3c2008-06-18 04:33:20 +00004022 return new StoreInst(II->getOperand(2), Ptr);
4023 }
4024 break;
4025
4026 case Intrinsic::x86_sse_cvttss2si: {
4027 // These intrinsics only demands the 0th element of its input vector. If
4028 // we can simplify the input based on that, do so now.
Evan Cheng388df622009-02-03 10:05:09 +00004029 unsigned VWidth =
4030 cast<VectorType>(II->getOperand(1)->getType())->getNumElements();
4031 APInt DemandedElts(VWidth, 1);
4032 APInt UndefElts(VWidth, 0);
4033 if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
Chris Lattner0521e3c2008-06-18 04:33:20 +00004034 UndefElts)) {
4035 II->setOperand(1, V);
4036 return II;
4037 }
4038 break;
4039 }
4040
4041 case Intrinsic::ppc_altivec_vperm:
4042 // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
4043 if (ConstantVector *Mask = dyn_cast<ConstantVector>(II->getOperand(3))) {
4044 assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
Chris Lattner867b99f2006-10-05 06:55:50 +00004045
Chris Lattner0521e3c2008-06-18 04:33:20 +00004046 // Check that all of the elements are integer constants or undefs.
4047 bool AllEltsOk = true;
4048 for (unsigned i = 0; i != 16; ++i) {
4049 if (!isa<ConstantInt>(Mask->getOperand(i)) &&
4050 !isa<UndefValue>(Mask->getOperand(i))) {
4051 AllEltsOk = false;
4052 break;
4053 }
4054 }
4055
4056 if (AllEltsOk) {
4057 // Cast the input vectors to byte vectors.
Chris Lattner08142f22009-08-30 19:47:22 +00004058 Value *Op0 = Builder->CreateBitCast(II->getOperand(1), Mask->getType());
4059 Value *Op1 = Builder->CreateBitCast(II->getOperand(2), Mask->getType());
Owen Anderson9e9a0d52009-07-30 23:03:37 +00004060 Value *Result = UndefValue::get(Op0->getType());
Chris Lattnere2ed0572006-04-06 19:19:17 +00004061
Chris Lattner0521e3c2008-06-18 04:33:20 +00004062 // Only extract each element once.
4063 Value *ExtractedElts[32];
4064 memset(ExtractedElts, 0, sizeof(ExtractedElts));
4065
Chris Lattnere2ed0572006-04-06 19:19:17 +00004066 for (unsigned i = 0; i != 16; ++i) {
Chris Lattner0521e3c2008-06-18 04:33:20 +00004067 if (isa<UndefValue>(Mask->getOperand(i)))
4068 continue;
4069 unsigned Idx=cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
4070 Idx &= 31; // Match the hardware behavior.
4071
4072 if (ExtractedElts[Idx] == 0) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +00004073 ExtractedElts[Idx] =
4074 Builder->CreateExtractElement(Idx < 16 ? Op0 : Op1,
Chris Lattner4de84762010-01-04 07:02:48 +00004075 ConstantInt::get(Type::getInt32Ty(II->getContext()),
4076 Idx&15, false), "tmp");
Chris Lattnere2ed0572006-04-06 19:19:17 +00004077 }
Chris Lattnere2ed0572006-04-06 19:19:17 +00004078
Chris Lattner0521e3c2008-06-18 04:33:20 +00004079 // Insert this value into the result vector.
Chris Lattnerf925cbd2009-08-30 18:50:58 +00004080 Result = Builder->CreateInsertElement(Result, ExtractedElts[Idx],
Chris Lattner4de84762010-01-04 07:02:48 +00004081 ConstantInt::get(Type::getInt32Ty(II->getContext()),
4082 i, false), "tmp");
Chris Lattnere2ed0572006-04-06 19:19:17 +00004083 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00004084 return CastInst::Create(Instruction::BitCast, Result, CI.getType());
Chris Lattnere2ed0572006-04-06 19:19:17 +00004085 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00004086 }
4087 break;
Chris Lattnere2ed0572006-04-06 19:19:17 +00004088
Chris Lattner0521e3c2008-06-18 04:33:20 +00004089 case Intrinsic::stackrestore: {
4090 // If the save is right next to the restore, remove the restore. This can
4091 // happen when variable allocas are DCE'd.
4092 if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
4093 if (SS->getIntrinsicID() == Intrinsic::stacksave) {
4094 BasicBlock::iterator BI = SS;
4095 if (&*++BI == II)
4096 return EraseInstFromFunction(CI);
Chris Lattnera728ddc2006-01-13 21:28:09 +00004097 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00004098 }
4099
4100 // Scan down this block to see if there is another stack restore in the
4101 // same block without an intervening call/alloca.
4102 BasicBlock::iterator BI = II;
4103 TerminatorInst *TI = II->getParent()->getTerminator();
4104 bool CannotRemove = false;
4105 for (++BI; &*BI != TI; ++BI) {
Victor Hernandez83d63912009-09-18 22:35:49 +00004106 if (isa<AllocaInst>(BI) || isMalloc(BI)) {
Chris Lattner0521e3c2008-06-18 04:33:20 +00004107 CannotRemove = true;
4108 break;
4109 }
Chris Lattneraa0bf522008-06-25 05:59:28 +00004110 if (CallInst *BCI = dyn_cast<CallInst>(BI)) {
4111 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(BCI)) {
4112 // If there is a stackrestore below this one, remove this one.
4113 if (II->getIntrinsicID() == Intrinsic::stackrestore)
4114 return EraseInstFromFunction(CI);
4115 // Otherwise, ignore the intrinsic.
4116 } else {
4117 // If we found a non-intrinsic call, we can't remove the stack
4118 // restore.
Chris Lattnerbf1d8a72008-02-18 06:12:38 +00004119 CannotRemove = true;
4120 break;
4121 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00004122 }
Chris Lattnera728ddc2006-01-13 21:28:09 +00004123 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00004124
4125 // If the stack restore is in a return/unwind block and if there are no
4126 // allocas or calls between the restore and the return, nuke the restore.
4127 if (!CannotRemove && (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)))
4128 return EraseInstFromFunction(CI);
4129 break;
4130 }
Chris Lattner35b9e482004-10-12 04:52:52 +00004131 }
4132
Chris Lattner8b0ea312006-01-13 20:11:04 +00004133 return visitCallSite(II);
Chris Lattner9fe38862003-06-19 17:00:31 +00004134}
4135
4136// InvokeInst simplification
4137//
4138Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
Chris Lattnera44d8a22003-10-07 22:32:43 +00004139 return visitCallSite(&II);
Chris Lattner9fe38862003-06-19 17:00:31 +00004140}
4141
Dale Johannesenda30ccb2008-04-25 21:16:07 +00004142/// isSafeToEliminateVarargsCast - If this cast does not affect the value
4143/// passed through the varargs area, we can eliminate the use of the cast.
Dale Johannesen1f530a52008-04-23 18:34:37 +00004144static bool isSafeToEliminateVarargsCast(const CallSite CS,
4145 const CastInst * const CI,
4146 const TargetData * const TD,
4147 const int ix) {
4148 if (!CI->isLosslessCast())
4149 return false;
4150
4151 // The size of ByVal arguments is derived from the type, so we
4152 // can't change to a type with a different size. If the size were
4153 // passed explicitly we could avoid this check.
Devang Patel05988662008-09-25 21:00:45 +00004154 if (!CS.paramHasAttr(ix, Attribute::ByVal))
Dale Johannesen1f530a52008-04-23 18:34:37 +00004155 return true;
4156
4157 const Type* SrcTy =
4158 cast<PointerType>(CI->getOperand(0)->getType())->getElementType();
4159 const Type* DstTy = cast<PointerType>(CI->getType())->getElementType();
4160 if (!SrcTy->isSized() || !DstTy->isSized())
4161 return false;
Dan Gohmance9fe9f2009-07-21 23:21:54 +00004162 if (!TD || TD->getTypeAllocSize(SrcTy) != TD->getTypeAllocSize(DstTy))
Dale Johannesen1f530a52008-04-23 18:34:37 +00004163 return false;
4164 return true;
4165}
4166
Chris Lattnera44d8a22003-10-07 22:32:43 +00004167// visitCallSite - Improvements for call and invoke instructions.
4168//
4169Instruction *InstCombiner::visitCallSite(CallSite CS) {
Chris Lattner6c266db2003-10-07 22:54:13 +00004170 bool Changed = false;
4171
4172 // If the callee is a constexpr cast of a function, attempt to move the cast
4173 // to the arguments of the call/invoke.
Chris Lattnera44d8a22003-10-07 22:32:43 +00004174 if (transformConstExprCastCall(CS)) return 0;
4175
Chris Lattner6c266db2003-10-07 22:54:13 +00004176 Value *Callee = CS.getCalledValue();
Chris Lattnere87597f2004-10-16 18:11:37 +00004177
Chris Lattner08b22ec2005-05-13 07:09:09 +00004178 if (Function *CalleeF = dyn_cast<Function>(Callee))
4179 if (CalleeF->getCallingConv() != CS.getCallingConv()) {
4180 Instruction *OldCall = CS.getInstruction();
4181 // If the call and callee calling conventions don't match, this call must
4182 // be unreachable, as the call is undefined.
Chris Lattner4de84762010-01-04 07:02:48 +00004183 new StoreInst(ConstantInt::getTrue(Callee->getContext()),
4184 UndefValue::get(Type::getInt1PtrTy(Callee->getContext())),
Owen Andersond672ecb2009-07-03 00:17:18 +00004185 OldCall);
Devang Patel228ebd02009-10-13 22:56:32 +00004186 // If OldCall dues not return void then replaceAllUsesWith undef.
4187 // This allows ValueHandlers and custom metadata to adjust itself.
Devang Patel9674d152009-10-14 17:29:00 +00004188 if (!OldCall->getType()->isVoidTy())
Devang Patel228ebd02009-10-13 22:56:32 +00004189 OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
Chris Lattner08b22ec2005-05-13 07:09:09 +00004190 if (isa<CallInst>(OldCall)) // Not worth removing an invoke here.
4191 return EraseInstFromFunction(*OldCall);
4192 return 0;
4193 }
4194
Chris Lattner17be6352004-10-18 02:59:09 +00004195 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
4196 // This instruction is not reachable, just remove it. We insert a store to
4197 // undef so that we know that this code is not reachable, despite the fact
4198 // that we can't modify the CFG here.
Chris Lattner4de84762010-01-04 07:02:48 +00004199 new StoreInst(ConstantInt::getTrue(Callee->getContext()),
4200 UndefValue::get(Type::getInt1PtrTy(Callee->getContext())),
Chris Lattner17be6352004-10-18 02:59:09 +00004201 CS.getInstruction());
4202
Devang Patel228ebd02009-10-13 22:56:32 +00004203 // If CS dues not return void then replaceAllUsesWith undef.
4204 // This allows ValueHandlers and custom metadata to adjust itself.
Devang Patel9674d152009-10-14 17:29:00 +00004205 if (!CS.getInstruction()->getType()->isVoidTy())
Devang Patel228ebd02009-10-13 22:56:32 +00004206 CS.getInstruction()->
4207 replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
Chris Lattner17be6352004-10-18 02:59:09 +00004208
4209 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
4210 // Don't break the CFG, insert a dummy cond branch.
Gabor Greif051a9502008-04-06 20:25:17 +00004211 BranchInst::Create(II->getNormalDest(), II->getUnwindDest(),
Chris Lattner4de84762010-01-04 07:02:48 +00004212 ConstantInt::getTrue(Callee->getContext()), II);
Chris Lattnere87597f2004-10-16 18:11:37 +00004213 }
Chris Lattner17be6352004-10-18 02:59:09 +00004214 return EraseInstFromFunction(*CS.getInstruction());
4215 }
Chris Lattnere87597f2004-10-16 18:11:37 +00004216
Duncan Sandscdb6d922007-09-17 10:26:40 +00004217 if (BitCastInst *BC = dyn_cast<BitCastInst>(Callee))
4218 if (IntrinsicInst *In = dyn_cast<IntrinsicInst>(BC->getOperand(0)))
4219 if (In->getIntrinsicID() == Intrinsic::init_trampoline)
4220 return transformCallThroughTrampoline(CS);
4221
Chris Lattner6c266db2003-10-07 22:54:13 +00004222 const PointerType *PTy = cast<PointerType>(Callee->getType());
4223 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
4224 if (FTy->isVarArg()) {
Dale Johannesen63e7eb42008-04-23 01:03:05 +00004225 int ix = FTy->getNumParams() + (isa<InvokeInst>(Callee) ? 3 : 1);
Chris Lattner6c266db2003-10-07 22:54:13 +00004226 // See if we can optimize any arguments passed through the varargs area of
4227 // the call.
4228 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
Dale Johannesen1f530a52008-04-23 18:34:37 +00004229 E = CS.arg_end(); I != E; ++I, ++ix) {
4230 CastInst *CI = dyn_cast<CastInst>(*I);
4231 if (CI && isSafeToEliminateVarargsCast(CS, CI, TD, ix)) {
4232 *I = CI->getOperand(0);
4233 Changed = true;
Chris Lattner6c266db2003-10-07 22:54:13 +00004234 }
Dale Johannesen1f530a52008-04-23 18:34:37 +00004235 }
Chris Lattner6c266db2003-10-07 22:54:13 +00004236 }
Misha Brukmanfd939082005-04-21 23:48:37 +00004237
Duncan Sandsf0c33542007-12-19 21:13:37 +00004238 if (isa<InlineAsm>(Callee) && !CS.doesNotThrow()) {
Duncan Sandsece2c042007-12-16 15:51:49 +00004239 // Inline asm calls cannot throw - mark them 'nounwind'.
Duncan Sandsf0c33542007-12-19 21:13:37 +00004240 CS.setDoesNotThrow();
Duncan Sandsece2c042007-12-16 15:51:49 +00004241 Changed = true;
4242 }
4243
Chris Lattner6c266db2003-10-07 22:54:13 +00004244 return Changed ? CS.getInstruction() : 0;
Chris Lattnera44d8a22003-10-07 22:32:43 +00004245}
4246
Chris Lattner9fe38862003-06-19 17:00:31 +00004247// transformConstExprCastCall - If the callee is a constexpr cast of a function,
4248// attempt to move the cast to the arguments of the call/invoke.
4249//
4250bool InstCombiner::transformConstExprCastCall(CallSite CS) {
4251 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
4252 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
Reid Spencer3da59db2006-11-27 01:05:10 +00004253 if (CE->getOpcode() != Instruction::BitCast ||
4254 !isa<Function>(CE->getOperand(0)))
Chris Lattner9fe38862003-06-19 17:00:31 +00004255 return false;
Reid Spencer8863f182004-07-18 00:38:32 +00004256 Function *Callee = cast<Function>(CE->getOperand(0));
Chris Lattner9fe38862003-06-19 17:00:31 +00004257 Instruction *Caller = CS.getInstruction();
Devang Patel05988662008-09-25 21:00:45 +00004258 const AttrListPtr &CallerPAL = CS.getAttributes();
Chris Lattner9fe38862003-06-19 17:00:31 +00004259
4260 // Okay, this is a cast from a function to a different type. Unless doing so
4261 // would cause a type conversion of one of our arguments, change this call to
4262 // be a direct call with arguments casted to the appropriate types.
4263 //
4264 const FunctionType *FT = Callee->getFunctionType();
4265 const Type *OldRetTy = Caller->getType();
Duncan Sandsf413cdf2008-06-01 07:38:42 +00004266 const Type *NewRetTy = FT->getReturnType();
Chris Lattner9fe38862003-06-19 17:00:31 +00004267
Duncan Sandsf413cdf2008-06-01 07:38:42 +00004268 if (isa<StructType>(NewRetTy))
Devang Patel75e6f022008-03-11 18:04:06 +00004269 return false; // TODO: Handle multiple return values.
4270
Chris Lattnerf78616b2004-01-14 06:06:08 +00004271 // Check to see if we are changing the return type...
Duncan Sandsf413cdf2008-06-01 07:38:42 +00004272 if (OldRetTy != NewRetTy) {
Bill Wendlinga6c31122008-05-14 22:45:20 +00004273 if (Callee->isDeclaration() &&
Duncan Sandsf413cdf2008-06-01 07:38:42 +00004274 // Conversion is ok if changing from one pointer type to another or from
4275 // a pointer to an integer of the same size.
Dan Gohmance9fe9f2009-07-21 23:21:54 +00004276 !((isa<PointerType>(OldRetTy) || !TD ||
Owen Anderson1d0be152009-08-13 21:58:54 +00004277 OldRetTy == TD->getIntPtrType(Caller->getContext())) &&
Dan Gohmance9fe9f2009-07-21 23:21:54 +00004278 (isa<PointerType>(NewRetTy) || !TD ||
Owen Anderson1d0be152009-08-13 21:58:54 +00004279 NewRetTy == TD->getIntPtrType(Caller->getContext()))))
Chris Lattnerec479922007-01-06 02:09:32 +00004280 return false; // Cannot transform this return value.
Chris Lattnerf78616b2004-01-14 06:06:08 +00004281
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00004282 if (!Caller->use_empty() &&
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00004283 // void -> non-void is handled specially
Devang Patel9674d152009-10-14 17:29:00 +00004284 !NewRetTy->isVoidTy() && !CastInst::isCastable(NewRetTy, OldRetTy))
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00004285 return false; // Cannot transform this return value.
4286
Chris Lattner58d74912008-03-12 17:45:29 +00004287 if (!CallerPAL.isEmpty() && !Caller->use_empty()) {
Devang Patel19c87462008-09-26 22:53:05 +00004288 Attributes RAttrs = CallerPAL.getRetAttributes();
Devang Patel05988662008-09-25 21:00:45 +00004289 if (RAttrs & Attribute::typeIncompatible(NewRetTy))
Duncan Sands6c3470e2008-01-07 17:16:06 +00004290 return false; // Attribute not compatible with transformed value.
4291 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +00004292
Chris Lattnerf78616b2004-01-14 06:06:08 +00004293 // If the callsite is an invoke instruction, and the return value is used by
4294 // a PHI node in a successor, we cannot change the return type of the call
4295 // because there is no place to put the cast instruction (without breaking
4296 // the critical edge). Bail out in this case.
4297 if (!Caller->use_empty())
4298 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
4299 for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
4300 UI != E; ++UI)
4301 if (PHINode *PN = dyn_cast<PHINode>(*UI))
4302 if (PN->getParent() == II->getNormalDest() ||
Chris Lattneraeb2a1d2004-02-08 21:44:31 +00004303 PN->getParent() == II->getUnwindDest())
Chris Lattnerf78616b2004-01-14 06:06:08 +00004304 return false;
4305 }
Chris Lattner9fe38862003-06-19 17:00:31 +00004306
4307 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
4308 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
Misha Brukmanfd939082005-04-21 23:48:37 +00004309
Chris Lattner9fe38862003-06-19 17:00:31 +00004310 CallSite::arg_iterator AI = CS.arg_begin();
4311 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
4312 const Type *ParamTy = FT->getParamType(i);
Andrew Lenharthb8e604c2006-06-28 01:01:52 +00004313 const Type *ActTy = (*AI)->getType();
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00004314
4315 if (!CastInst::isCastable(ActTy, ParamTy))
Duncan Sandsad9a9e12008-01-06 18:27:01 +00004316 return false; // Cannot transform this parameter value.
4317
Devang Patel19c87462008-09-26 22:53:05 +00004318 if (CallerPAL.getParamAttributes(i + 1)
4319 & Attribute::typeIncompatible(ParamTy))
Chris Lattner58d74912008-03-12 17:45:29 +00004320 return false; // Attribute not compatible with transformed value.
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00004321
Duncan Sandsf413cdf2008-06-01 07:38:42 +00004322 // Converting from one pointer type to another or between a pointer and an
4323 // integer of the same size is safe even if we do not have a body.
Chris Lattnerec479922007-01-06 02:09:32 +00004324 bool isConvertible = ActTy == ParamTy ||
Owen Anderson1d0be152009-08-13 21:58:54 +00004325 (TD && ((isa<PointerType>(ParamTy) ||
4326 ParamTy == TD->getIntPtrType(Caller->getContext())) &&
4327 (isa<PointerType>(ActTy) ||
4328 ActTy == TD->getIntPtrType(Caller->getContext()))));
Reid Spencer5cbf9852007-01-30 20:08:39 +00004329 if (Callee->isDeclaration() && !isConvertible) return false;
Chris Lattner9fe38862003-06-19 17:00:31 +00004330 }
4331
4332 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
Reid Spencer5cbf9852007-01-30 20:08:39 +00004333 Callee->isDeclaration())
Chris Lattner58d74912008-03-12 17:45:29 +00004334 return false; // Do not delete arguments unless we have a function body.
Chris Lattner9fe38862003-06-19 17:00:31 +00004335
Chris Lattner58d74912008-03-12 17:45:29 +00004336 if (FT->getNumParams() < NumActualArgs && FT->isVarArg() &&
4337 !CallerPAL.isEmpty())
Duncan Sandsad9a9e12008-01-06 18:27:01 +00004338 // In this case we have more arguments than the new function type, but we
Duncan Sandse1e520f2008-01-13 08:02:44 +00004339 // won't be dropping them. Check that these extra arguments have attributes
4340 // that are compatible with being a vararg call argument.
Chris Lattner58d74912008-03-12 17:45:29 +00004341 for (unsigned i = CallerPAL.getNumSlots(); i; --i) {
4342 if (CallerPAL.getSlot(i - 1).Index <= FT->getNumParams())
Duncan Sandse1e520f2008-01-13 08:02:44 +00004343 break;
Devang Pateleaf42ab2008-09-23 23:03:40 +00004344 Attributes PAttrs = CallerPAL.getSlot(i - 1).Attrs;
Devang Patel05988662008-09-25 21:00:45 +00004345 if (PAttrs & Attribute::VarArgsIncompatible)
Duncan Sandse1e520f2008-01-13 08:02:44 +00004346 return false;
4347 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +00004348
Chris Lattner9fe38862003-06-19 17:00:31 +00004349 // Okay, we decided that this is a safe thing to do: go ahead and start
4350 // inserting cast instructions as necessary...
4351 std::vector<Value*> Args;
4352 Args.reserve(NumActualArgs);
Devang Patel05988662008-09-25 21:00:45 +00004353 SmallVector<AttributeWithIndex, 8> attrVec;
Duncan Sandsad9a9e12008-01-06 18:27:01 +00004354 attrVec.reserve(NumCommonArgs);
4355
4356 // Get any return attributes.
Devang Patel19c87462008-09-26 22:53:05 +00004357 Attributes RAttrs = CallerPAL.getRetAttributes();
Duncan Sandsad9a9e12008-01-06 18:27:01 +00004358
4359 // If the return value is not being used, the type may not be compatible
4360 // with the existing attributes. Wipe out any problematic attributes.
Devang Patel05988662008-09-25 21:00:45 +00004361 RAttrs &= ~Attribute::typeIncompatible(NewRetTy);
Duncan Sandsad9a9e12008-01-06 18:27:01 +00004362
4363 // Add the new return attributes.
4364 if (RAttrs)
Devang Patel05988662008-09-25 21:00:45 +00004365 attrVec.push_back(AttributeWithIndex::get(0, RAttrs));
Chris Lattner9fe38862003-06-19 17:00:31 +00004366
4367 AI = CS.arg_begin();
4368 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
4369 const Type *ParamTy = FT->getParamType(i);
4370 if ((*AI)->getType() == ParamTy) {
4371 Args.push_back(*AI);
4372 } else {
Reid Spencer8a903db2006-12-18 08:47:13 +00004373 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
Reid Spencerc5b206b2006-12-31 05:48:39 +00004374 false, ParamTy, false);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00004375 Args.push_back(Builder->CreateCast(opcode, *AI, ParamTy, "tmp"));
Chris Lattner9fe38862003-06-19 17:00:31 +00004376 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +00004377
4378 // Add any parameter attributes.
Devang Patel19c87462008-09-26 22:53:05 +00004379 if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
Devang Patel05988662008-09-25 21:00:45 +00004380 attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
Chris Lattner9fe38862003-06-19 17:00:31 +00004381 }
4382
4383 // If the function takes more arguments than the call was taking, add them
Chris Lattnerf925cbd2009-08-30 18:50:58 +00004384 // now.
Chris Lattner9fe38862003-06-19 17:00:31 +00004385 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
Owen Andersona7235ea2009-07-31 20:28:14 +00004386 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
Chris Lattner9fe38862003-06-19 17:00:31 +00004387
Chris Lattnerf925cbd2009-08-30 18:50:58 +00004388 // If we are removing arguments to the function, emit an obnoxious warning.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00004389 if (FT->getNumParams() < NumActualArgs) {
Chris Lattner9fe38862003-06-19 17:00:31 +00004390 if (!FT->isVarArg()) {
Daniel Dunbarce63ffb2009-07-25 00:23:56 +00004391 errs() << "WARNING: While resolving call to function '"
4392 << Callee->getName() << "' arguments were dropped!\n";
Chris Lattner9fe38862003-06-19 17:00:31 +00004393 } else {
Chris Lattnerf925cbd2009-08-30 18:50:58 +00004394 // Add all of the arguments in their promoted form to the arg list.
Chris Lattner9fe38862003-06-19 17:00:31 +00004395 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
4396 const Type *PTy = getPromotedType((*AI)->getType());
4397 if (PTy != (*AI)->getType()) {
4398 // Must promote to pass through va_arg area!
Chris Lattnerf925cbd2009-08-30 18:50:58 +00004399 Instruction::CastOps opcode =
4400 CastInst::getCastOpcode(*AI, false, PTy, false);
4401 Args.push_back(Builder->CreateCast(opcode, *AI, PTy, "tmp"));
Chris Lattner9fe38862003-06-19 17:00:31 +00004402 } else {
4403 Args.push_back(*AI);
4404 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +00004405
Duncan Sandse1e520f2008-01-13 08:02:44 +00004406 // Add any parameter attributes.
Devang Patel19c87462008-09-26 22:53:05 +00004407 if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
Devang Patel05988662008-09-25 21:00:45 +00004408 attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
Duncan Sandse1e520f2008-01-13 08:02:44 +00004409 }
Chris Lattner9fe38862003-06-19 17:00:31 +00004410 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00004411 }
Chris Lattner9fe38862003-06-19 17:00:31 +00004412
Devang Patel19c87462008-09-26 22:53:05 +00004413 if (Attributes FnAttrs = CallerPAL.getFnAttributes())
4414 attrVec.push_back(AttributeWithIndex::get(~0, FnAttrs));
4415
Devang Patel9674d152009-10-14 17:29:00 +00004416 if (NewRetTy->isVoidTy())
Chris Lattner6934a042007-02-11 01:23:03 +00004417 Caller->setName(""); // Void type should not have a name.
Chris Lattner9fe38862003-06-19 17:00:31 +00004418
Eric Christophera66297a2009-07-25 02:45:27 +00004419 const AttrListPtr &NewCallerPAL = AttrListPtr::get(attrVec.begin(),
4420 attrVec.end());
Duncan Sandsad9a9e12008-01-06 18:27:01 +00004421
Chris Lattner9fe38862003-06-19 17:00:31 +00004422 Instruction *NC;
4423 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Gabor Greif051a9502008-04-06 20:25:17 +00004424 NC = InvokeInst::Create(Callee, II->getNormalDest(), II->getUnwindDest(),
Gabor Greifb1dbcd82008-05-15 10:04:30 +00004425 Args.begin(), Args.end(),
4426 Caller->getName(), Caller);
Reid Spencered3fa852007-07-30 19:53:57 +00004427 cast<InvokeInst>(NC)->setCallingConv(II->getCallingConv());
Devang Patel05988662008-09-25 21:00:45 +00004428 cast<InvokeInst>(NC)->setAttributes(NewCallerPAL);
Chris Lattner9fe38862003-06-19 17:00:31 +00004429 } else {
Gabor Greif051a9502008-04-06 20:25:17 +00004430 NC = CallInst::Create(Callee, Args.begin(), Args.end(),
4431 Caller->getName(), Caller);
Duncan Sandsdc024672007-11-27 13:23:08 +00004432 CallInst *CI = cast<CallInst>(Caller);
4433 if (CI->isTailCall())
Chris Lattnera9e92112005-05-06 06:48:21 +00004434 cast<CallInst>(NC)->setTailCall();
Duncan Sandsdc024672007-11-27 13:23:08 +00004435 cast<CallInst>(NC)->setCallingConv(CI->getCallingConv());
Devang Patel05988662008-09-25 21:00:45 +00004436 cast<CallInst>(NC)->setAttributes(NewCallerPAL);
Chris Lattner9fe38862003-06-19 17:00:31 +00004437 }
4438
Chris Lattner6934a042007-02-11 01:23:03 +00004439 // Insert a cast of the return type as necessary.
Chris Lattner9fe38862003-06-19 17:00:31 +00004440 Value *NV = NC;
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00004441 if (OldRetTy != NV->getType() && !Caller->use_empty()) {
Devang Patel9674d152009-10-14 17:29:00 +00004442 if (!NV->getType()->isVoidTy()) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00004443 Instruction::CastOps opcode = CastInst::getCastOpcode(NC, false,
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00004444 OldRetTy, false);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004445 NV = NC = CastInst::Create(opcode, NC, OldRetTy, "tmp");
Chris Lattnerbb609042003-10-30 00:46:41 +00004446
4447 // If this is an invoke instruction, we should insert it after the first
4448 // non-phi, instruction in the normal successor block.
4449 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Dan Gohman02dea8b2008-05-23 21:05:58 +00004450 BasicBlock::iterator I = II->getNormalDest()->getFirstNonPHI();
Chris Lattnerbb609042003-10-30 00:46:41 +00004451 InsertNewInstBefore(NC, *I);
4452 } else {
4453 // Otherwise, it's a call, just insert cast right after the call instr
4454 InsertNewInstBefore(NC, *Caller);
4455 }
Chris Lattnere5ecdb52009-08-30 06:22:51 +00004456 Worklist.AddUsersToWorkList(*Caller);
Chris Lattner9fe38862003-06-19 17:00:31 +00004457 } else {
Owen Anderson9e9a0d52009-07-30 23:03:37 +00004458 NV = UndefValue::get(Caller->getType());
Chris Lattner9fe38862003-06-19 17:00:31 +00004459 }
4460 }
4461
Devang Patel1bf5ebc2009-10-13 21:41:20 +00004462
Chris Lattner931f8f32009-08-31 05:17:58 +00004463 if (!Caller->use_empty())
Chris Lattner9fe38862003-06-19 17:00:31 +00004464 Caller->replaceAllUsesWith(NV);
Chris Lattner931f8f32009-08-31 05:17:58 +00004465
4466 EraseInstFromFunction(*Caller);
Chris Lattner9fe38862003-06-19 17:00:31 +00004467 return true;
4468}
4469
Duncan Sandscdb6d922007-09-17 10:26:40 +00004470// transformCallThroughTrampoline - Turn a call to a function created by the
4471// init_trampoline intrinsic into a direct call to the underlying function.
4472//
4473Instruction *InstCombiner::transformCallThroughTrampoline(CallSite CS) {
4474 Value *Callee = CS.getCalledValue();
4475 const PointerType *PTy = cast<PointerType>(Callee->getType());
4476 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
Devang Patel05988662008-09-25 21:00:45 +00004477 const AttrListPtr &Attrs = CS.getAttributes();
Duncan Sandsb0c9b932008-01-14 19:52:09 +00004478
4479 // If the call already has the 'nest' attribute somewhere then give up -
4480 // otherwise 'nest' would occur twice after splicing in the chain.
Devang Patel05988662008-09-25 21:00:45 +00004481 if (Attrs.hasAttrSomewhere(Attribute::Nest))
Duncan Sandsb0c9b932008-01-14 19:52:09 +00004482 return 0;
Duncan Sandscdb6d922007-09-17 10:26:40 +00004483
4484 IntrinsicInst *Tramp =
4485 cast<IntrinsicInst>(cast<BitCastInst>(Callee)->getOperand(0));
4486
Anton Korobeynikov0b12ecf2008-05-07 22:54:15 +00004487 Function *NestF = cast<Function>(Tramp->getOperand(2)->stripPointerCasts());
Duncan Sandscdb6d922007-09-17 10:26:40 +00004488 const PointerType *NestFPTy = cast<PointerType>(NestF->getType());
4489 const FunctionType *NestFTy = cast<FunctionType>(NestFPTy->getElementType());
4490
Devang Patel05988662008-09-25 21:00:45 +00004491 const AttrListPtr &NestAttrs = NestF->getAttributes();
Chris Lattner58d74912008-03-12 17:45:29 +00004492 if (!NestAttrs.isEmpty()) {
Duncan Sandscdb6d922007-09-17 10:26:40 +00004493 unsigned NestIdx = 1;
4494 const Type *NestTy = 0;
Devang Patel05988662008-09-25 21:00:45 +00004495 Attributes NestAttr = Attribute::None;
Duncan Sandscdb6d922007-09-17 10:26:40 +00004496
4497 // Look for a parameter marked with the 'nest' attribute.
4498 for (FunctionType::param_iterator I = NestFTy->param_begin(),
4499 E = NestFTy->param_end(); I != E; ++NestIdx, ++I)
Devang Patel05988662008-09-25 21:00:45 +00004500 if (NestAttrs.paramHasAttr(NestIdx, Attribute::Nest)) {
Duncan Sandscdb6d922007-09-17 10:26:40 +00004501 // Record the parameter type and any other attributes.
4502 NestTy = *I;
Devang Patel19c87462008-09-26 22:53:05 +00004503 NestAttr = NestAttrs.getParamAttributes(NestIdx);
Duncan Sandscdb6d922007-09-17 10:26:40 +00004504 break;
4505 }
4506
4507 if (NestTy) {
4508 Instruction *Caller = CS.getInstruction();
4509 std::vector<Value*> NewArgs;
4510 NewArgs.reserve(unsigned(CS.arg_end()-CS.arg_begin())+1);
4511
Devang Patel05988662008-09-25 21:00:45 +00004512 SmallVector<AttributeWithIndex, 8> NewAttrs;
Chris Lattner58d74912008-03-12 17:45:29 +00004513 NewAttrs.reserve(Attrs.getNumSlots() + 1);
Duncan Sandsb0c9b932008-01-14 19:52:09 +00004514
Duncan Sandscdb6d922007-09-17 10:26:40 +00004515 // Insert the nest argument into the call argument list, which may
Duncan Sandsb0c9b932008-01-14 19:52:09 +00004516 // mean appending it. Likewise for attributes.
4517
Devang Patel19c87462008-09-26 22:53:05 +00004518 // Add any result attributes.
4519 if (Attributes Attr = Attrs.getRetAttributes())
Devang Patel05988662008-09-25 21:00:45 +00004520 NewAttrs.push_back(AttributeWithIndex::get(0, Attr));
Duncan Sandsb0c9b932008-01-14 19:52:09 +00004521
Duncan Sandscdb6d922007-09-17 10:26:40 +00004522 {
4523 unsigned Idx = 1;
4524 CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
4525 do {
4526 if (Idx == NestIdx) {
Duncan Sandsb0c9b932008-01-14 19:52:09 +00004527 // Add the chain argument and attributes.
Duncan Sandscdb6d922007-09-17 10:26:40 +00004528 Value *NestVal = Tramp->getOperand(3);
4529 if (NestVal->getType() != NestTy)
4530 NestVal = new BitCastInst(NestVal, NestTy, "nest", Caller);
4531 NewArgs.push_back(NestVal);
Devang Patel05988662008-09-25 21:00:45 +00004532 NewAttrs.push_back(AttributeWithIndex::get(NestIdx, NestAttr));
Duncan Sandscdb6d922007-09-17 10:26:40 +00004533 }
4534
4535 if (I == E)
4536 break;
4537
Duncan Sandsb0c9b932008-01-14 19:52:09 +00004538 // Add the original argument and attributes.
Duncan Sandscdb6d922007-09-17 10:26:40 +00004539 NewArgs.push_back(*I);
Devang Patel19c87462008-09-26 22:53:05 +00004540 if (Attributes Attr = Attrs.getParamAttributes(Idx))
Duncan Sandsb0c9b932008-01-14 19:52:09 +00004541 NewAttrs.push_back
Devang Patel05988662008-09-25 21:00:45 +00004542 (AttributeWithIndex::get(Idx + (Idx >= NestIdx), Attr));
Duncan Sandscdb6d922007-09-17 10:26:40 +00004543
4544 ++Idx, ++I;
4545 } while (1);
4546 }
4547
Devang Patel19c87462008-09-26 22:53:05 +00004548 // Add any function attributes.
4549 if (Attributes Attr = Attrs.getFnAttributes())
4550 NewAttrs.push_back(AttributeWithIndex::get(~0, Attr));
4551
Duncan Sandscdb6d922007-09-17 10:26:40 +00004552 // The trampoline may have been bitcast to a bogus type (FTy).
4553 // Handle this by synthesizing a new function type, equal to FTy
Duncan Sandsb0c9b932008-01-14 19:52:09 +00004554 // with the chain parameter inserted.
Duncan Sandscdb6d922007-09-17 10:26:40 +00004555
Duncan Sandscdb6d922007-09-17 10:26:40 +00004556 std::vector<const Type*> NewTypes;
Duncan Sandscdb6d922007-09-17 10:26:40 +00004557 NewTypes.reserve(FTy->getNumParams()+1);
4558
Duncan Sandscdb6d922007-09-17 10:26:40 +00004559 // Insert the chain's type into the list of parameter types, which may
Duncan Sandsb0c9b932008-01-14 19:52:09 +00004560 // mean appending it.
Duncan Sandscdb6d922007-09-17 10:26:40 +00004561 {
4562 unsigned Idx = 1;
4563 FunctionType::param_iterator I = FTy->param_begin(),
4564 E = FTy->param_end();
4565
4566 do {
Duncan Sandsb0c9b932008-01-14 19:52:09 +00004567 if (Idx == NestIdx)
4568 // Add the chain's type.
Duncan Sandscdb6d922007-09-17 10:26:40 +00004569 NewTypes.push_back(NestTy);
Duncan Sandscdb6d922007-09-17 10:26:40 +00004570
4571 if (I == E)
4572 break;
4573
Duncan Sandsb0c9b932008-01-14 19:52:09 +00004574 // Add the original type.
Duncan Sandscdb6d922007-09-17 10:26:40 +00004575 NewTypes.push_back(*I);
Duncan Sandscdb6d922007-09-17 10:26:40 +00004576
4577 ++Idx, ++I;
4578 } while (1);
4579 }
4580
4581 // Replace the trampoline call with a direct call. Let the generic
4582 // code sort out any function type mismatches.
Owen Andersondebcb012009-07-29 22:17:13 +00004583 FunctionType *NewFTy = FunctionType::get(FTy->getReturnType(), NewTypes,
Owen Andersond672ecb2009-07-03 00:17:18 +00004584 FTy->isVarArg());
4585 Constant *NewCallee =
Owen Andersondebcb012009-07-29 22:17:13 +00004586 NestF->getType() == PointerType::getUnqual(NewFTy) ?
Owen Andersonbaf3c402009-07-29 18:55:55 +00004587 NestF : ConstantExpr::getBitCast(NestF,
Owen Andersondebcb012009-07-29 22:17:13 +00004588 PointerType::getUnqual(NewFTy));
Eric Christophera66297a2009-07-25 02:45:27 +00004589 const AttrListPtr &NewPAL = AttrListPtr::get(NewAttrs.begin(),
4590 NewAttrs.end());
Duncan Sandscdb6d922007-09-17 10:26:40 +00004591
4592 Instruction *NewCaller;
4593 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Gabor Greif051a9502008-04-06 20:25:17 +00004594 NewCaller = InvokeInst::Create(NewCallee,
4595 II->getNormalDest(), II->getUnwindDest(),
4596 NewArgs.begin(), NewArgs.end(),
4597 Caller->getName(), Caller);
Duncan Sandscdb6d922007-09-17 10:26:40 +00004598 cast<InvokeInst>(NewCaller)->setCallingConv(II->getCallingConv());
Devang Patel05988662008-09-25 21:00:45 +00004599 cast<InvokeInst>(NewCaller)->setAttributes(NewPAL);
Duncan Sandscdb6d922007-09-17 10:26:40 +00004600 } else {
Gabor Greif051a9502008-04-06 20:25:17 +00004601 NewCaller = CallInst::Create(NewCallee, NewArgs.begin(), NewArgs.end(),
4602 Caller->getName(), Caller);
Duncan Sandscdb6d922007-09-17 10:26:40 +00004603 if (cast<CallInst>(Caller)->isTailCall())
4604 cast<CallInst>(NewCaller)->setTailCall();
4605 cast<CallInst>(NewCaller)->
4606 setCallingConv(cast<CallInst>(Caller)->getCallingConv());
Devang Patel05988662008-09-25 21:00:45 +00004607 cast<CallInst>(NewCaller)->setAttributes(NewPAL);
Duncan Sandscdb6d922007-09-17 10:26:40 +00004608 }
Devang Patel9674d152009-10-14 17:29:00 +00004609 if (!Caller->getType()->isVoidTy())
Duncan Sandscdb6d922007-09-17 10:26:40 +00004610 Caller->replaceAllUsesWith(NewCaller);
4611 Caller->eraseFromParent();
Chris Lattner7a1e9242009-08-30 06:13:40 +00004612 Worklist.Remove(Caller);
Duncan Sandscdb6d922007-09-17 10:26:40 +00004613 return 0;
4614 }
4615 }
4616
4617 // Replace the trampoline call with a direct call. Since there is no 'nest'
4618 // parameter, there is no need to adjust the argument list. Let the generic
4619 // code sort out any function type mismatches.
4620 Constant *NewCallee =
Owen Andersond672ecb2009-07-03 00:17:18 +00004621 NestF->getType() == PTy ? NestF :
Owen Andersonbaf3c402009-07-29 18:55:55 +00004622 ConstantExpr::getBitCast(NestF, PTy);
Duncan Sandscdb6d922007-09-17 10:26:40 +00004623 CS.setCalledFunction(NewCallee);
4624 return CS.getInstruction();
4625}
4626
Reid Spencere4d87aa2006-12-23 06:05:41 +00004627
Chris Lattner473945d2002-05-06 18:06:38 +00004628
Chris Lattner7e708292002-06-25 16:13:24 +00004629Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
Chris Lattnerc514c1f2009-11-27 00:29:05 +00004630 SmallVector<Value*, 8> Ops(GEP.op_begin(), GEP.op_end());
4631
4632 if (Value *V = SimplifyGEPInst(&Ops[0], Ops.size(), TD))
4633 return ReplaceInstUsesWith(GEP, V);
4634
Chris Lattner620ce142004-05-07 22:09:22 +00004635 Value *PtrOp = GEP.getOperand(0);
Chris Lattnerc6bd1952004-02-22 05:25:17 +00004636
Chris Lattnere87597f2004-10-16 18:11:37 +00004637 if (isa<UndefValue>(GEP.getOperand(0)))
Owen Anderson9e9a0d52009-07-30 23:03:37 +00004638 return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00004639
Chris Lattner28977af2004-04-05 01:30:19 +00004640 // Eliminate unneeded casts for indices.
Chris Lattnerccf4b342009-08-30 04:49:01 +00004641 if (TD) {
4642 bool MadeChange = false;
4643 unsigned PtrSize = TD->getPointerSizeInBits();
4644
4645 gep_type_iterator GTI = gep_type_begin(GEP);
4646 for (User::op_iterator I = GEP.op_begin() + 1, E = GEP.op_end();
4647 I != E; ++I, ++GTI) {
4648 if (!isa<SequentialType>(*GTI)) continue;
4649
Chris Lattnercb69a4e2004-04-07 18:38:20 +00004650 // If we are using a wider index than needed for this platform, shrink it
Chris Lattnerccf4b342009-08-30 04:49:01 +00004651 // to what we need. If narrower, sign-extend it to what we need. This
4652 // explicit cast can make subsequent optimizations more obvious.
4653 unsigned OpBits = cast<IntegerType>((*I)->getType())->getBitWidth();
Chris Lattnerccf4b342009-08-30 04:49:01 +00004654 if (OpBits == PtrSize)
4655 continue;
4656
Chris Lattner2345d1d2009-08-30 20:01:10 +00004657 *I = Builder->CreateIntCast(*I, TD->getIntPtrType(GEP.getContext()),true);
Chris Lattnerccf4b342009-08-30 04:49:01 +00004658 MadeChange = true;
Chris Lattner28977af2004-04-05 01:30:19 +00004659 }
Chris Lattnerccf4b342009-08-30 04:49:01 +00004660 if (MadeChange) return &GEP;
Chris Lattnerdb9654e2007-03-25 20:43:09 +00004661 }
Chris Lattner28977af2004-04-05 01:30:19 +00004662
Chris Lattner90ac28c2002-08-02 19:29:35 +00004663 // Combine Indices - If the source pointer to this getelementptr instruction
4664 // is a getelementptr instruction, combine the indices of the two
4665 // getelementptr instructions into a single instruction.
4666 //
Dan Gohmand6aa02d2009-07-28 01:40:03 +00004667 if (GEPOperator *Src = dyn_cast<GEPOperator>(PtrOp)) {
Chris Lattner620ce142004-05-07 22:09:22 +00004668 // Note that if our source is a gep chain itself that we wait for that
4669 // chain to be resolved before we perform this transformation. This
4670 // avoids us creating a TON of code in some cases.
4671 //
Chris Lattnerf9b91bb2009-08-30 05:08:50 +00004672 if (GetElementPtrInst *SrcGEP =
4673 dyn_cast<GetElementPtrInst>(Src->getOperand(0)))
4674 if (SrcGEP->getNumOperands() == 2)
4675 return 0; // Wait until our source is folded to completion.
Chris Lattner620ce142004-05-07 22:09:22 +00004676
Chris Lattner72588fc2007-02-15 22:48:32 +00004677 SmallVector<Value*, 8> Indices;
Chris Lattner620ce142004-05-07 22:09:22 +00004678
4679 // Find out whether the last index in the source GEP is a sequential idx.
4680 bool EndsWithSequential = false;
Chris Lattnerab984842009-08-30 05:30:55 +00004681 for (gep_type_iterator I = gep_type_begin(*Src), E = gep_type_end(*Src);
4682 I != E; ++I)
Chris Lattnerbe97b4e2004-05-08 22:41:42 +00004683 EndsWithSequential = !isa<StructType>(*I);
Misha Brukmanfd939082005-04-21 23:48:37 +00004684
Chris Lattner90ac28c2002-08-02 19:29:35 +00004685 // Can we combine the two pointer arithmetics offsets?
Chris Lattner620ce142004-05-07 22:09:22 +00004686 if (EndsWithSequential) {
Chris Lattnerdecd0812003-03-05 22:33:14 +00004687 // Replace: gep (gep %P, long B), long A, ...
4688 // With: T = long A+B; gep %P, T, ...
4689 //
Chris Lattnerf9b91bb2009-08-30 05:08:50 +00004690 Value *Sum;
4691 Value *SO1 = Src->getOperand(Src->getNumOperands()-1);
4692 Value *GO1 = GEP.getOperand(1);
Owen Andersona7235ea2009-07-31 20:28:14 +00004693 if (SO1 == Constant::getNullValue(SO1->getType())) {
Chris Lattner28977af2004-04-05 01:30:19 +00004694 Sum = GO1;
Owen Andersona7235ea2009-07-31 20:28:14 +00004695 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
Chris Lattner28977af2004-04-05 01:30:19 +00004696 Sum = SO1;
4697 } else {
Chris Lattnerab984842009-08-30 05:30:55 +00004698 // If they aren't the same type, then the input hasn't been processed
4699 // by the loop above yet (which canonicalizes sequential index types to
4700 // intptr_t). Just avoid transforming this until the input has been
4701 // normalized.
4702 if (SO1->getType() != GO1->getType())
4703 return 0;
Chris Lattnerf925cbd2009-08-30 18:50:58 +00004704 Sum = Builder->CreateAdd(SO1, GO1, PtrOp->getName()+".sum");
Chris Lattner28977af2004-04-05 01:30:19 +00004705 }
Chris Lattner620ce142004-05-07 22:09:22 +00004706
Chris Lattnerab984842009-08-30 05:30:55 +00004707 // Update the GEP in place if possible.
Chris Lattnerf9b91bb2009-08-30 05:08:50 +00004708 if (Src->getNumOperands() == 2) {
4709 GEP.setOperand(0, Src->getOperand(0));
Chris Lattner620ce142004-05-07 22:09:22 +00004710 GEP.setOperand(1, Sum);
4711 return &GEP;
Chris Lattner620ce142004-05-07 22:09:22 +00004712 }
Chris Lattnerab984842009-08-30 05:30:55 +00004713 Indices.append(Src->op_begin()+1, Src->op_end()-1);
Chris Lattnerccf4b342009-08-30 04:49:01 +00004714 Indices.push_back(Sum);
Chris Lattnerab984842009-08-30 05:30:55 +00004715 Indices.append(GEP.op_begin()+2, GEP.op_end());
Misha Brukmanfd939082005-04-21 23:48:37 +00004716 } else if (isa<Constant>(*GEP.idx_begin()) &&
Chris Lattner28977af2004-04-05 01:30:19 +00004717 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
Chris Lattnerf9b91bb2009-08-30 05:08:50 +00004718 Src->getNumOperands() != 1) {
Chris Lattner90ac28c2002-08-02 19:29:35 +00004719 // Otherwise we can do the fold if the first index of the GEP is a zero
Chris Lattnerab984842009-08-30 05:30:55 +00004720 Indices.append(Src->op_begin()+1, Src->op_end());
4721 Indices.append(GEP.idx_begin()+1, GEP.idx_end());
Chris Lattner90ac28c2002-08-02 19:29:35 +00004722 }
4723
Dan Gohmanf8dbee72009-09-07 23:54:19 +00004724 if (!Indices.empty())
4725 return (cast<GEPOperator>(&GEP)->isInBounds() &&
4726 Src->isInBounds()) ?
4727 GetElementPtrInst::CreateInBounds(Src->getOperand(0), Indices.begin(),
4728 Indices.end(), GEP.getName()) :
Chris Lattnerf9b91bb2009-08-30 05:08:50 +00004729 GetElementPtrInst::Create(Src->getOperand(0), Indices.begin(),
Chris Lattnerccf4b342009-08-30 04:49:01 +00004730 Indices.end(), GEP.getName());
Chris Lattner6e24d832009-08-30 05:00:50 +00004731 }
4732
Chris Lattnerf9b91bb2009-08-30 05:08:50 +00004733 // Handle gep(bitcast x) and gep(gep x, 0, 0, 0).
4734 if (Value *X = getBitCastOperand(PtrOp)) {
Chris Lattner6e24d832009-08-30 05:00:50 +00004735 assert(isa<PointerType>(X->getType()) && "Must be cast from pointer");
Chris Lattner963f4ba2009-08-30 20:36:46 +00004736
Chris Lattner2de23192009-08-30 20:38:21 +00004737 // If the input bitcast is actually "bitcast(bitcast(x))", then we don't
4738 // want to change the gep until the bitcasts are eliminated.
4739 if (getBitCastOperand(X)) {
4740 Worklist.AddValue(PtrOp);
4741 return 0;
4742 }
4743
Chris Lattnerc514c1f2009-11-27 00:29:05 +00004744 bool HasZeroPointerIndex = false;
4745 if (ConstantInt *C = dyn_cast<ConstantInt>(GEP.getOperand(1)))
4746 HasZeroPointerIndex = C->isZero();
4747
Chris Lattner963f4ba2009-08-30 20:36:46 +00004748 // Transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ...
4749 // into : GEP [10 x i8]* X, i32 0, ...
4750 //
4751 // Likewise, transform: GEP (bitcast i8* X to [0 x i8]*), i32 0, ...
4752 // into : GEP i8* X, ...
4753 //
4754 // This occurs when the program declares an array extern like "int X[];"
Chris Lattner6e24d832009-08-30 05:00:50 +00004755 if (HasZeroPointerIndex) {
Chris Lattnereed48272005-09-13 00:40:14 +00004756 const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
4757 const PointerType *XTy = cast<PointerType>(X->getType());
Duncan Sands5b7cfb02009-03-02 09:18:21 +00004758 if (const ArrayType *CATy =
4759 dyn_cast<ArrayType>(CPTy->getElementType())) {
4760 // GEP (bitcast i8* X to [0 x i8]*), i32 0, ... ?
4761 if (CATy->getElementType() == XTy->getElementType()) {
4762 // -> GEP i8* X, ...
4763 SmallVector<Value*, 8> Indices(GEP.idx_begin()+1, GEP.idx_end());
Dan Gohmanf8dbee72009-09-07 23:54:19 +00004764 return cast<GEPOperator>(&GEP)->isInBounds() ?
4765 GetElementPtrInst::CreateInBounds(X, Indices.begin(), Indices.end(),
4766 GEP.getName()) :
Dan Gohmand6aa02d2009-07-28 01:40:03 +00004767 GetElementPtrInst::Create(X, Indices.begin(), Indices.end(),
4768 GEP.getName());
Chris Lattner963f4ba2009-08-30 20:36:46 +00004769 }
4770
4771 if (const ArrayType *XATy = dyn_cast<ArrayType>(XTy->getElementType())){
Duncan Sands5b7cfb02009-03-02 09:18:21 +00004772 // GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ... ?
Chris Lattnereed48272005-09-13 00:40:14 +00004773 if (CATy->getElementType() == XATy->getElementType()) {
Duncan Sands5b7cfb02009-03-02 09:18:21 +00004774 // -> GEP [10 x i8]* X, i32 0, ...
Chris Lattnereed48272005-09-13 00:40:14 +00004775 // At this point, we know that the cast source type is a pointer
4776 // to an array of the same type as the destination pointer
4777 // array. Because the array type is never stepped over (there
4778 // is a leading zero) we can fold the cast into this GEP.
4779 GEP.setOperand(0, X);
4780 return &GEP;
4781 }
Duncan Sands5b7cfb02009-03-02 09:18:21 +00004782 }
4783 }
Chris Lattnereed48272005-09-13 00:40:14 +00004784 } else if (GEP.getNumOperands() == 2) {
4785 // Transform things like:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +00004786 // %t = getelementptr i32* bitcast ([2 x i32]* %str to i32*), i32 %V
4787 // into: %t1 = getelementptr [2 x i32]* %str, i32 0, i32 %V; bitcast
Chris Lattnereed48272005-09-13 00:40:14 +00004788 const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
4789 const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
Dan Gohmance9fe9f2009-07-21 23:21:54 +00004790 if (TD && isa<ArrayType>(SrcElTy) &&
Duncan Sands777d2302009-05-09 07:06:46 +00004791 TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
4792 TD->getTypeAllocSize(ResElTy)) {
David Greeneb8f74792007-09-04 15:46:09 +00004793 Value *Idx[2];
Chris Lattner4de84762010-01-04 07:02:48 +00004794 Idx[0] = Constant::getNullValue(Type::getInt32Ty(GEP.getContext()));
David Greeneb8f74792007-09-04 15:46:09 +00004795 Idx[1] = GEP.getOperand(1);
Dan Gohmanf8dbee72009-09-07 23:54:19 +00004796 Value *NewGEP = cast<GEPOperator>(&GEP)->isInBounds() ?
4797 Builder->CreateInBoundsGEP(X, Idx, Idx + 2, GEP.getName()) :
Chris Lattnerf925cbd2009-08-30 18:50:58 +00004798 Builder->CreateGEP(X, Idx, Idx + 2, GEP.getName());
Reid Spencer3da59db2006-11-27 01:05:10 +00004799 // V and GEP are both pointer types --> BitCast
Chris Lattnerf925cbd2009-08-30 18:50:58 +00004800 return new BitCastInst(NewGEP, GEP.getType());
Chris Lattnerc6bd1952004-02-22 05:25:17 +00004801 }
Chris Lattner7835cdd2005-09-13 18:36:04 +00004802
4803 // Transform things like:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +00004804 // getelementptr i8* bitcast ([100 x double]* X to i8*), i32 %tmp
Chris Lattner7835cdd2005-09-13 18:36:04 +00004805 // (where tmp = 8*tmp2) into:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +00004806 // getelementptr [100 x double]* %arr, i32 0, i32 %tmp2; bitcast
Chris Lattner7835cdd2005-09-13 18:36:04 +00004807
Chris Lattner4de84762010-01-04 07:02:48 +00004808 if (TD && isa<ArrayType>(SrcElTy) &&
4809 ResElTy == Type::getInt8Ty(GEP.getContext())) {
Chris Lattner7835cdd2005-09-13 18:36:04 +00004810 uint64_t ArrayEltSize =
Duncan Sands777d2302009-05-09 07:06:46 +00004811 TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType());
Chris Lattner7835cdd2005-09-13 18:36:04 +00004812
4813 // Check to see if "tmp" is a scale by a multiple of ArrayEltSize. We
4814 // allow either a mul, shift, or constant here.
4815 Value *NewIdx = 0;
4816 ConstantInt *Scale = 0;
4817 if (ArrayEltSize == 1) {
4818 NewIdx = GEP.getOperand(1);
Chris Lattnerab984842009-08-30 05:30:55 +00004819 Scale = ConstantInt::get(cast<IntegerType>(NewIdx->getType()), 1);
Chris Lattner7835cdd2005-09-13 18:36:04 +00004820 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
Owen Andersoneed707b2009-07-24 23:12:02 +00004821 NewIdx = ConstantInt::get(CI->getType(), 1);
Chris Lattner7835cdd2005-09-13 18:36:04 +00004822 Scale = CI;
4823 } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
4824 if (Inst->getOpcode() == Instruction::Shl &&
4825 isa<ConstantInt>(Inst->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00004826 ConstantInt *ShAmt = cast<ConstantInt>(Inst->getOperand(1));
4827 uint32_t ShAmtVal = ShAmt->getLimitedValue(64);
Owen Andersoneed707b2009-07-24 23:12:02 +00004828 Scale = ConstantInt::get(cast<IntegerType>(Inst->getType()),
Dan Gohman6de29f82009-06-15 22:12:54 +00004829 1ULL << ShAmtVal);
Chris Lattner7835cdd2005-09-13 18:36:04 +00004830 NewIdx = Inst->getOperand(0);
4831 } else if (Inst->getOpcode() == Instruction::Mul &&
4832 isa<ConstantInt>(Inst->getOperand(1))) {
4833 Scale = cast<ConstantInt>(Inst->getOperand(1));
4834 NewIdx = Inst->getOperand(0);
4835 }
4836 }
Wojciech Matyjewiczed223252007-12-12 15:21:32 +00004837
Chris Lattner7835cdd2005-09-13 18:36:04 +00004838 // If the index will be to exactly the right offset with the scale taken
Wojciech Matyjewiczed223252007-12-12 15:21:32 +00004839 // out, perform the transformation. Note, we don't know whether Scale is
4840 // signed or not. We'll use unsigned version of division/modulo
4841 // operation after making sure Scale doesn't have the sign bit set.
Chris Lattner58b1ac72009-02-25 18:20:01 +00004842 if (ArrayEltSize && Scale && Scale->getSExtValue() >= 0LL &&
Wojciech Matyjewiczed223252007-12-12 15:21:32 +00004843 Scale->getZExtValue() % ArrayEltSize == 0) {
Owen Andersoneed707b2009-07-24 23:12:02 +00004844 Scale = ConstantInt::get(Scale->getType(),
Wojciech Matyjewiczed223252007-12-12 15:21:32 +00004845 Scale->getZExtValue() / ArrayEltSize);
Reid Spencerb83eb642006-10-20 07:07:24 +00004846 if (Scale->getZExtValue() != 1) {
Chris Lattner878daed2009-08-30 05:56:44 +00004847 Constant *C = ConstantExpr::getIntegerCast(Scale, NewIdx->getType(),
4848 false /*ZExt*/);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00004849 NewIdx = Builder->CreateMul(NewIdx, C, "idxscale");
Chris Lattner7835cdd2005-09-13 18:36:04 +00004850 }
4851
4852 // Insert the new GEP instruction.
David Greeneb8f74792007-09-04 15:46:09 +00004853 Value *Idx[2];
Chris Lattner4de84762010-01-04 07:02:48 +00004854 Idx[0] = Constant::getNullValue(Type::getInt32Ty(GEP.getContext()));
David Greeneb8f74792007-09-04 15:46:09 +00004855 Idx[1] = NewIdx;
Dan Gohmanf8dbee72009-09-07 23:54:19 +00004856 Value *NewGEP = cast<GEPOperator>(&GEP)->isInBounds() ?
4857 Builder->CreateInBoundsGEP(X, Idx, Idx + 2, GEP.getName()) :
4858 Builder->CreateGEP(X, Idx, Idx + 2, GEP.getName());
Reid Spencer3da59db2006-11-27 01:05:10 +00004859 // The NewGEP must be pointer typed, so must the old one -> BitCast
4860 return new BitCastInst(NewGEP, GEP.getType());
Chris Lattner7835cdd2005-09-13 18:36:04 +00004861 }
4862 }
Chris Lattnerc6bd1952004-02-22 05:25:17 +00004863 }
Chris Lattner8a2a3112001-12-14 16:52:21 +00004864 }
Chris Lattner58407792009-01-09 04:53:57 +00004865
Chris Lattner46cd5a12009-01-09 05:44:56 +00004866 /// See if we can simplify:
Chris Lattner873ff012009-08-30 05:55:36 +00004867 /// X = bitcast A* to B*
Chris Lattner46cd5a12009-01-09 05:44:56 +00004868 /// Y = gep X, <...constant indices...>
4869 /// into a gep of the original struct. This is important for SROA and alias
4870 /// analysis of unions. If "A" is also a bitcast, wait for A/X to be merged.
Chris Lattner58407792009-01-09 04:53:57 +00004871 if (BitCastInst *BCI = dyn_cast<BitCastInst>(PtrOp)) {
Dan Gohmance9fe9f2009-07-21 23:21:54 +00004872 if (TD &&
4873 !isa<BitCastInst>(BCI->getOperand(0)) && GEP.hasAllConstantIndices()) {
Chris Lattner46cd5a12009-01-09 05:44:56 +00004874 // Determine how much the GEP moves the pointer. We are guaranteed to get
4875 // a constant back from EmitGEPOffset.
Chris Lattner02446fc2010-01-04 07:37:31 +00004876 ConstantInt *OffsetV = cast<ConstantInt>(EmitGEPOffset(&GEP));
Chris Lattner46cd5a12009-01-09 05:44:56 +00004877 int64_t Offset = OffsetV->getSExtValue();
4878
4879 // If this GEP instruction doesn't move the pointer, just replace the GEP
4880 // with a bitcast of the real input to the dest type.
4881 if (Offset == 0) {
4882 // If the bitcast is of an allocation, and the allocation will be
4883 // converted to match the type of the cast, don't touch this.
Victor Hernandez7b929da2009-10-23 21:09:37 +00004884 if (isa<AllocaInst>(BCI->getOperand(0)) ||
Victor Hernandez83d63912009-09-18 22:35:49 +00004885 isMalloc(BCI->getOperand(0))) {
Chris Lattner46cd5a12009-01-09 05:44:56 +00004886 // See if the bitcast simplifies, if so, don't nuke this GEP yet.
4887 if (Instruction *I = visitBitCast(*BCI)) {
4888 if (I != BCI) {
4889 I->takeName(BCI);
4890 BCI->getParent()->getInstList().insert(BCI, I);
4891 ReplaceInstUsesWith(*BCI, I);
4892 }
4893 return &GEP;
Chris Lattner58407792009-01-09 04:53:57 +00004894 }
Chris Lattner58407792009-01-09 04:53:57 +00004895 }
Chris Lattner46cd5a12009-01-09 05:44:56 +00004896 return new BitCastInst(BCI->getOperand(0), GEP.getType());
Chris Lattner58407792009-01-09 04:53:57 +00004897 }
Chris Lattner46cd5a12009-01-09 05:44:56 +00004898
4899 // Otherwise, if the offset is non-zero, we need to find out if there is a
4900 // field at Offset in 'A's type. If so, we can pull the cast through the
4901 // GEP.
4902 SmallVector<Value*, 8> NewIndices;
4903 const Type *InTy =
4904 cast<PointerType>(BCI->getOperand(0)->getType())->getElementType();
Chris Lattner80f43d32010-01-04 07:53:58 +00004905 if (FindElementAtOffset(InTy, Offset, NewIndices)) {
Dan Gohmanf8dbee72009-09-07 23:54:19 +00004906 Value *NGEP = cast<GEPOperator>(&GEP)->isInBounds() ?
4907 Builder->CreateInBoundsGEP(BCI->getOperand(0), NewIndices.begin(),
4908 NewIndices.end()) :
4909 Builder->CreateGEP(BCI->getOperand(0), NewIndices.begin(),
4910 NewIndices.end());
Chris Lattnerf925cbd2009-08-30 18:50:58 +00004911
4912 if (NGEP->getType() == GEP.getType())
4913 return ReplaceInstUsesWith(GEP, NGEP);
Chris Lattner46cd5a12009-01-09 05:44:56 +00004914 NGEP->takeName(&GEP);
4915 return new BitCastInst(NGEP, GEP.getType());
4916 }
Chris Lattner58407792009-01-09 04:53:57 +00004917 }
4918 }
4919
Chris Lattner8a2a3112001-12-14 16:52:21 +00004920 return 0;
4921}
4922
Victor Hernandez66284e02009-10-24 04:23:03 +00004923Instruction *InstCombiner::visitFree(Instruction &FI) {
4924 Value *Op = FI.getOperand(1);
4925
4926 // free undef -> unreachable.
4927 if (isa<UndefValue>(Op)) {
4928 // Insert a new store to null because we cannot modify the CFG here.
Chris Lattner4de84762010-01-04 07:02:48 +00004929 new StoreInst(ConstantInt::getTrue(FI.getContext()),
4930 UndefValue::get(Type::getInt1PtrTy(FI.getContext())), &FI);
Victor Hernandez66284e02009-10-24 04:23:03 +00004931 return EraseInstFromFunction(FI);
4932 }
4933
4934 // If we have 'free null' delete the instruction. This can happen in stl code
4935 // when lots of inlining happens.
4936 if (isa<ConstantPointerNull>(Op))
4937 return EraseInstFromFunction(FI);
4938
Victor Hernandez046e78c2009-10-26 23:43:48 +00004939 // If we have a malloc call whose only use is a free call, delete both.
Dan Gohman7f712a12009-10-27 00:11:02 +00004940 if (isMalloc(Op)) {
Victor Hernandez66284e02009-10-24 04:23:03 +00004941 if (CallInst* CI = extractMallocCallFromBitCast(Op)) {
4942 if (Op->hasOneUse() && CI->hasOneUse()) {
4943 EraseInstFromFunction(FI);
4944 EraseInstFromFunction(*CI);
4945 return EraseInstFromFunction(*cast<Instruction>(Op));
4946 }
4947 } else {
4948 // Op is a call to malloc
4949 if (Op->hasOneUse()) {
4950 EraseInstFromFunction(FI);
4951 return EraseInstFromFunction(*cast<Instruction>(Op));
4952 }
4953 }
Dan Gohman7f712a12009-10-27 00:11:02 +00004954 }
Victor Hernandez66284e02009-10-24 04:23:03 +00004955
4956 return 0;
4957}
Chris Lattner67b1e1b2003-12-07 01:24:23 +00004958
Chris Lattner3284d1f2007-04-15 00:07:55 +00004959
Chris Lattner2f503e62005-01-31 05:36:43 +00004960
Chris Lattnerc4d10eb2003-06-04 04:46:00 +00004961Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
4962 // Change br (not X), label True, label False to: br X, label False, True
Reid Spencer4b828e62005-06-18 17:37:34 +00004963 Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004964 BasicBlock *TrueDest;
4965 BasicBlock *FalseDest;
Dan Gohman4ae51262009-08-12 16:23:25 +00004966 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004967 !isa<Constant>(X)) {
4968 // Swap Destinations and condition...
4969 BI.setCondition(X);
4970 BI.setSuccessor(0, FalseDest);
4971 BI.setSuccessor(1, TrueDest);
4972 return &BI;
4973 }
4974
Reid Spencere4d87aa2006-12-23 06:05:41 +00004975 // Cannonicalize fcmp_one -> fcmp_oeq
4976 FCmpInst::Predicate FPred; Value *Y;
4977 if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)),
Chris Lattner7a1e9242009-08-30 06:13:40 +00004978 TrueDest, FalseDest)) &&
4979 BI.getCondition()->hasOneUse())
4980 if (FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
4981 FPred == FCmpInst::FCMP_OGE) {
4982 FCmpInst *Cond = cast<FCmpInst>(BI.getCondition());
4983 Cond->setPredicate(FCmpInst::getInversePredicate(FPred));
4984
4985 // Swap Destinations and condition.
Reid Spencere4d87aa2006-12-23 06:05:41 +00004986 BI.setSuccessor(0, FalseDest);
4987 BI.setSuccessor(1, TrueDest);
Chris Lattner7a1e9242009-08-30 06:13:40 +00004988 Worklist.Add(Cond);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004989 return &BI;
4990 }
4991
4992 // Cannonicalize icmp_ne -> icmp_eq
4993 ICmpInst::Predicate IPred;
4994 if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
Chris Lattner7a1e9242009-08-30 06:13:40 +00004995 TrueDest, FalseDest)) &&
4996 BI.getCondition()->hasOneUse())
4997 if (IPred == ICmpInst::ICMP_NE || IPred == ICmpInst::ICMP_ULE ||
4998 IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
4999 IPred == ICmpInst::ICMP_SGE) {
5000 ICmpInst *Cond = cast<ICmpInst>(BI.getCondition());
5001 Cond->setPredicate(ICmpInst::getInversePredicate(IPred));
5002 // Swap Destinations and condition.
Chris Lattner40f5d702003-06-04 05:10:11 +00005003 BI.setSuccessor(0, FalseDest);
5004 BI.setSuccessor(1, TrueDest);
Chris Lattner7a1e9242009-08-30 06:13:40 +00005005 Worklist.Add(Cond);
Chris Lattner40f5d702003-06-04 05:10:11 +00005006 return &BI;
5007 }
Misha Brukmanfd939082005-04-21 23:48:37 +00005008
Chris Lattnerc4d10eb2003-06-04 04:46:00 +00005009 return 0;
5010}
Chris Lattner0864acf2002-11-04 16:18:53 +00005011
Chris Lattner46238a62004-07-03 00:26:11 +00005012Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
5013 Value *Cond = SI.getCondition();
5014 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
5015 if (I->getOpcode() == Instruction::Add)
5016 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
5017 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
5018 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
Owen Andersond672ecb2009-07-03 00:17:18 +00005019 SI.setOperand(i,
Owen Andersonbaf3c402009-07-29 18:55:55 +00005020 ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
Chris Lattner46238a62004-07-03 00:26:11 +00005021 AddRHS));
5022 SI.setOperand(0, I->getOperand(0));
Chris Lattner7a1e9242009-08-30 06:13:40 +00005023 Worklist.Add(I);
Chris Lattner46238a62004-07-03 00:26:11 +00005024 return &SI;
5025 }
5026 }
5027 return 0;
5028}
5029
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +00005030Instruction *InstCombiner::visitExtractValueInst(ExtractValueInst &EV) {
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +00005031 Value *Agg = EV.getAggregateOperand();
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +00005032
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +00005033 if (!EV.hasIndices())
5034 return ReplaceInstUsesWith(EV, Agg);
5035
5036 if (Constant *C = dyn_cast<Constant>(Agg)) {
5037 if (isa<UndefValue>(C))
Owen Anderson9e9a0d52009-07-30 23:03:37 +00005038 return ReplaceInstUsesWith(EV, UndefValue::get(EV.getType()));
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +00005039
5040 if (isa<ConstantAggregateZero>(C))
Owen Andersona7235ea2009-07-31 20:28:14 +00005041 return ReplaceInstUsesWith(EV, Constant::getNullValue(EV.getType()));
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +00005042
5043 if (isa<ConstantArray>(C) || isa<ConstantStruct>(C)) {
5044 // Extract the element indexed by the first index out of the constant
5045 Value *V = C->getOperand(*EV.idx_begin());
5046 if (EV.getNumIndices() > 1)
5047 // Extract the remaining indices out of the constant indexed by the
5048 // first index
5049 return ExtractValueInst::Create(V, EV.idx_begin() + 1, EV.idx_end());
5050 else
5051 return ReplaceInstUsesWith(EV, V);
5052 }
5053 return 0; // Can't handle other constants
5054 }
5055 if (InsertValueInst *IV = dyn_cast<InsertValueInst>(Agg)) {
5056 // We're extracting from an insertvalue instruction, compare the indices
5057 const unsigned *exti, *exte, *insi, *inse;
5058 for (exti = EV.idx_begin(), insi = IV->idx_begin(),
5059 exte = EV.idx_end(), inse = IV->idx_end();
5060 exti != exte && insi != inse;
5061 ++exti, ++insi) {
5062 if (*insi != *exti)
5063 // The insert and extract both reference distinctly different elements.
5064 // This means the extract is not influenced by the insert, and we can
5065 // replace the aggregate operand of the extract with the aggregate
5066 // operand of the insert. i.e., replace
5067 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
5068 // %E = extractvalue { i32, { i32 } } %I, 0
5069 // with
5070 // %E = extractvalue { i32, { i32 } } %A, 0
5071 return ExtractValueInst::Create(IV->getAggregateOperand(),
5072 EV.idx_begin(), EV.idx_end());
5073 }
5074 if (exti == exte && insi == inse)
5075 // Both iterators are at the end: Index lists are identical. Replace
5076 // %B = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
5077 // %C = extractvalue { i32, { i32 } } %B, 1, 0
5078 // with "i32 42"
5079 return ReplaceInstUsesWith(EV, IV->getInsertedValueOperand());
5080 if (exti == exte) {
5081 // The extract list is a prefix of the insert list. i.e. replace
5082 // %I = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
5083 // %E = extractvalue { i32, { i32 } } %I, 1
5084 // with
5085 // %X = extractvalue { i32, { i32 } } %A, 1
5086 // %E = insertvalue { i32 } %X, i32 42, 0
5087 // by switching the order of the insert and extract (though the
5088 // insertvalue should be left in, since it may have other uses).
Chris Lattnerf925cbd2009-08-30 18:50:58 +00005089 Value *NewEV = Builder->CreateExtractValue(IV->getAggregateOperand(),
5090 EV.idx_begin(), EV.idx_end());
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +00005091 return InsertValueInst::Create(NewEV, IV->getInsertedValueOperand(),
5092 insi, inse);
5093 }
5094 if (insi == inse)
5095 // The insert list is a prefix of the extract list
5096 // We can simply remove the common indices from the extract and make it
5097 // operate on the inserted value instead of the insertvalue result.
5098 // i.e., replace
5099 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
5100 // %E = extractvalue { i32, { i32 } } %I, 1, 0
5101 // with
5102 // %E extractvalue { i32 } { i32 42 }, 0
5103 return ExtractValueInst::Create(IV->getInsertedValueOperand(),
5104 exti, exte);
5105 }
Chris Lattner7e606e22009-11-09 07:07:56 +00005106 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Agg)) {
5107 // We're extracting from an intrinsic, see if we're the only user, which
5108 // allows us to simplify multiple result intrinsics to simpler things that
5109 // just get one value..
5110 if (II->hasOneUse()) {
5111 // Check if we're grabbing the overflow bit or the result of a 'with
5112 // overflow' intrinsic. If it's the latter we can remove the intrinsic
5113 // and replace it with a traditional binary instruction.
5114 switch (II->getIntrinsicID()) {
5115 case Intrinsic::uadd_with_overflow:
5116 case Intrinsic::sadd_with_overflow:
5117 if (*EV.idx_begin() == 0) { // Normal result.
5118 Value *LHS = II->getOperand(1), *RHS = II->getOperand(2);
5119 II->replaceAllUsesWith(UndefValue::get(II->getType()));
5120 EraseInstFromFunction(*II);
5121 return BinaryOperator::CreateAdd(LHS, RHS);
5122 }
5123 break;
5124 case Intrinsic::usub_with_overflow:
5125 case Intrinsic::ssub_with_overflow:
5126 if (*EV.idx_begin() == 0) { // Normal result.
5127 Value *LHS = II->getOperand(1), *RHS = II->getOperand(2);
5128 II->replaceAllUsesWith(UndefValue::get(II->getType()));
5129 EraseInstFromFunction(*II);
5130 return BinaryOperator::CreateSub(LHS, RHS);
5131 }
5132 break;
5133 case Intrinsic::umul_with_overflow:
5134 case Intrinsic::smul_with_overflow:
5135 if (*EV.idx_begin() == 0) { // Normal result.
5136 Value *LHS = II->getOperand(1), *RHS = II->getOperand(2);
5137 II->replaceAllUsesWith(UndefValue::get(II->getType()));
5138 EraseInstFromFunction(*II);
5139 return BinaryOperator::CreateMul(LHS, RHS);
5140 }
5141 break;
5142 default:
5143 break;
5144 }
5145 }
5146 }
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +00005147 // Can't simplify extracts from other values. Note that nested extracts are
5148 // already simplified implicitely by the above (extract ( extract (insert) )
5149 // will be translated into extract ( insert ( extract ) ) first and then just
5150 // the value inserted, if appropriate).
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +00005151 return 0;
5152}
5153
Chris Lattnera844fc4c2006-04-10 22:45:52 +00005154
Robert Bocchino1d7456d2006-01-13 22:48:06 +00005155
Chris Lattnerea1c4542004-12-08 23:43:58 +00005156
5157/// TryToSinkInstruction - Try to move the specified instruction from its
5158/// current block into the beginning of DestBlock, which can only happen if it's
5159/// safe to move the instruction past all of the instructions between it and the
5160/// end of its block.
5161static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
5162 assert(I->hasOneUse() && "Invariants didn't hold!");
5163
Chris Lattner108e9022005-10-27 17:13:11 +00005164 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
Duncan Sands7af1c782009-05-06 06:49:50 +00005165 if (isa<PHINode>(I) || I->mayHaveSideEffects() || isa<TerminatorInst>(I))
Chris Lattnerbfc538c2008-05-09 15:07:33 +00005166 return false;
Misha Brukmanfd939082005-04-21 23:48:37 +00005167
Chris Lattnerea1c4542004-12-08 23:43:58 +00005168 // Do not sink alloca instructions out of the entry block.
Dan Gohmanecb7a772007-03-22 16:38:57 +00005169 if (isa<AllocaInst>(I) && I->getParent() ==
5170 &DestBlock->getParent()->getEntryBlock())
Chris Lattnerea1c4542004-12-08 23:43:58 +00005171 return false;
5172
Chris Lattner96a52a62004-12-09 07:14:34 +00005173 // We can only sink load instructions if there is nothing between the load and
5174 // the end of block that could change the value.
Chris Lattner2539e332008-05-08 17:37:37 +00005175 if (I->mayReadFromMemory()) {
5176 for (BasicBlock::iterator Scan = I, E = I->getParent()->end();
Chris Lattner96a52a62004-12-09 07:14:34 +00005177 Scan != E; ++Scan)
5178 if (Scan->mayWriteToMemory())
5179 return false;
Chris Lattner96a52a62004-12-09 07:14:34 +00005180 }
Chris Lattnerea1c4542004-12-08 23:43:58 +00005181
Dan Gohman02dea8b2008-05-23 21:05:58 +00005182 BasicBlock::iterator InsertPos = DestBlock->getFirstNonPHI();
Chris Lattnerea1c4542004-12-08 23:43:58 +00005183
Chris Lattner4bc5f802005-08-08 19:11:57 +00005184 I->moveBefore(InsertPos);
Chris Lattnerea1c4542004-12-08 23:43:58 +00005185 ++NumSunkInst;
5186 return true;
5187}
5188
Chris Lattnerf4f5a772006-05-10 19:00:36 +00005189
5190/// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
5191/// all reachable code to the worklist.
5192///
5193/// This has a couple of tricks to make the code faster and more powerful. In
5194/// particular, we constant fold and DCE instructions as we go, to avoid adding
5195/// them to the worklist (this significantly speeds up instcombine on code where
5196/// many instructions are dead or constant). Additionally, if we find a branch
5197/// whose condition is a known constant, we only visit the reachable successors.
5198///
Chris Lattner2ee743b2009-10-15 04:59:28 +00005199static bool AddReachableCodeToWorklist(BasicBlock *BB,
Chris Lattner1f87a582007-02-15 19:41:52 +00005200 SmallPtrSet<BasicBlock*, 64> &Visited,
Chris Lattnerdbab3862007-03-02 21:28:56 +00005201 InstCombiner &IC,
Chris Lattner8c8c66a2006-05-11 17:11:52 +00005202 const TargetData *TD) {
Chris Lattner2ee743b2009-10-15 04:59:28 +00005203 bool MadeIRChange = false;
Chris Lattner2806dff2008-08-15 04:03:01 +00005204 SmallVector<BasicBlock*, 256> Worklist;
Chris Lattner2c7718a2007-03-23 19:17:18 +00005205 Worklist.push_back(BB);
Chris Lattner67f7d542009-10-12 03:58:40 +00005206
5207 std::vector<Instruction*> InstrsForInstCombineWorklist;
5208 InstrsForInstCombineWorklist.reserve(128);
Chris Lattnerf4f5a772006-05-10 19:00:36 +00005209
Chris Lattner2ee743b2009-10-15 04:59:28 +00005210 SmallPtrSet<ConstantExpr*, 64> FoldedConstants;
5211
Chris Lattner2c7718a2007-03-23 19:17:18 +00005212 while (!Worklist.empty()) {
5213 BB = Worklist.back();
5214 Worklist.pop_back();
5215
5216 // We have now visited this block! If we've already been here, ignore it.
5217 if (!Visited.insert(BB)) continue;
Devang Patel7fe1dec2008-11-19 18:56:50 +00005218
Chris Lattner2c7718a2007-03-23 19:17:18 +00005219 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
5220 Instruction *Inst = BBI++;
Chris Lattnerf4f5a772006-05-10 19:00:36 +00005221
Chris Lattner2c7718a2007-03-23 19:17:18 +00005222 // DCE instruction if trivially dead.
5223 if (isInstructionTriviallyDead(Inst)) {
5224 ++NumDeadInst;
Chris Lattnerbdff5482009-08-23 04:37:46 +00005225 DEBUG(errs() << "IC: DCE: " << *Inst << '\n');
Chris Lattner2c7718a2007-03-23 19:17:18 +00005226 Inst->eraseFromParent();
5227 continue;
5228 }
5229
5230 // ConstantProp instruction if trivially constant.
Chris Lattnere2cc1ad2009-10-15 04:13:44 +00005231 if (!Inst->use_empty() && isa<Constant>(Inst->getOperand(0)))
Chris Lattner7b550cc2009-11-06 04:27:31 +00005232 if (Constant *C = ConstantFoldInstruction(Inst, TD)) {
Chris Lattnere2cc1ad2009-10-15 04:13:44 +00005233 DEBUG(errs() << "IC: ConstFold to: " << *C << " from: "
5234 << *Inst << '\n');
5235 Inst->replaceAllUsesWith(C);
5236 ++NumConstProp;
5237 Inst->eraseFromParent();
5238 continue;
5239 }
Chris Lattner2ee743b2009-10-15 04:59:28 +00005240
5241
5242
5243 if (TD) {
5244 // See if we can constant fold its operands.
5245 for (User::op_iterator i = Inst->op_begin(), e = Inst->op_end();
5246 i != e; ++i) {
5247 ConstantExpr *CE = dyn_cast<ConstantExpr>(i);
5248 if (CE == 0) continue;
5249
5250 // If we already folded this constant, don't try again.
5251 if (!FoldedConstants.insert(CE))
5252 continue;
5253
Chris Lattner7b550cc2009-11-06 04:27:31 +00005254 Constant *NewC = ConstantFoldConstantExpression(CE, TD);
Chris Lattner2ee743b2009-10-15 04:59:28 +00005255 if (NewC && NewC != CE) {
5256 *i = NewC;
5257 MadeIRChange = true;
5258 }
5259 }
5260 }
5261
Devang Patel7fe1dec2008-11-19 18:56:50 +00005262
Chris Lattner67f7d542009-10-12 03:58:40 +00005263 InstrsForInstCombineWorklist.push_back(Inst);
Chris Lattnerf4f5a772006-05-10 19:00:36 +00005264 }
Chris Lattner2c7718a2007-03-23 19:17:18 +00005265
5266 // Recursively visit successors. If this is a branch or switch on a
5267 // constant, only visit the reachable successor.
5268 TerminatorInst *TI = BB->getTerminator();
5269 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
5270 if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
5271 bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
Nick Lewycky91436992008-03-09 08:50:23 +00005272 BasicBlock *ReachableBB = BI->getSuccessor(!CondVal);
Nick Lewycky280a6e62008-04-25 16:53:59 +00005273 Worklist.push_back(ReachableBB);
Chris Lattner2c7718a2007-03-23 19:17:18 +00005274 continue;
5275 }
5276 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
5277 if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
5278 // See if this is an explicit destination.
5279 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
5280 if (SI->getCaseValue(i) == Cond) {
Nick Lewycky91436992008-03-09 08:50:23 +00005281 BasicBlock *ReachableBB = SI->getSuccessor(i);
Nick Lewycky280a6e62008-04-25 16:53:59 +00005282 Worklist.push_back(ReachableBB);
Chris Lattner2c7718a2007-03-23 19:17:18 +00005283 continue;
5284 }
5285
5286 // Otherwise it is the default destination.
5287 Worklist.push_back(SI->getSuccessor(0));
5288 continue;
5289 }
5290 }
5291
5292 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
5293 Worklist.push_back(TI->getSuccessor(i));
Chris Lattnerf4f5a772006-05-10 19:00:36 +00005294 }
Chris Lattner67f7d542009-10-12 03:58:40 +00005295
5296 // Once we've found all of the instructions to add to instcombine's worklist,
5297 // add them in reverse order. This way instcombine will visit from the top
5298 // of the function down. This jives well with the way that it adds all uses
5299 // of instructions to the worklist after doing a transformation, thus avoiding
5300 // some N^2 behavior in pathological cases.
5301 IC.Worklist.AddInitialGroup(&InstrsForInstCombineWorklist[0],
5302 InstrsForInstCombineWorklist.size());
Chris Lattner2ee743b2009-10-15 04:59:28 +00005303
5304 return MadeIRChange;
Chris Lattnerf4f5a772006-05-10 19:00:36 +00005305}
5306
Chris Lattnerec9c3582007-03-03 02:04:50 +00005307bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) {
Chris Lattnerb0b822c2009-08-31 06:57:37 +00005308 MadeIRChange = false;
Chris Lattnerec9c3582007-03-03 02:04:50 +00005309
Daniel Dunbarce63ffb2009-07-25 00:23:56 +00005310 DEBUG(errs() << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
5311 << F.getNameStr() << "\n");
Chris Lattner8a2a3112001-12-14 16:52:21 +00005312
Chris Lattnerb3d59702005-07-07 20:40:38 +00005313 {
Chris Lattnerf4f5a772006-05-10 19:00:36 +00005314 // Do a depth-first traversal of the function, populate the worklist with
5315 // the reachable instructions. Ignore blocks that are not reachable. Keep
5316 // track of which blocks we visit.
Chris Lattner1f87a582007-02-15 19:41:52 +00005317 SmallPtrSet<BasicBlock*, 64> Visited;
Chris Lattner2ee743b2009-10-15 04:59:28 +00005318 MadeIRChange |= AddReachableCodeToWorklist(F.begin(), Visited, *this, TD);
Jeff Cohen00b168892005-07-27 06:12:32 +00005319
Chris Lattnerb3d59702005-07-07 20:40:38 +00005320 // Do a quick scan over the function. If we find any blocks that are
5321 // unreachable, remove any instructions inside of them. This prevents
5322 // the instcombine code from having to deal with some bad special cases.
5323 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
5324 if (!Visited.count(BB)) {
5325 Instruction *Term = BB->getTerminator();
5326 while (Term != BB->begin()) { // Remove instrs bottom-up
5327 BasicBlock::iterator I = Term; --I;
Chris Lattner6ffe5512004-04-27 15:13:33 +00005328
Chris Lattnerbdff5482009-08-23 04:37:46 +00005329 DEBUG(errs() << "IC: DCE: " << *I << '\n');
Dale Johannesenff278b12009-03-10 21:19:49 +00005330 // A debug intrinsic shouldn't force another iteration if we weren't
5331 // going to do one without it.
5332 if (!isa<DbgInfoIntrinsic>(I)) {
5333 ++NumDeadInst;
Chris Lattnerb0b822c2009-08-31 06:57:37 +00005334 MadeIRChange = true;
Dale Johannesenff278b12009-03-10 21:19:49 +00005335 }
Devang Patel228ebd02009-10-13 22:56:32 +00005336
Devang Patel228ebd02009-10-13 22:56:32 +00005337 // If I is not void type then replaceAllUsesWith undef.
5338 // This allows ValueHandlers and custom metadata to adjust itself.
Devang Patel9674d152009-10-14 17:29:00 +00005339 if (!I->getType()->isVoidTy())
Devang Patel228ebd02009-10-13 22:56:32 +00005340 I->replaceAllUsesWith(UndefValue::get(I->getType()));
Chris Lattnerb3d59702005-07-07 20:40:38 +00005341 I->eraseFromParent();
5342 }
5343 }
5344 }
Chris Lattner8a2a3112001-12-14 16:52:21 +00005345
Chris Lattner873ff012009-08-30 05:55:36 +00005346 while (!Worklist.isEmpty()) {
5347 Instruction *I = Worklist.RemoveOne();
Chris Lattnerdbab3862007-03-02 21:28:56 +00005348 if (I == 0) continue; // skip null values.
Chris Lattner8a2a3112001-12-14 16:52:21 +00005349
Chris Lattner8c8c66a2006-05-11 17:11:52 +00005350 // Check to see if we can DCE the instruction.
Chris Lattner62b14df2002-09-02 04:59:56 +00005351 if (isInstructionTriviallyDead(I)) {
Chris Lattnerbdff5482009-08-23 04:37:46 +00005352 DEBUG(errs() << "IC: DCE: " << *I << '\n');
Chris Lattner7a1e9242009-08-30 06:13:40 +00005353 EraseInstFromFunction(*I);
5354 ++NumDeadInst;
Chris Lattnerb0b822c2009-08-31 06:57:37 +00005355 MadeIRChange = true;
Chris Lattner4bb7c022003-10-06 17:11:01 +00005356 continue;
5357 }
Chris Lattner62b14df2002-09-02 04:59:56 +00005358
Chris Lattner8c8c66a2006-05-11 17:11:52 +00005359 // Instruction isn't dead, see if we can constant propagate it.
Chris Lattnere2cc1ad2009-10-15 04:13:44 +00005360 if (!I->use_empty() && isa<Constant>(I->getOperand(0)))
Chris Lattner7b550cc2009-11-06 04:27:31 +00005361 if (Constant *C = ConstantFoldInstruction(I, TD)) {
Chris Lattnere2cc1ad2009-10-15 04:13:44 +00005362 DEBUG(errs() << "IC: ConstFold to: " << *C << " from: " << *I << '\n');
Chris Lattnerad5fec12005-01-28 19:32:01 +00005363
Chris Lattnere2cc1ad2009-10-15 04:13:44 +00005364 // Add operands to the worklist.
5365 ReplaceInstUsesWith(*I, C);
5366 ++NumConstProp;
5367 EraseInstFromFunction(*I);
5368 MadeIRChange = true;
5369 continue;
5370 }
Chris Lattner4bb7c022003-10-06 17:11:01 +00005371
Chris Lattnerea1c4542004-12-08 23:43:58 +00005372 // See if we can trivially sink this instruction to a successor basic block.
Dan Gohmanfc74abf2008-07-23 00:34:11 +00005373 if (I->hasOneUse()) {
Chris Lattnerea1c4542004-12-08 23:43:58 +00005374 BasicBlock *BB = I->getParent();
Chris Lattner8db2cd12009-10-14 15:21:58 +00005375 Instruction *UserInst = cast<Instruction>(I->use_back());
5376 BasicBlock *UserParent;
5377
5378 // Get the block the use occurs in.
5379 if (PHINode *PN = dyn_cast<PHINode>(UserInst))
5380 UserParent = PN->getIncomingBlock(I->use_begin().getUse());
5381 else
5382 UserParent = UserInst->getParent();
5383
Chris Lattnerea1c4542004-12-08 23:43:58 +00005384 if (UserParent != BB) {
5385 bool UserIsSuccessor = false;
5386 // See if the user is one of our successors.
5387 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
5388 if (*SI == UserParent) {
5389 UserIsSuccessor = true;
5390 break;
5391 }
5392
5393 // If the user is one of our immediate successors, and if that successor
5394 // only has us as a predecessors (we'd have to split the critical edge
5395 // otherwise), we can keep going.
Chris Lattner8db2cd12009-10-14 15:21:58 +00005396 if (UserIsSuccessor && UserParent->getSinglePredecessor())
Chris Lattnerea1c4542004-12-08 23:43:58 +00005397 // Okay, the CFG is simple enough, try to sink this instruction.
Chris Lattnerb0b822c2009-08-31 06:57:37 +00005398 MadeIRChange |= TryToSinkInstruction(I, UserParent);
Chris Lattnerea1c4542004-12-08 23:43:58 +00005399 }
5400 }
5401
Chris Lattner74381062009-08-30 07:44:24 +00005402 // Now that we have an instruction, try combining it to simplify it.
5403 Builder->SetInsertPoint(I->getParent(), I);
5404
Reid Spencera9b81012007-03-26 17:44:01 +00005405#ifndef NDEBUG
5406 std::string OrigI;
5407#endif
Chris Lattnerbdff5482009-08-23 04:37:46 +00005408 DEBUG(raw_string_ostream SS(OrigI); I->print(SS); OrigI = SS.str(););
Jeffrey Yasskin43069632009-10-08 00:12:24 +00005409 DEBUG(errs() << "IC: Visiting: " << OrigI << '\n');
5410
Chris Lattner90ac28c2002-08-02 19:29:35 +00005411 if (Instruction *Result = visit(*I)) {
Chris Lattner3dec1f22002-05-10 15:38:35 +00005412 ++NumCombined;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00005413 // Should we replace the old instruction with a new one?
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +00005414 if (Result != I) {
Chris Lattnerbdff5482009-08-23 04:37:46 +00005415 DEBUG(errs() << "IC: Old = " << *I << '\n'
5416 << " New = " << *Result << '\n');
Chris Lattner0cea42a2004-03-13 23:54:27 +00005417
Chris Lattnerf523d062004-06-09 05:08:07 +00005418 // Everything uses the new instruction now.
5419 I->replaceAllUsesWith(Result);
5420
5421 // Push the new instruction and any users onto the worklist.
Chris Lattner7a1e9242009-08-30 06:13:40 +00005422 Worklist.Add(Result);
Chris Lattnere5ecdb52009-08-30 06:22:51 +00005423 Worklist.AddUsersToWorkList(*Result);
Chris Lattner4bb7c022003-10-06 17:11:01 +00005424
Chris Lattner6934a042007-02-11 01:23:03 +00005425 // Move the name to the new instruction first.
5426 Result->takeName(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +00005427
5428 // Insert the new instruction into the basic block...
5429 BasicBlock *InstParent = I->getParent();
Chris Lattnerbac32862004-11-14 19:13:23 +00005430 BasicBlock::iterator InsertPos = I;
5431
5432 if (!isa<PHINode>(Result)) // If combining a PHI, don't insert
5433 while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
5434 ++InsertPos;
5435
5436 InstParent->getInstList().insert(InsertPos, Result);
Chris Lattner4bb7c022003-10-06 17:11:01 +00005437
Chris Lattner7a1e9242009-08-30 06:13:40 +00005438 EraseInstFromFunction(*I);
Chris Lattner7e708292002-06-25 16:13:24 +00005439 } else {
Evan Chengc7baf682007-03-27 16:44:48 +00005440#ifndef NDEBUG
Chris Lattnerbdff5482009-08-23 04:37:46 +00005441 DEBUG(errs() << "IC: Mod = " << OrigI << '\n'
5442 << " New = " << *I << '\n');
Evan Chengc7baf682007-03-27 16:44:48 +00005443#endif
Chris Lattner0cea42a2004-03-13 23:54:27 +00005444
Chris Lattner90ac28c2002-08-02 19:29:35 +00005445 // If the instruction was modified, it's possible that it is now dead.
5446 // if so, remove it.
Chris Lattner00d51312004-05-01 23:27:23 +00005447 if (isInstructionTriviallyDead(I)) {
Chris Lattner7a1e9242009-08-30 06:13:40 +00005448 EraseInstFromFunction(*I);
Chris Lattnerf523d062004-06-09 05:08:07 +00005449 } else {
Chris Lattner7a1e9242009-08-30 06:13:40 +00005450 Worklist.Add(I);
Chris Lattnere5ecdb52009-08-30 06:22:51 +00005451 Worklist.AddUsersToWorkList(*I);
Chris Lattner90ac28c2002-08-02 19:29:35 +00005452 }
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +00005453 }
Chris Lattnerb0b822c2009-08-31 06:57:37 +00005454 MadeIRChange = true;
Chris Lattner8a2a3112001-12-14 16:52:21 +00005455 }
5456 }
5457
Chris Lattner873ff012009-08-30 05:55:36 +00005458 Worklist.Zap();
Chris Lattnerb0b822c2009-08-31 06:57:37 +00005459 return MadeIRChange;
Chris Lattnerbd0ef772002-02-26 21:46:54 +00005460}
5461
Chris Lattnerec9c3582007-03-03 02:04:50 +00005462
5463bool InstCombiner::runOnFunction(Function &F) {
Chris Lattnerf964f322007-03-04 04:27:24 +00005464 MustPreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
Chris Lattnere2cc1ad2009-10-15 04:13:44 +00005465 TD = getAnalysisIfAvailable<TargetData>();
5466
Chris Lattner74381062009-08-30 07:44:24 +00005467
5468 /// Builder - This is an IRBuilder that automatically inserts new
5469 /// instructions into the worklist when they are created.
Chris Lattnere2cc1ad2009-10-15 04:13:44 +00005470 IRBuilder<true, TargetFolder, InstCombineIRInserter>
Chris Lattnerf55eeb92009-11-06 05:59:53 +00005471 TheBuilder(F.getContext(), TargetFolder(TD),
Chris Lattner74381062009-08-30 07:44:24 +00005472 InstCombineIRInserter(Worklist));
5473 Builder = &TheBuilder;
5474
Chris Lattnerec9c3582007-03-03 02:04:50 +00005475 bool EverMadeChange = false;
5476
5477 // Iterate while there is work to do.
5478 unsigned Iteration = 0;
Bill Wendlinga6c31122008-05-14 22:45:20 +00005479 while (DoOneIteration(F, Iteration++))
Chris Lattnerec9c3582007-03-03 02:04:50 +00005480 EverMadeChange = true;
Chris Lattner74381062009-08-30 07:44:24 +00005481
5482 Builder = 0;
Chris Lattnerec9c3582007-03-03 02:04:50 +00005483 return EverMadeChange;
5484}
5485
Brian Gaeke96d4bf72004-07-27 17:43:21 +00005486FunctionPass *llvm::createInstructionCombiningPass() {
Chris Lattnerdd841ae2002-04-18 17:39:14 +00005487 return new InstCombiner();
Chris Lattnerbd0ef772002-02-26 21:46:54 +00005488}