blob: 1b08b0e05571986a4456c8e6c0051a7908e36533 [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 Lattner4cb170c2004-02-23 06:38:22 +000080// getPromotedType - Return the specified type promoted as it would be to pass
Chris Lattner248a84b2010-01-05 07:04:23 +000081// though a va_arg area.
Chris Lattner4cb170c2004-02-23 06:38:22 +000082static const Type *getPromotedType(const Type *Ty) {
Reid Spencera54b7cb2007-01-12 07:05:14 +000083 if (const IntegerType* ITy = dyn_cast<IntegerType>(Ty)) {
84 if (ITy->getBitWidth() < 32)
Owen Anderson1d0be152009-08-13 21:58:54 +000085 return Type::getInt32Ty(Ty->getContext());
Chris Lattner2b7e0ad2007-05-23 01:17:04 +000086 }
Reid Spencera54b7cb2007-01-12 07:05:14 +000087 return Ty;
Chris Lattner4cb170c2004-02-23 06:38:22 +000088}
89
Chris Lattnerc22d4d12009-11-10 07:23:37 +000090/// ShouldChangeType - Return true if it is desirable to convert a computation
91/// from 'From' to 'To'. We don't want to convert from a legal to an illegal
92/// type for example, or from a smaller to a larger illegal type.
Chris Lattner80f43d32010-01-04 07:53:58 +000093bool InstCombiner::ShouldChangeType(const Type *From, const Type *To) const {
Chris Lattnerc22d4d12009-11-10 07:23:37 +000094 assert(isa<IntegerType>(From) && isa<IntegerType>(To));
95
96 // If we don't have TD, we don't know if the source/dest are legal.
97 if (!TD) return false;
98
99 unsigned FromWidth = From->getPrimitiveSizeInBits();
100 unsigned ToWidth = To->getPrimitiveSizeInBits();
101 bool FromLegal = TD->isLegalInteger(FromWidth);
102 bool ToLegal = TD->isLegalInteger(ToWidth);
103
104 // If this is a legal integer from type, and the result would be an illegal
105 // type, don't do the transformation.
106 if (FromLegal && !ToLegal)
107 return false;
108
109 // Otherwise, if both are illegal, do not increase the size of the result. We
110 // do allow things like i160 -> i64, but not i64 -> i160.
111 if (!FromLegal && !ToLegal && ToWidth > FromWidth)
112 return false;
113
114 return true;
115}
116
Matthijs Kooijman7e6d9b92008-10-13 15:17:01 +0000117/// getBitCastOperand - If the specified operand is a CastInst, a constant
118/// expression bitcast, or a GetElementPtrInst with all zero indices, return the
119/// operand value, otherwise return null.
Reid Spencer3da59db2006-11-27 01:05:10 +0000120static Value *getBitCastOperand(Value *V) {
Dan Gohman016de812009-07-17 23:55:56 +0000121 if (Operator *O = dyn_cast<Operator>(V)) {
122 if (O->getOpcode() == Instruction::BitCast)
123 return O->getOperand(0);
124 if (GEPOperator *GEP = dyn_cast<GEPOperator>(V))
125 if (GEP->hasAllZeroIndices())
126 return GEP->getPointerOperand();
Matthijs Kooijman7e6d9b92008-10-13 15:17:01 +0000127 }
Chris Lattnereed48272005-09-13 00:40:14 +0000128 return 0;
129}
130
Dan Gohmance9fe9f2009-07-21 23:21:54 +0000131
Chris Lattner33a61132006-05-06 09:00:16 +0000132
Chris Lattner4f98c562003-03-10 21:43:22 +0000133// SimplifyCommutative - This performs a few simplifications for commutative
134// operators:
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000135//
Chris Lattner4f98c562003-03-10 21:43:22 +0000136// 1. Order operands such that they are listed from right (least complex) to
137// left (most complex). This puts constants before unary operators before
138// binary operators.
139//
Chris Lattnerc8802d22003-03-11 00:12:48 +0000140// 2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
141// 3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattner4f98c562003-03-10 21:43:22 +0000142//
Chris Lattnerc8802d22003-03-11 00:12:48 +0000143bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +0000144 bool Changed = false;
Dan Gohman14ef4f02009-08-29 23:39:38 +0000145 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
Chris Lattner4f98c562003-03-10 21:43:22 +0000146 Changed = !I.swapOperands();
Misha Brukmanfd939082005-04-21 23:48:37 +0000147
Chris Lattner4f98c562003-03-10 21:43:22 +0000148 if (!I.isAssociative()) return Changed;
Chris Lattner248a84b2010-01-05 07:04:23 +0000149
Chris Lattner4f98c562003-03-10 21:43:22 +0000150 Instruction::BinaryOps Opcode = I.getOpcode();
Chris Lattnerc8802d22003-03-11 00:12:48 +0000151 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
152 if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
153 if (isa<Constant>(I.getOperand(1))) {
Owen Andersonbaf3c402009-07-29 18:55:55 +0000154 Constant *Folded = ConstantExpr::get(I.getOpcode(),
Chris Lattner2a9c8472003-05-27 16:40:51 +0000155 cast<Constant>(I.getOperand(1)),
156 cast<Constant>(Op->getOperand(1)));
Chris Lattnerc8802d22003-03-11 00:12:48 +0000157 I.setOperand(0, Op->getOperand(0));
158 I.setOperand(1, Folded);
159 return true;
Chris Lattner248a84b2010-01-05 07:04:23 +0000160 }
161
162 if (BinaryOperator *Op1 = dyn_cast<BinaryOperator>(I.getOperand(1)))
Chris Lattnerc8802d22003-03-11 00:12:48 +0000163 if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
Chris Lattner248a84b2010-01-05 07:04:23 +0000164 Op->hasOneUse() && Op1->hasOneUse()) {
Chris Lattnerc8802d22003-03-11 00:12:48 +0000165 Constant *C1 = cast<Constant>(Op->getOperand(1));
166 Constant *C2 = cast<Constant>(Op1->getOperand(1));
167
168 // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Owen Andersonbaf3c402009-07-29 18:55:55 +0000169 Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000170 Instruction *New = BinaryOperator::Create(Opcode, Op->getOperand(0),
Chris Lattnerc8802d22003-03-11 00:12:48 +0000171 Op1->getOperand(0),
172 Op1->getName(), &I);
Chris Lattner7a1e9242009-08-30 06:13:40 +0000173 Worklist.Add(New);
Chris Lattnerc8802d22003-03-11 00:12:48 +0000174 I.setOperand(0, New);
175 I.setOperand(1, Folded);
176 return true;
Misha Brukmanfd939082005-04-21 23:48:37 +0000177 }
Chris Lattner4f98c562003-03-10 21:43:22 +0000178 }
Chris Lattner4f98c562003-03-10 21:43:22 +0000179 return Changed;
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000180}
Chris Lattner8a2a3112001-12-14 16:52:21 +0000181
Chris Lattner8d969642003-03-10 23:06:50 +0000182// dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
183// if the LHS is a constant zero (which is the 'negate' form).
Chris Lattnerb35dde12002-05-06 16:49:18 +0000184//
Chris Lattner02446fc2010-01-04 07:37:31 +0000185Value *InstCombiner::dyn_castNegVal(Value *V) const {
Owen Andersonfa82b6e2009-07-13 22:18:28 +0000186 if (BinaryOperator::isNeg(V))
Chris Lattnera1df33c2005-04-24 07:30:14 +0000187 return BinaryOperator::getNegArgument(V);
Chris Lattner8d969642003-03-10 23:06:50 +0000188
Chris Lattner0ce85802004-12-14 20:08:06 +0000189 // Constants can be considered to be negated values if they can be folded.
190 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
Owen Andersonbaf3c402009-07-29 18:55:55 +0000191 return ConstantExpr::getNeg(C);
Nick Lewycky18b3da62008-05-23 04:54:45 +0000192
193 if (ConstantVector *C = dyn_cast<ConstantVector>(V))
194 if (C->getType()->getElementType()->isInteger())
Owen Andersonbaf3c402009-07-29 18:55:55 +0000195 return ConstantExpr::getNeg(C);
Nick Lewycky18b3da62008-05-23 04:54:45 +0000196
Chris Lattner8d969642003-03-10 23:06:50 +0000197 return 0;
Chris Lattnerb35dde12002-05-06 16:49:18 +0000198}
199
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000200// dyn_castFNegVal - Given a 'fsub' instruction, return the RHS of the
201// instruction if the LHS is a constant negative zero (which is the 'negate'
202// form).
203//
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000204Value *InstCombiner::dyn_castFNegVal(Value *V) const {
Owen Andersonfa82b6e2009-07-13 22:18:28 +0000205 if (BinaryOperator::isFNeg(V))
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000206 return BinaryOperator::getFNegArgument(V);
207
208 // Constants can be considered to be negated values if they can be folded.
209 if (ConstantFP *C = dyn_cast<ConstantFP>(V))
Owen Andersonbaf3c402009-07-29 18:55:55 +0000210 return ConstantExpr::getFNeg(C);
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000211
212 if (ConstantVector *C = dyn_cast<ConstantVector>(V))
213 if (C->getType()->getElementType()->isFloatingPoint())
Owen Andersonbaf3c402009-07-29 18:55:55 +0000214 return ConstantExpr::getFNeg(C);
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000215
216 return 0;
217}
218
Chris Lattner48b59ec2009-10-26 15:40:07 +0000219/// isFreeToInvert - Return true if the specified value is free to invert (apply
220/// ~ to). This happens in cases where the ~ can be eliminated.
221static inline bool isFreeToInvert(Value *V) {
222 // ~(~(X)) -> X.
Evan Cheng85def162009-10-26 03:51:32 +0000223 if (BinaryOperator::isNot(V))
Chris Lattner48b59ec2009-10-26 15:40:07 +0000224 return true;
225
226 // Constants can be considered to be not'ed values.
227 if (isa<ConstantInt>(V))
228 return true;
229
230 // Compares can be inverted if they have a single use.
231 if (CmpInst *CI = dyn_cast<CmpInst>(V))
232 return CI->hasOneUse();
233
234 return false;
235}
236
237static inline Value *dyn_castNotVal(Value *V) {
238 // If this is not(not(x)) don't return that this is a not: we want the two
239 // not's to be folded first.
240 if (BinaryOperator::isNot(V)) {
241 Value *Operand = BinaryOperator::getNotArgument(V);
242 if (!isFreeToInvert(Operand))
243 return Operand;
244 }
Chris Lattner8d969642003-03-10 23:06:50 +0000245
246 // Constants can be considered to be not'ed values...
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000247 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
Dan Gohman186a6362009-08-12 16:04:34 +0000248 return ConstantInt::get(C->getType(), ~C->getValue());
Chris Lattner8d969642003-03-10 23:06:50 +0000249 return 0;
250}
251
Chris Lattner48b59ec2009-10-26 15:40:07 +0000252
253
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000254/// AddOne - Add one to a ConstantInt.
Dan Gohman186a6362009-08-12 16:04:34 +0000255static Constant *AddOne(Constant *C) {
Chris Lattner02446fc2010-01-04 07:37:31 +0000256 return ConstantExpr::getAdd(C, ConstantInt::get(C->getType(), 1));
Chris Lattner955f3312004-09-28 21:48:02 +0000257}
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000258/// SubOne - Subtract one from a ConstantInt.
Dan Gohman186a6362009-08-12 16:04:34 +0000259static Constant *SubOne(ConstantInt *C) {
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000260 return ConstantInt::get(C->getContext(), C->getValue()-1);
Chris Lattner955f3312004-09-28 21:48:02 +0000261}
Reid Spencere7816b52007-03-08 01:52:58 +0000262
Dan Gohman45b4e482008-05-19 22:14:15 +0000263
Chris Lattner6e7ba452005-01-01 16:22:27 +0000264static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
Chris Lattner2eefe512004-04-09 19:05:30 +0000265 InstCombiner *IC) {
Chris Lattner08142f22009-08-30 19:47:22 +0000266 if (CastInst *CI = dyn_cast<CastInst>(&I))
Chris Lattner2345d1d2009-08-30 20:01:10 +0000267 return IC->Builder->CreateCast(CI->getOpcode(), SO, I.getType());
Chris Lattner6e7ba452005-01-01 16:22:27 +0000268
Chris Lattner2eefe512004-04-09 19:05:30 +0000269 // Figure out if the constant is the left or the right argument.
Chris Lattner6e7ba452005-01-01 16:22:27 +0000270 bool ConstIsRHS = isa<Constant>(I.getOperand(1));
271 Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
Chris Lattner564a7272003-08-13 19:01:45 +0000272
Chris Lattner2eefe512004-04-09 19:05:30 +0000273 if (Constant *SOC = dyn_cast<Constant>(SO)) {
274 if (ConstIsRHS)
Owen Andersonbaf3c402009-07-29 18:55:55 +0000275 return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
276 return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
Chris Lattner2eefe512004-04-09 19:05:30 +0000277 }
278
279 Value *Op0 = SO, *Op1 = ConstOperand;
280 if (!ConstIsRHS)
281 std::swap(Op0, Op1);
Chris Lattner74381062009-08-30 07:44:24 +0000282
Chris Lattner6e7ba452005-01-01 16:22:27 +0000283 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
Chris Lattner74381062009-08-30 07:44:24 +0000284 return IC->Builder->CreateBinOp(BO->getOpcode(), Op0, Op1,
285 SO->getName()+".op");
286 if (ICmpInst *CI = dyn_cast<ICmpInst>(&I))
287 return IC->Builder->CreateICmp(CI->getPredicate(), Op0, Op1,
288 SO->getName()+".cmp");
289 if (FCmpInst *CI = dyn_cast<FCmpInst>(&I))
290 return IC->Builder->CreateICmp(CI->getPredicate(), Op0, Op1,
291 SO->getName()+".cmp");
292 llvm_unreachable("Unknown binary instruction type!");
Chris Lattner6e7ba452005-01-01 16:22:27 +0000293}
294
295// FoldOpIntoSelect - Given an instruction with a select as one operand and a
296// constant as the other operand, try to fold the binary operator into the
297// select arguments. This also works for Cast instructions, which obviously do
298// not have a second operand.
Chris Lattner80f43d32010-01-04 07:53:58 +0000299Instruction *InstCombiner::FoldOpIntoSelect(Instruction &Op, SelectInst *SI) {
Chris Lattner6e7ba452005-01-01 16:22:27 +0000300 // Don't modify shared select instructions
301 if (!SI->hasOneUse()) return 0;
302 Value *TV = SI->getOperand(1);
303 Value *FV = SI->getOperand(2);
304
305 if (isa<Constant>(TV) || isa<Constant>(FV)) {
Chris Lattner956db272005-04-21 05:43:13 +0000306 // Bool selects with constant operands can be folded to logical ops.
Chris Lattner4de84762010-01-04 07:02:48 +0000307 if (SI->getType() == Type::getInt1Ty(SI->getContext())) return 0;
Chris Lattner956db272005-04-21 05:43:13 +0000308
Chris Lattner80f43d32010-01-04 07:53:58 +0000309 Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, this);
310 Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, this);
Chris Lattner6e7ba452005-01-01 16:22:27 +0000311
Gabor Greif051a9502008-04-06 20:25:17 +0000312 return SelectInst::Create(SI->getCondition(), SelectTrueVal,
313 SelectFalseVal);
Chris Lattner6e7ba452005-01-01 16:22:27 +0000314 }
315 return 0;
Chris Lattner2eefe512004-04-09 19:05:30 +0000316}
317
Chris Lattner4e998b22004-09-29 05:07:12 +0000318
Chris Lattner5d1704d2009-09-27 19:57:57 +0000319/// FoldOpIntoPhi - Given a binary operator, cast instruction, or select which
320/// has a PHI node as operand #0, see if we can fold the instruction into the
321/// PHI (which is only possible if all operands to the PHI are constants).
Chris Lattner213cd612009-09-27 20:46:36 +0000322///
323/// If AllowAggressive is true, FoldOpIntoPhi will allow certain transforms
324/// that would normally be unprofitable because they strongly encourage jump
325/// threading.
326Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I,
327 bool AllowAggressive) {
328 AllowAggressive = false;
Chris Lattner4e998b22004-09-29 05:07:12 +0000329 PHINode *PN = cast<PHINode>(I.getOperand(0));
Chris Lattnerbac32862004-11-14 19:13:23 +0000330 unsigned NumPHIValues = PN->getNumIncomingValues();
Chris Lattner213cd612009-09-27 20:46:36 +0000331 if (NumPHIValues == 0 ||
332 // We normally only transform phis with a single use, unless we're trying
333 // hard to make jump threading happen.
334 (!PN->hasOneUse() && !AllowAggressive))
335 return 0;
336
337
Chris Lattner5d1704d2009-09-27 19:57:57 +0000338 // Check to see if all of the operands of the PHI are simple constants
339 // (constantint/constantfp/undef). If there is one non-constant value,
Chris Lattnerc6df8f42009-09-27 20:18:49 +0000340 // remember the BB it is in. If there is more than one or if *it* is a PHI,
341 // bail out. We don't do arbitrary constant expressions here because moving
342 // their computation can be expensive without a cost model.
Chris Lattner2a86f3b2006-09-09 22:02:56 +0000343 BasicBlock *NonConstBB = 0;
344 for (unsigned i = 0; i != NumPHIValues; ++i)
Chris Lattner5d1704d2009-09-27 19:57:57 +0000345 if (!isa<Constant>(PN->getIncomingValue(i)) ||
346 isa<ConstantExpr>(PN->getIncomingValue(i))) {
Chris Lattner2a86f3b2006-09-09 22:02:56 +0000347 if (NonConstBB) return 0; // More than one non-const value.
Chris Lattnerb3036682007-02-24 01:03:45 +0000348 if (isa<PHINode>(PN->getIncomingValue(i))) return 0; // Itself a phi.
Chris Lattner2a86f3b2006-09-09 22:02:56 +0000349 NonConstBB = PN->getIncomingBlock(i);
350
351 // If the incoming non-constant value is in I's block, we have an infinite
352 // loop.
353 if (NonConstBB == I.getParent())
354 return 0;
355 }
356
357 // If there is exactly one non-constant value, we can insert a copy of the
358 // operation in that block. However, if this is a critical edge, we would be
359 // inserting the computation one some other paths (e.g. inside a loop). Only
360 // do this if the pred block is unconditionally branching into the phi block.
Chris Lattner213cd612009-09-27 20:46:36 +0000361 if (NonConstBB != 0 && !AllowAggressive) {
Chris Lattner2a86f3b2006-09-09 22:02:56 +0000362 BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
363 if (!BI || !BI->isUnconditional()) return 0;
364 }
Chris Lattner4e998b22004-09-29 05:07:12 +0000365
366 // Okay, we can do the transformation: create the new PHI node.
Gabor Greif051a9502008-04-06 20:25:17 +0000367 PHINode *NewPN = PHINode::Create(I.getType(), "");
Chris Lattner55517062005-01-29 00:39:08 +0000368 NewPN->reserveOperandSpace(PN->getNumOperands()/2);
Chris Lattner857eb572009-10-21 23:41:58 +0000369 InsertNewInstBefore(NewPN, *PN);
370 NewPN->takeName(PN);
Chris Lattner4e998b22004-09-29 05:07:12 +0000371
372 // Next, add all of the operands to the PHI.
Chris Lattner5d1704d2009-09-27 19:57:57 +0000373 if (SelectInst *SI = dyn_cast<SelectInst>(&I)) {
374 // We only currently try to fold the condition of a select when it is a phi,
375 // not the true/false values.
Chris Lattnerc6df8f42009-09-27 20:18:49 +0000376 Value *TrueV = SI->getTrueValue();
377 Value *FalseV = SI->getFalseValue();
Chris Lattner3ddfb212009-09-28 06:49:44 +0000378 BasicBlock *PhiTransBB = PN->getParent();
Chris Lattner5d1704d2009-09-27 19:57:57 +0000379 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattnerc6df8f42009-09-27 20:18:49 +0000380 BasicBlock *ThisBB = PN->getIncomingBlock(i);
Chris Lattner3ddfb212009-09-28 06:49:44 +0000381 Value *TrueVInPred = TrueV->DoPHITranslation(PhiTransBB, ThisBB);
382 Value *FalseVInPred = FalseV->DoPHITranslation(PhiTransBB, ThisBB);
Chris Lattner5d1704d2009-09-27 19:57:57 +0000383 Value *InV = 0;
384 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Chris Lattnerc6df8f42009-09-27 20:18:49 +0000385 InV = InC->isNullValue() ? FalseVInPred : TrueVInPred;
Chris Lattner5d1704d2009-09-27 19:57:57 +0000386 } else {
387 assert(PN->getIncomingBlock(i) == NonConstBB);
Chris Lattnerc6df8f42009-09-27 20:18:49 +0000388 InV = SelectInst::Create(PN->getIncomingValue(i), TrueVInPred,
389 FalseVInPred,
Chris Lattner5d1704d2009-09-27 19:57:57 +0000390 "phitmp", NonConstBB->getTerminator());
Chris Lattner857eb572009-10-21 23:41:58 +0000391 Worklist.Add(cast<Instruction>(InV));
Chris Lattner5d1704d2009-09-27 19:57:57 +0000392 }
Chris Lattnerc6df8f42009-09-27 20:18:49 +0000393 NewPN->addIncoming(InV, ThisBB);
Chris Lattner5d1704d2009-09-27 19:57:57 +0000394 }
395 } else if (I.getNumOperands() == 2) {
Chris Lattner4e998b22004-09-29 05:07:12 +0000396 Constant *C = cast<Constant>(I.getOperand(1));
Chris Lattnerbac32862004-11-14 19:13:23 +0000397 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattnera9ff5eb2007-08-05 08:47:58 +0000398 Value *InV = 0;
Chris Lattner2a86f3b2006-09-09 22:02:56 +0000399 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Reid Spencere4d87aa2006-12-23 06:05:41 +0000400 if (CmpInst *CI = dyn_cast<CmpInst>(&I))
Owen Andersonbaf3c402009-07-29 18:55:55 +0000401 InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C);
Reid Spencere4d87aa2006-12-23 06:05:41 +0000402 else
Owen Andersonbaf3c402009-07-29 18:55:55 +0000403 InV = ConstantExpr::get(I.getOpcode(), InC, C);
Chris Lattner2a86f3b2006-09-09 22:02:56 +0000404 } else {
405 assert(PN->getIncomingBlock(i) == NonConstBB);
406 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000407 InV = BinaryOperator::Create(BO->getOpcode(),
Chris Lattner2a86f3b2006-09-09 22:02:56 +0000408 PN->getIncomingValue(i), C, "phitmp",
409 NonConstBB->getTerminator());
Reid Spencere4d87aa2006-12-23 06:05:41 +0000410 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
Dan Gohman1c8a23c2009-08-25 23:17:54 +0000411 InV = CmpInst::Create(CI->getOpcode(),
Reid Spencere4d87aa2006-12-23 06:05:41 +0000412 CI->getPredicate(),
413 PN->getIncomingValue(i), C, "phitmp",
414 NonConstBB->getTerminator());
Chris Lattner2a86f3b2006-09-09 22:02:56 +0000415 else
Torok Edwinc23197a2009-07-14 16:55:14 +0000416 llvm_unreachable("Unknown binop!");
Chris Lattner857eb572009-10-21 23:41:58 +0000417
418 Worklist.Add(cast<Instruction>(InV));
Chris Lattner2a86f3b2006-09-09 22:02:56 +0000419 }
420 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner4e998b22004-09-29 05:07:12 +0000421 }
Reid Spencer3da59db2006-11-27 01:05:10 +0000422 } else {
423 CastInst *CI = cast<CastInst>(&I);
424 const Type *RetTy = CI->getType();
Chris Lattnerbac32862004-11-14 19:13:23 +0000425 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattner2a86f3b2006-09-09 22:02:56 +0000426 Value *InV;
427 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Owen Andersonbaf3c402009-07-29 18:55:55 +0000428 InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
Chris Lattner2a86f3b2006-09-09 22:02:56 +0000429 } else {
430 assert(PN->getIncomingBlock(i) == NonConstBB);
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000431 InV = CastInst::Create(CI->getOpcode(), PN->getIncomingValue(i),
Reid Spencer3da59db2006-11-27 01:05:10 +0000432 I.getType(), "phitmp",
433 NonConstBB->getTerminator());
Chris Lattner857eb572009-10-21 23:41:58 +0000434 Worklist.Add(cast<Instruction>(InV));
Chris Lattner2a86f3b2006-09-09 22:02:56 +0000435 }
436 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner4e998b22004-09-29 05:07:12 +0000437 }
438 }
439 return ReplaceInstUsesWith(I, NewPN);
440}
441
Chris Lattner2454a2e2008-01-29 06:52:45 +0000442
Reid Spencere4d87aa2006-12-23 06:05:41 +0000443/// getICmpCode - Encode a icmp predicate into a three bit mask. These bits
Chris Lattneraa9c1f12003-08-13 20:16:26 +0000444/// are carefully arranged to allow folding of expressions such as:
445///
446/// (A < B) | (A > B) --> (A != B)
447///
Reid Spencere4d87aa2006-12-23 06:05:41 +0000448/// Note that this is only valid if the first and second predicates have the
449/// same sign. Is illegal to do: (A u< B) | (A s> B)
Chris Lattneraa9c1f12003-08-13 20:16:26 +0000450///
Reid Spencere4d87aa2006-12-23 06:05:41 +0000451/// Three bits are used to represent the condition, as follows:
452/// 0 A > B
453/// 1 A == B
454/// 2 A < B
455///
456/// <=> Value Definition
457/// 000 0 Always false
458/// 001 1 A > B
459/// 010 2 A == B
460/// 011 3 A >= B
461/// 100 4 A < B
462/// 101 5 A != B
463/// 110 6 A <= B
464/// 111 7 Always true
465///
466static unsigned getICmpCode(const ICmpInst *ICI) {
467 switch (ICI->getPredicate()) {
Chris Lattneraa9c1f12003-08-13 20:16:26 +0000468 // False -> 0
Reid Spencere4d87aa2006-12-23 06:05:41 +0000469 case ICmpInst::ICMP_UGT: return 1; // 001
470 case ICmpInst::ICMP_SGT: return 1; // 001
471 case ICmpInst::ICMP_EQ: return 2; // 010
472 case ICmpInst::ICMP_UGE: return 3; // 011
473 case ICmpInst::ICMP_SGE: return 3; // 011
474 case ICmpInst::ICMP_ULT: return 4; // 100
475 case ICmpInst::ICMP_SLT: return 4; // 100
476 case ICmpInst::ICMP_NE: return 5; // 101
477 case ICmpInst::ICMP_ULE: return 6; // 110
478 case ICmpInst::ICMP_SLE: return 6; // 110
Chris Lattneraa9c1f12003-08-13 20:16:26 +0000479 // True -> 7
480 default:
Torok Edwinc23197a2009-07-14 16:55:14 +0000481 llvm_unreachable("Invalid ICmp predicate!");
Chris Lattneraa9c1f12003-08-13 20:16:26 +0000482 return 0;
483 }
484}
485
Evan Cheng8db90722008-10-14 17:15:11 +0000486/// getFCmpCode - Similar to getICmpCode but for FCmpInst. This encodes a fcmp
487/// predicate into a three bit mask. It also returns whether it is an ordered
488/// predicate by reference.
489static unsigned getFCmpCode(FCmpInst::Predicate CC, bool &isOrdered) {
490 isOrdered = false;
491 switch (CC) {
492 case FCmpInst::FCMP_ORD: isOrdered = true; return 0; // 000
493 case FCmpInst::FCMP_UNO: return 0; // 000
Evan Cheng4990b252008-10-14 18:13:38 +0000494 case FCmpInst::FCMP_OGT: isOrdered = true; return 1; // 001
495 case FCmpInst::FCMP_UGT: return 1; // 001
496 case FCmpInst::FCMP_OEQ: isOrdered = true; return 2; // 010
497 case FCmpInst::FCMP_UEQ: return 2; // 010
Evan Cheng8db90722008-10-14 17:15:11 +0000498 case FCmpInst::FCMP_OGE: isOrdered = true; return 3; // 011
499 case FCmpInst::FCMP_UGE: return 3; // 011
500 case FCmpInst::FCMP_OLT: isOrdered = true; return 4; // 100
501 case FCmpInst::FCMP_ULT: return 4; // 100
Evan Cheng4990b252008-10-14 18:13:38 +0000502 case FCmpInst::FCMP_ONE: isOrdered = true; return 5; // 101
503 case FCmpInst::FCMP_UNE: return 5; // 101
Evan Cheng8db90722008-10-14 17:15:11 +0000504 case FCmpInst::FCMP_OLE: isOrdered = true; return 6; // 110
505 case FCmpInst::FCMP_ULE: return 6; // 110
Evan Cheng40300622008-10-14 18:44:08 +0000506 // True -> 7
Evan Cheng8db90722008-10-14 17:15:11 +0000507 default:
508 // Not expecting FCMP_FALSE and FCMP_TRUE;
Torok Edwinc23197a2009-07-14 16:55:14 +0000509 llvm_unreachable("Unexpected FCmp predicate!");
Evan Cheng8db90722008-10-14 17:15:11 +0000510 return 0;
511 }
512}
513
Reid Spencere4d87aa2006-12-23 06:05:41 +0000514/// getICmpValue - This is the complement of getICmpCode, which turns an
515/// opcode and two operands into either a constant true or false, or a brand
Dan Gohman5d066ff2007-09-17 17:31:57 +0000516/// new ICmp instruction. The sign is passed in to determine which kind
Evan Cheng8db90722008-10-14 17:15:11 +0000517/// of predicate to use in the new icmp instruction.
Chris Lattnera317e042010-01-05 06:59:49 +0000518static Value *getICmpValue(bool Sign, unsigned Code, Value *LHS, Value *RHS) {
519 switch (Code) {
520 default: assert(0 && "Illegal ICmp code!");
521 case 0:
522 return ConstantInt::getFalse(LHS->getContext());
523 case 1:
524 if (Sign)
Dan Gohman1c8a23c2009-08-25 23:17:54 +0000525 return new ICmpInst(ICmpInst::ICMP_SGT, LHS, RHS);
Chris Lattnera317e042010-01-05 06:59:49 +0000526 return new ICmpInst(ICmpInst::ICMP_UGT, LHS, RHS);
527 case 2:
528 return new ICmpInst(ICmpInst::ICMP_EQ, LHS, RHS);
529 case 3:
530 if (Sign)
Dan Gohman1c8a23c2009-08-25 23:17:54 +0000531 return new ICmpInst(ICmpInst::ICMP_SGE, LHS, RHS);
Chris Lattnera317e042010-01-05 06:59:49 +0000532 return new ICmpInst(ICmpInst::ICMP_UGE, LHS, RHS);
533 case 4:
534 if (Sign)
Dan Gohman1c8a23c2009-08-25 23:17:54 +0000535 return new ICmpInst(ICmpInst::ICMP_SLT, LHS, RHS);
Chris Lattnera317e042010-01-05 06:59:49 +0000536 return new ICmpInst(ICmpInst::ICMP_ULT, LHS, RHS);
537 case 5:
538 return new ICmpInst(ICmpInst::ICMP_NE, LHS, RHS);
539 case 6:
540 if (Sign)
Dan Gohman1c8a23c2009-08-25 23:17:54 +0000541 return new ICmpInst(ICmpInst::ICMP_SLE, LHS, RHS);
Chris Lattnera317e042010-01-05 06:59:49 +0000542 return new ICmpInst(ICmpInst::ICMP_ULE, LHS, RHS);
543 case 7:
544 return ConstantInt::getTrue(LHS->getContext());
Chris Lattneraa9c1f12003-08-13 20:16:26 +0000545 }
546}
547
Evan Cheng8db90722008-10-14 17:15:11 +0000548/// getFCmpValue - This is the complement of getFCmpCode, which turns an
549/// opcode and two operands into either a FCmp instruction. isordered is passed
550/// in to determine which kind of predicate to use in the new fcmp instruction.
551static Value *getFCmpValue(bool isordered, unsigned code,
Chris Lattner4de84762010-01-04 07:02:48 +0000552 Value *LHS, Value *RHS) {
Evan Cheng8db90722008-10-14 17:15:11 +0000553 switch (code) {
Torok Edwinc23197a2009-07-14 16:55:14 +0000554 default: llvm_unreachable("Illegal FCmp code!");
Evan Cheng8db90722008-10-14 17:15:11 +0000555 case 0:
556 if (isordered)
Dan Gohman1c8a23c2009-08-25 23:17:54 +0000557 return new FCmpInst(FCmpInst::FCMP_ORD, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +0000558 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +0000559 return new FCmpInst(FCmpInst::FCMP_UNO, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +0000560 case 1:
561 if (isordered)
Dan Gohman1c8a23c2009-08-25 23:17:54 +0000562 return new FCmpInst(FCmpInst::FCMP_OGT, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +0000563 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +0000564 return new FCmpInst(FCmpInst::FCMP_UGT, LHS, RHS);
Evan Cheng4990b252008-10-14 18:13:38 +0000565 case 2:
566 if (isordered)
Dan Gohman1c8a23c2009-08-25 23:17:54 +0000567 return new FCmpInst(FCmpInst::FCMP_OEQ, LHS, RHS);
Evan Cheng4990b252008-10-14 18:13:38 +0000568 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +0000569 return new FCmpInst(FCmpInst::FCMP_UEQ, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +0000570 case 3:
571 if (isordered)
Dan Gohman1c8a23c2009-08-25 23:17:54 +0000572 return new FCmpInst(FCmpInst::FCMP_OGE, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +0000573 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +0000574 return new FCmpInst(FCmpInst::FCMP_UGE, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +0000575 case 4:
576 if (isordered)
Dan Gohman1c8a23c2009-08-25 23:17:54 +0000577 return new FCmpInst(FCmpInst::FCMP_OLT, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +0000578 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +0000579 return new FCmpInst(FCmpInst::FCMP_ULT, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +0000580 case 5:
581 if (isordered)
Dan Gohman1c8a23c2009-08-25 23:17:54 +0000582 return new FCmpInst(FCmpInst::FCMP_ONE, LHS, RHS);
Evan Cheng4990b252008-10-14 18:13:38 +0000583 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +0000584 return new FCmpInst(FCmpInst::FCMP_UNE, LHS, RHS);
Evan Cheng4990b252008-10-14 18:13:38 +0000585 case 6:
586 if (isordered)
Dan Gohman1c8a23c2009-08-25 23:17:54 +0000587 return new FCmpInst(FCmpInst::FCMP_OLE, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +0000588 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +0000589 return new FCmpInst(FCmpInst::FCMP_ULE, LHS, RHS);
Chris Lattner4de84762010-01-04 07:02:48 +0000590 case 7: return ConstantInt::getTrue(LHS->getContext());
Evan Cheng8db90722008-10-14 17:15:11 +0000591 }
592}
593
Chris Lattnerb9553d62008-11-16 04:55:20 +0000594/// PredicatesFoldable - Return true if both predicates match sign or if at
595/// least one of them is an equality comparison (which is signless).
Reid Spencere4d87aa2006-12-23 06:05:41 +0000596static bool PredicatesFoldable(ICmpInst::Predicate p1, ICmpInst::Predicate p2) {
Nick Lewycky4a134af2009-10-25 05:20:17 +0000597 return (CmpInst::isSigned(p1) == CmpInst::isSigned(p2)) ||
598 (CmpInst::isSigned(p1) && ICmpInst::isEquality(p2)) ||
599 (CmpInst::isSigned(p2) && ICmpInst::isEquality(p1));
Reid Spencere4d87aa2006-12-23 06:05:41 +0000600}
601
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +0000602// OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
603// the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
Reid Spencer832254e2007-02-02 02:16:23 +0000604// guaranteed to be a binary operator.
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +0000605Instruction *InstCombiner::OptAndOp(Instruction *Op,
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000606 ConstantInt *OpRHS,
607 ConstantInt *AndRHS,
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +0000608 BinaryOperator &TheAnd) {
609 Value *X = Op->getOperand(0);
Chris Lattner76f7fe22004-01-12 19:47:05 +0000610 Constant *Together = 0;
Reid Spencer832254e2007-02-02 02:16:23 +0000611 if (!Op->isShift())
Owen Andersonbaf3c402009-07-29 18:55:55 +0000612 Together = ConstantExpr::getAnd(AndRHS, OpRHS);
Chris Lattner7c4049c2004-01-12 19:35:11 +0000613
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +0000614 switch (Op->getOpcode()) {
615 case Instruction::Xor:
Chris Lattner6e7ba452005-01-01 16:22:27 +0000616 if (Op->hasOneUse()) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +0000617 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
Chris Lattner74381062009-08-30 07:44:24 +0000618 Value *And = Builder->CreateAnd(X, AndRHS);
Chris Lattner6934a042007-02-11 01:23:03 +0000619 And->takeName(Op);
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000620 return BinaryOperator::CreateXor(And, Together);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +0000621 }
622 break;
623 case Instruction::Or:
Chris Lattner6e7ba452005-01-01 16:22:27 +0000624 if (Together == AndRHS) // (X | C) & C --> C
625 return ReplaceInstUsesWith(TheAnd, AndRHS);
Misha Brukmanfd939082005-04-21 23:48:37 +0000626
Chris Lattner6e7ba452005-01-01 16:22:27 +0000627 if (Op->hasOneUse() && Together != OpRHS) {
628 // (X | C1) & C2 --> (X | (C1&C2)) & C2
Chris Lattner74381062009-08-30 07:44:24 +0000629 Value *Or = Builder->CreateOr(X, Together);
Chris Lattner6934a042007-02-11 01:23:03 +0000630 Or->takeName(Op);
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000631 return BinaryOperator::CreateAnd(Or, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +0000632 }
633 break;
634 case Instruction::Add:
Chris Lattnerfd059242003-10-15 16:48:29 +0000635 if (Op->hasOneUse()) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +0000636 // Adding a one to a single bit bit-field should be turned into an XOR
637 // of the bit. First thing to check is to see if this AND is with a
638 // single bit constant.
Chris Lattnerc6334b92010-01-05 06:03:12 +0000639 const APInt &AndRHSV = cast<ConstantInt>(AndRHS)->getValue();
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +0000640
Chris Lattnerc6334b92010-01-05 06:03:12 +0000641 // If there is only one bit set.
642 if (AndRHSV.isPowerOf2()) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +0000643 // Ok, at this point, we know that we are masking the result of the
644 // ADD down to exactly one bit. If the constant we are adding has
645 // no bits set below this bit, then we can eliminate the ADD.
Zhou Sheng3a507fd2007-04-01 17:13:37 +0000646 const APInt& AddRHS = cast<ConstantInt>(OpRHS)->getValue();
Misha Brukmanfd939082005-04-21 23:48:37 +0000647
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +0000648 // Check to see if any bits below the one bit set in AndRHSV are set.
649 if ((AddRHS & (AndRHSV-1)) == 0) {
650 // If not, the only thing that can effect the output of the AND is
651 // the bit specified by AndRHSV. If that bit is set, the effect of
652 // the XOR is to toggle the bit. If it is clear, then the ADD has
653 // no effect.
654 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
655 TheAnd.setOperand(0, X);
656 return &TheAnd;
657 } else {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +0000658 // Pull the XOR out of the AND.
Chris Lattner74381062009-08-30 07:44:24 +0000659 Value *NewAnd = Builder->CreateAnd(X, AndRHS);
Chris Lattner6934a042007-02-11 01:23:03 +0000660 NewAnd->takeName(Op);
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000661 return BinaryOperator::CreateXor(NewAnd, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +0000662 }
663 }
664 }
665 }
666 break;
Chris Lattner62a355c2003-09-19 19:05:02 +0000667
668 case Instruction::Shl: {
669 // We know that the AND will not produce any of the bits shifted in, so if
670 // the anded constant includes them, clear them now!
671 //
Zhou Sheng290bec52007-03-29 08:15:12 +0000672 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +0000673 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +0000674 APInt ShlMask(APInt::getHighBitsSet(BitWidth, BitWidth-OpRHSVal));
Chris Lattner4de84762010-01-04 07:02:48 +0000675 ConstantInt *CI = ConstantInt::get(AndRHS->getContext(),
676 AndRHS->getValue() & ShlMask);
Misha Brukmanfd939082005-04-21 23:48:37 +0000677
Zhou Sheng290bec52007-03-29 08:15:12 +0000678 if (CI->getValue() == ShlMask) {
679 // Masking out bits that the shift already masks
Chris Lattner0c967662004-09-24 15:21:34 +0000680 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
681 } else if (CI != AndRHS) { // Reducing bits set in and.
Chris Lattner62a355c2003-09-19 19:05:02 +0000682 TheAnd.setOperand(1, CI);
683 return &TheAnd;
684 }
685 break;
Misha Brukmanfd939082005-04-21 23:48:37 +0000686 }
Chris Lattner4de84762010-01-04 07:02:48 +0000687 case Instruction::LShr: {
Chris Lattner62a355c2003-09-19 19:05:02 +0000688 // We know that the AND will not produce any of the bits shifted in, so if
689 // the anded constant includes them, clear them now! This only applies to
690 // unsigned shifts, because a signed shr may bring in set bits!
691 //
Zhou Sheng290bec52007-03-29 08:15:12 +0000692 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +0000693 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +0000694 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
Chris Lattner4de84762010-01-04 07:02:48 +0000695 ConstantInt *CI = ConstantInt::get(Op->getContext(),
696 AndRHS->getValue() & ShrMask);
Chris Lattner0c967662004-09-24 15:21:34 +0000697
Zhou Sheng290bec52007-03-29 08:15:12 +0000698 if (CI->getValue() == ShrMask) {
699 // Masking out bits that the shift already masks.
Reid Spencer3822ff52006-11-08 06:47:33 +0000700 return ReplaceInstUsesWith(TheAnd, Op);
701 } else if (CI != AndRHS) {
702 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
703 return &TheAnd;
704 }
705 break;
706 }
707 case Instruction::AShr:
708 // Signed shr.
709 // See if this is shifting in some sign extension, then masking it out
710 // with an and.
711 if (Op->hasOneUse()) {
Zhou Sheng290bec52007-03-29 08:15:12 +0000712 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +0000713 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +0000714 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
Chris Lattner4de84762010-01-04 07:02:48 +0000715 Constant *C = ConstantInt::get(Op->getContext(),
716 AndRHS->getValue() & ShrMask);
Reid Spencer7eb76382006-12-13 17:19:09 +0000717 if (C == AndRHS) { // Masking out bits shifted in.
Reid Spencer17212df2006-12-12 09:18:51 +0000718 // (Val ashr C1) & C2 -> (Val lshr C1) & C2
Reid Spencer3822ff52006-11-08 06:47:33 +0000719 // Make the argument unsigned.
720 Value *ShVal = Op->getOperand(0);
Chris Lattner74381062009-08-30 07:44:24 +0000721 ShVal = Builder->CreateLShr(ShVal, OpRHS, Op->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000722 return BinaryOperator::CreateAnd(ShVal, AndRHS, TheAnd.getName());
Chris Lattner0c967662004-09-24 15:21:34 +0000723 }
Chris Lattner62a355c2003-09-19 19:05:02 +0000724 }
725 break;
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +0000726 }
727 return 0;
728}
729
Chris Lattner8b170942002-08-09 23:47:40 +0000730
Chris Lattnera96879a2004-09-29 17:40:11 +0000731/// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
732/// true, otherwise (V < Lo || V >= Hi). In pratice, we emit the more efficient
Reid Spencere4d87aa2006-12-23 06:05:41 +0000733/// (V-Lo) <u Hi-Lo. This method expects that Lo <= Hi. isSigned indicates
734/// whether to treat the V, Lo and HI as signed or not. IB is the location to
Chris Lattnera96879a2004-09-29 17:40:11 +0000735/// insert new instructions.
736Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
Reid Spencere4d87aa2006-12-23 06:05:41 +0000737 bool isSigned, bool Inside,
738 Instruction &IB) {
Owen Andersonbaf3c402009-07-29 18:55:55 +0000739 assert(cast<ConstantInt>(ConstantExpr::getICmp((isSigned ?
Reid Spencer579dca12007-01-12 04:24:46 +0000740 ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
Chris Lattnera96879a2004-09-29 17:40:11 +0000741 "Lo is not <= Hi in range emission code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +0000742
Chris Lattnera96879a2004-09-29 17:40:11 +0000743 if (Inside) {
744 if (Lo == Hi) // Trivially false.
Dan Gohman1c8a23c2009-08-25 23:17:54 +0000745 return new ICmpInst(ICmpInst::ICMP_NE, V, V);
Misha Brukmanfd939082005-04-21 23:48:37 +0000746
Reid Spencere4d87aa2006-12-23 06:05:41 +0000747 // V >= Min && V < Hi --> V < Hi
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000748 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
Reid Spencere4e40032007-03-21 23:19:50 +0000749 ICmpInst::Predicate pred = (isSigned ?
Reid Spencere4d87aa2006-12-23 06:05:41 +0000750 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
Dan Gohman1c8a23c2009-08-25 23:17:54 +0000751 return new ICmpInst(pred, V, Hi);
Reid Spencere4d87aa2006-12-23 06:05:41 +0000752 }
753
754 // Emit V-Lo <u Hi-Lo
Owen Andersonbaf3c402009-07-29 18:55:55 +0000755 Constant *NegLo = ConstantExpr::getNeg(Lo);
Chris Lattner74381062009-08-30 07:44:24 +0000756 Value *Add = Builder->CreateAdd(V, NegLo, V->getName()+".off");
Owen Andersonbaf3c402009-07-29 18:55:55 +0000757 Constant *UpperBound = ConstantExpr::getAdd(NegLo, Hi);
Dan Gohman1c8a23c2009-08-25 23:17:54 +0000758 return new ICmpInst(ICmpInst::ICMP_ULT, Add, UpperBound);
Chris Lattnera96879a2004-09-29 17:40:11 +0000759 }
760
761 if (Lo == Hi) // Trivially true.
Dan Gohman1c8a23c2009-08-25 23:17:54 +0000762 return new ICmpInst(ICmpInst::ICMP_EQ, V, V);
Chris Lattnera96879a2004-09-29 17:40:11 +0000763
Reid Spencere4e40032007-03-21 23:19:50 +0000764 // V < Min || V >= Hi -> V > Hi-1
Dan Gohman186a6362009-08-12 16:04:34 +0000765 Hi = SubOne(cast<ConstantInt>(Hi));
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000766 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +0000767 ICmpInst::Predicate pred = (isSigned ?
768 ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
Dan Gohman1c8a23c2009-08-25 23:17:54 +0000769 return new ICmpInst(pred, V, Hi);
Reid Spencere4d87aa2006-12-23 06:05:41 +0000770 }
Reid Spencerb83eb642006-10-20 07:07:24 +0000771
Reid Spencere4e40032007-03-21 23:19:50 +0000772 // Emit V-Lo >u Hi-1-Lo
773 // Note that Hi has already had one subtracted from it, above.
Owen Andersonbaf3c402009-07-29 18:55:55 +0000774 ConstantInt *NegLo = cast<ConstantInt>(ConstantExpr::getNeg(Lo));
Chris Lattner74381062009-08-30 07:44:24 +0000775 Value *Add = Builder->CreateAdd(V, NegLo, V->getName()+".off");
Owen Andersonbaf3c402009-07-29 18:55:55 +0000776 Constant *LowerBound = ConstantExpr::getAdd(NegLo, Hi);
Dan Gohman1c8a23c2009-08-25 23:17:54 +0000777 return new ICmpInst(ICmpInst::ICMP_UGT, Add, LowerBound);
Chris Lattnera96879a2004-09-29 17:40:11 +0000778}
779
Chris Lattner7203e152005-09-18 07:22:02 +0000780// isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
781// any number of 0s on either side. The 1s are allowed to wrap from LSB to
782// MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs. 0x0F0F0000 is
783// not, since all 1s are not contiguous.
Zhou Sheng4351c642007-04-02 08:20:41 +0000784static bool isRunOfOnes(ConstantInt *Val, uint32_t &MB, uint32_t &ME) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +0000785 const APInt& V = Val->getValue();
Reid Spencerf2442522007-03-24 00:42:08 +0000786 uint32_t BitWidth = Val->getType()->getBitWidth();
787 if (!APIntOps::isShiftedMask(BitWidth, V)) return false;
Chris Lattner7203e152005-09-18 07:22:02 +0000788
789 // look for the first zero bit after the run of ones
Reid Spencerf2442522007-03-24 00:42:08 +0000790 MB = BitWidth - ((V - 1) ^ V).countLeadingZeros();
Chris Lattner7203e152005-09-18 07:22:02 +0000791 // look for the first non-zero bit
Reid Spencerf2442522007-03-24 00:42:08 +0000792 ME = V.getActiveBits();
Chris Lattner7203e152005-09-18 07:22:02 +0000793 return true;
794}
795
Chris Lattner7203e152005-09-18 07:22:02 +0000796/// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
797/// where isSub determines whether the operator is a sub. If we can fold one of
798/// the following xforms:
Chris Lattnerc8e77562005-09-18 04:24:45 +0000799///
800/// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
801/// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
802/// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
803///
804/// return (A +/- B).
805///
806Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000807 ConstantInt *Mask, bool isSub,
Chris Lattnerc8e77562005-09-18 04:24:45 +0000808 Instruction &I) {
809 Instruction *LHSI = dyn_cast<Instruction>(LHS);
810 if (!LHSI || LHSI->getNumOperands() != 2 ||
811 !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
812
813 ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
814
815 switch (LHSI->getOpcode()) {
816 default: return 0;
817 case Instruction::And:
Owen Andersonbaf3c402009-07-29 18:55:55 +0000818 if (ConstantExpr::getAnd(N, Mask) == Mask) {
Chris Lattner7203e152005-09-18 07:22:02 +0000819 // If the AndRHS is a power of two minus one (0+1+), this is simple.
Zhou Sheng00f436c2007-03-24 15:34:37 +0000820 if ((Mask->getValue().countLeadingZeros() +
821 Mask->getValue().countPopulation()) ==
822 Mask->getValue().getBitWidth())
Chris Lattner7203e152005-09-18 07:22:02 +0000823 break;
824
825 // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
826 // part, we don't need any explicit masks to take them out of A. If that
827 // is all N is, ignore it.
Zhou Sheng4351c642007-04-02 08:20:41 +0000828 uint32_t MB = 0, ME = 0;
Chris Lattner7203e152005-09-18 07:22:02 +0000829 if (isRunOfOnes(Mask, MB, ME)) { // begin/end bit of run, inclusive
Reid Spencerb35ae032007-03-23 18:46:34 +0000830 uint32_t BitWidth = cast<IntegerType>(RHS->getType())->getBitWidth();
Zhou Sheng290bec52007-03-29 08:15:12 +0000831 APInt Mask(APInt::getLowBitsSet(BitWidth, MB-1));
Chris Lattner3bedbd92006-02-07 07:27:52 +0000832 if (MaskedValueIsZero(RHS, Mask))
Chris Lattner7203e152005-09-18 07:22:02 +0000833 break;
834 }
835 }
Chris Lattnerc8e77562005-09-18 04:24:45 +0000836 return 0;
837 case Instruction::Or:
838 case Instruction::Xor:
Chris Lattner7203e152005-09-18 07:22:02 +0000839 // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
Zhou Sheng00f436c2007-03-24 15:34:37 +0000840 if ((Mask->getValue().countLeadingZeros() +
841 Mask->getValue().countPopulation()) == Mask->getValue().getBitWidth()
Owen Andersonbaf3c402009-07-29 18:55:55 +0000842 && ConstantExpr::getAnd(N, Mask)->isNullValue())
Chris Lattnerc8e77562005-09-18 04:24:45 +0000843 break;
844 return 0;
845 }
846
Chris Lattnerc8e77562005-09-18 04:24:45 +0000847 if (isSub)
Chris Lattner74381062009-08-30 07:44:24 +0000848 return Builder->CreateSub(LHSI->getOperand(0), RHS, "fold");
849 return Builder->CreateAdd(LHSI->getOperand(0), RHS, "fold");
Chris Lattnerc8e77562005-09-18 04:24:45 +0000850}
851
Chris Lattner29cd5ba2008-11-16 05:06:21 +0000852/// FoldAndOfICmps - Fold (icmp)&(icmp) if possible.
853Instruction *InstCombiner::FoldAndOfICmps(Instruction &I,
854 ICmpInst *LHS, ICmpInst *RHS) {
Chris Lattnera317e042010-01-05 06:59:49 +0000855 ICmpInst::Predicate LHSCC = LHS->getPredicate(), RHSCC = RHS->getPredicate();
856
857 // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
858 if (PredicatesFoldable(LHSCC, RHSCC)) {
859 if (LHS->getOperand(0) == RHS->getOperand(1) &&
860 LHS->getOperand(1) == RHS->getOperand(0))
861 LHS->swapOperands();
862 if (LHS->getOperand(0) == RHS->getOperand(0) &&
863 LHS->getOperand(1) == RHS->getOperand(1)) {
864 Value *Op0 = LHS->getOperand(0), *Op1 = LHS->getOperand(1);
865 unsigned Code = getICmpCode(LHS) & getICmpCode(RHS);
866 bool isSigned = LHS->isSigned() || RHS->isSigned();
867 Value *RV = getICmpValue(isSigned, Code, Op0, Op1);
868 if (Instruction *I = dyn_cast<Instruction>(RV))
869 return I;
870 // Otherwise, it's a constant boolean value.
871 return ReplaceInstUsesWith(I, RV);
872 }
873 }
Chris Lattner29cd5ba2008-11-16 05:06:21 +0000874
Chris Lattnerea065fb2008-11-16 05:10:52 +0000875 // This only handles icmp of constants: (icmp1 A, C1) & (icmp2 B, C2).
Chris Lattnera317e042010-01-05 06:59:49 +0000876 Value *Val = LHS->getOperand(0), *Val2 = RHS->getOperand(0);
877 ConstantInt *LHSCst = dyn_cast<ConstantInt>(LHS->getOperand(1));
878 ConstantInt *RHSCst = dyn_cast<ConstantInt>(RHS->getOperand(1));
879 if (LHSCst == 0 || RHSCst == 0) return 0;
Chris Lattnerea065fb2008-11-16 05:10:52 +0000880
Chris Lattner3f40e232009-11-29 00:51:17 +0000881 if (LHSCst == RHSCst && LHSCC == RHSCC) {
882 // (icmp ult A, C) & (icmp ult B, C) --> (icmp ult (A|B), C)
883 // where C is a power of 2
884 if (LHSCC == ICmpInst::ICMP_ULT &&
885 LHSCst->getValue().isPowerOf2()) {
886 Value *NewOr = Builder->CreateOr(Val, Val2);
887 return new ICmpInst(LHSCC, NewOr, LHSCst);
888 }
889
890 // (icmp eq A, 0) & (icmp eq B, 0) --> (icmp eq (A|B), 0)
891 if (LHSCC == ICmpInst::ICMP_EQ && LHSCst->isZero()) {
892 Value *NewOr = Builder->CreateOr(Val, Val2);
893 return new ICmpInst(LHSCC, NewOr, LHSCst);
894 }
Chris Lattnerea065fb2008-11-16 05:10:52 +0000895 }
896
897 // From here on, we only handle:
898 // (icmp1 A, C1) & (icmp2 A, C2) --> something simpler.
899 if (Val != Val2) return 0;
900
Chris Lattner29cd5ba2008-11-16 05:06:21 +0000901 // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
902 if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
903 RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
904 LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
905 RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
906 return 0;
907
908 // We can't fold (ugt x, C) & (sgt x, C2).
909 if (!PredicatesFoldable(LHSCC, RHSCC))
910 return 0;
911
912 // Ensure that the larger constant is on the RHS.
Chris Lattneraa3e1572008-11-16 05:14:43 +0000913 bool ShouldSwap;
Nick Lewycky4a134af2009-10-25 05:20:17 +0000914 if (CmpInst::isSigned(LHSCC) ||
Chris Lattner29cd5ba2008-11-16 05:06:21 +0000915 (ICmpInst::isEquality(LHSCC) &&
Nick Lewycky4a134af2009-10-25 05:20:17 +0000916 CmpInst::isSigned(RHSCC)))
Chris Lattneraa3e1572008-11-16 05:14:43 +0000917 ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
Chris Lattner29cd5ba2008-11-16 05:06:21 +0000918 else
Chris Lattneraa3e1572008-11-16 05:14:43 +0000919 ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
920
921 if (ShouldSwap) {
Chris Lattner29cd5ba2008-11-16 05:06:21 +0000922 std::swap(LHS, RHS);
923 std::swap(LHSCst, RHSCst);
924 std::swap(LHSCC, RHSCC);
925 }
926
927 // At this point, we know we have have two icmp instructions
928 // comparing a value against two constants and and'ing the result
929 // together. Because of the above check, we know that we only have
930 // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know
Chris Lattnera317e042010-01-05 06:59:49 +0000931 // (from the icmp folding check above), that the two constants
Chris Lattner29cd5ba2008-11-16 05:06:21 +0000932 // are not equal and that the larger constant is on the RHS
933 assert(LHSCst != RHSCst && "Compares not folded above?");
934
935 switch (LHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +0000936 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +0000937 case ICmpInst::ICMP_EQ:
938 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +0000939 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +0000940 case ICmpInst::ICMP_EQ: // (X == 13 & X == 15) -> false
941 case ICmpInst::ICMP_UGT: // (X == 13 & X > 15) -> false
942 case ICmpInst::ICMP_SGT: // (X == 13 & X > 15) -> false
Chris Lattner4de84762010-01-04 07:02:48 +0000943 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getContext()));
Chris Lattner29cd5ba2008-11-16 05:06:21 +0000944 case ICmpInst::ICMP_NE: // (X == 13 & X != 15) -> X == 13
945 case ICmpInst::ICMP_ULT: // (X == 13 & X < 15) -> X == 13
946 case ICmpInst::ICMP_SLT: // (X == 13 & X < 15) -> X == 13
947 return ReplaceInstUsesWith(I, LHS);
948 }
949 case ICmpInst::ICMP_NE:
950 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +0000951 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +0000952 case ICmpInst::ICMP_ULT:
Dan Gohman186a6362009-08-12 16:04:34 +0000953 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X u< 14) -> X < 13
Dan Gohman1c8a23c2009-08-25 23:17:54 +0000954 return new ICmpInst(ICmpInst::ICMP_ULT, Val, LHSCst);
Chris Lattner29cd5ba2008-11-16 05:06:21 +0000955 break; // (X != 13 & X u< 15) -> no change
956 case ICmpInst::ICMP_SLT:
Dan Gohman186a6362009-08-12 16:04:34 +0000957 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X s< 14) -> X < 13
Dan Gohman1c8a23c2009-08-25 23:17:54 +0000958 return new ICmpInst(ICmpInst::ICMP_SLT, Val, LHSCst);
Chris Lattner29cd5ba2008-11-16 05:06:21 +0000959 break; // (X != 13 & X s< 15) -> no change
960 case ICmpInst::ICMP_EQ: // (X != 13 & X == 15) -> X == 15
961 case ICmpInst::ICMP_UGT: // (X != 13 & X u> 15) -> X u> 15
962 case ICmpInst::ICMP_SGT: // (X != 13 & X s> 15) -> X s> 15
963 return ReplaceInstUsesWith(I, RHS);
964 case ICmpInst::ICMP_NE:
Dan Gohman186a6362009-08-12 16:04:34 +0000965 if (LHSCst == SubOne(RHSCst)){// (X != 13 & X != 14) -> X-13 >u 1
Owen Andersonbaf3c402009-07-29 18:55:55 +0000966 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
Chris Lattner74381062009-08-30 07:44:24 +0000967 Value *Add = Builder->CreateAdd(Val, AddCST, Val->getName()+".off");
Dan Gohman1c8a23c2009-08-25 23:17:54 +0000968 return new ICmpInst(ICmpInst::ICMP_UGT, Add,
Owen Andersoneed707b2009-07-24 23:12:02 +0000969 ConstantInt::get(Add->getType(), 1));
Chris Lattner29cd5ba2008-11-16 05:06:21 +0000970 }
971 break; // (X != 13 & X != 15) -> no change
972 }
973 break;
974 case ICmpInst::ICMP_ULT:
975 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +0000976 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +0000977 case ICmpInst::ICMP_EQ: // (X u< 13 & X == 15) -> false
978 case ICmpInst::ICMP_UGT: // (X u< 13 & X u> 15) -> false
Chris Lattner4de84762010-01-04 07:02:48 +0000979 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getContext()));
Chris Lattner29cd5ba2008-11-16 05:06:21 +0000980 case ICmpInst::ICMP_SGT: // (X u< 13 & X s> 15) -> no change
981 break;
982 case ICmpInst::ICMP_NE: // (X u< 13 & X != 15) -> X u< 13
983 case ICmpInst::ICMP_ULT: // (X u< 13 & X u< 15) -> X u< 13
984 return ReplaceInstUsesWith(I, LHS);
985 case ICmpInst::ICMP_SLT: // (X u< 13 & X s< 15) -> no change
986 break;
987 }
988 break;
989 case ICmpInst::ICMP_SLT:
990 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +0000991 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +0000992 case ICmpInst::ICMP_EQ: // (X s< 13 & X == 15) -> false
993 case ICmpInst::ICMP_SGT: // (X s< 13 & X s> 15) -> false
Chris Lattner4de84762010-01-04 07:02:48 +0000994 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getContext()));
Chris Lattner29cd5ba2008-11-16 05:06:21 +0000995 case ICmpInst::ICMP_UGT: // (X s< 13 & X u> 15) -> no change
996 break;
997 case ICmpInst::ICMP_NE: // (X s< 13 & X != 15) -> X < 13
998 case ICmpInst::ICMP_SLT: // (X s< 13 & X s< 15) -> X < 13
999 return ReplaceInstUsesWith(I, LHS);
1000 case ICmpInst::ICMP_ULT: // (X s< 13 & X u< 15) -> no change
1001 break;
1002 }
1003 break;
1004 case ICmpInst::ICMP_UGT:
1005 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00001006 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00001007 case ICmpInst::ICMP_EQ: // (X u> 13 & X == 15) -> X == 15
1008 case ICmpInst::ICMP_UGT: // (X u> 13 & X u> 15) -> X u> 15
1009 return ReplaceInstUsesWith(I, RHS);
1010 case ICmpInst::ICMP_SGT: // (X u> 13 & X s> 15) -> no change
1011 break;
1012 case ICmpInst::ICMP_NE:
Dan Gohman186a6362009-08-12 16:04:34 +00001013 if (RHSCst == AddOne(LHSCst)) // (X u> 13 & X != 14) -> X u> 14
Dan Gohman1c8a23c2009-08-25 23:17:54 +00001014 return new ICmpInst(LHSCC, Val, RHSCst);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00001015 break; // (X u> 13 & X != 15) -> no change
Chris Lattner69d4ced2008-11-16 05:20:07 +00001016 case ICmpInst::ICMP_ULT: // (X u> 13 & X u< 15) -> (X-14) <u 1
Dan Gohman186a6362009-08-12 16:04:34 +00001017 return InsertRangeTest(Val, AddOne(LHSCst),
Owen Andersond672ecb2009-07-03 00:17:18 +00001018 RHSCst, false, true, I);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00001019 case ICmpInst::ICMP_SLT: // (X u> 13 & X s< 15) -> no change
1020 break;
1021 }
1022 break;
1023 case ICmpInst::ICMP_SGT:
1024 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00001025 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00001026 case ICmpInst::ICMP_EQ: // (X s> 13 & X == 15) -> X == 15
1027 case ICmpInst::ICMP_SGT: // (X s> 13 & X s> 15) -> X s> 15
1028 return ReplaceInstUsesWith(I, RHS);
1029 case ICmpInst::ICMP_UGT: // (X s> 13 & X u> 15) -> no change
1030 break;
1031 case ICmpInst::ICMP_NE:
Dan Gohman186a6362009-08-12 16:04:34 +00001032 if (RHSCst == AddOne(LHSCst)) // (X s> 13 & X != 14) -> X s> 14
Dan Gohman1c8a23c2009-08-25 23:17:54 +00001033 return new ICmpInst(LHSCC, Val, RHSCst);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00001034 break; // (X s> 13 & X != 15) -> no change
Chris Lattner69d4ced2008-11-16 05:20:07 +00001035 case ICmpInst::ICMP_SLT: // (X s> 13 & X s< 15) -> (X-14) s< 1
Dan Gohman186a6362009-08-12 16:04:34 +00001036 return InsertRangeTest(Val, AddOne(LHSCst),
Owen Andersond672ecb2009-07-03 00:17:18 +00001037 RHSCst, true, true, I);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00001038 case ICmpInst::ICMP_ULT: // (X s> 13 & X u< 15) -> no change
1039 break;
1040 }
1041 break;
1042 }
Chris Lattner29cd5ba2008-11-16 05:06:21 +00001043
1044 return 0;
1045}
1046
Chris Lattner42d1be02009-07-23 05:14:02 +00001047Instruction *InstCombiner::FoldAndOfFCmps(Instruction &I, FCmpInst *LHS,
1048 FCmpInst *RHS) {
1049
1050 if (LHS->getPredicate() == FCmpInst::FCMP_ORD &&
1051 RHS->getPredicate() == FCmpInst::FCMP_ORD) {
1052 // (fcmp ord x, c) & (fcmp ord y, c) -> (fcmp ord x, y)
1053 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
1054 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
1055 // If either of the constants are nans, then the whole thing returns
1056 // false.
1057 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Chris Lattner4de84762010-01-04 07:02:48 +00001058 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getContext()));
Dan Gohman1c8a23c2009-08-25 23:17:54 +00001059 return new FCmpInst(FCmpInst::FCMP_ORD,
Chris Lattner42d1be02009-07-23 05:14:02 +00001060 LHS->getOperand(0), RHS->getOperand(0));
1061 }
Chris Lattnerf98d2532009-07-23 05:32:17 +00001062
1063 // Handle vector zeros. This occurs because the canonical form of
1064 // "fcmp ord x,x" is "fcmp ord x, 0".
1065 if (isa<ConstantAggregateZero>(LHS->getOperand(1)) &&
1066 isa<ConstantAggregateZero>(RHS->getOperand(1)))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00001067 return new FCmpInst(FCmpInst::FCMP_ORD,
Chris Lattnerf98d2532009-07-23 05:32:17 +00001068 LHS->getOperand(0), RHS->getOperand(0));
Chris Lattner42d1be02009-07-23 05:14:02 +00001069 return 0;
1070 }
1071
1072 Value *Op0LHS = LHS->getOperand(0), *Op0RHS = LHS->getOperand(1);
1073 Value *Op1LHS = RHS->getOperand(0), *Op1RHS = RHS->getOperand(1);
1074 FCmpInst::Predicate Op0CC = LHS->getPredicate(), Op1CC = RHS->getPredicate();
1075
1076
1077 if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
1078 // Swap RHS operands to match LHS.
1079 Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
1080 std::swap(Op1LHS, Op1RHS);
1081 }
1082
1083 if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
1084 // Simplify (fcmp cc0 x, y) & (fcmp cc1 x, y).
1085 if (Op0CC == Op1CC)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00001086 return new FCmpInst((FCmpInst::Predicate)Op0CC, Op0LHS, Op0RHS);
Chris Lattner42d1be02009-07-23 05:14:02 +00001087
1088 if (Op0CC == FCmpInst::FCMP_FALSE || Op1CC == FCmpInst::FCMP_FALSE)
Chris Lattner4de84762010-01-04 07:02:48 +00001089 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getContext()));
Chris Lattner42d1be02009-07-23 05:14:02 +00001090 if (Op0CC == FCmpInst::FCMP_TRUE)
1091 return ReplaceInstUsesWith(I, RHS);
1092 if (Op1CC == FCmpInst::FCMP_TRUE)
1093 return ReplaceInstUsesWith(I, LHS);
1094
1095 bool Op0Ordered;
1096 bool Op1Ordered;
1097 unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
1098 unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
1099 if (Op1Pred == 0) {
1100 std::swap(LHS, RHS);
1101 std::swap(Op0Pred, Op1Pred);
1102 std::swap(Op0Ordered, Op1Ordered);
1103 }
1104 if (Op0Pred == 0) {
1105 // uno && ueq -> uno && (uno || eq) -> ueq
1106 // ord && olt -> ord && (ord && lt) -> olt
1107 if (Op0Ordered == Op1Ordered)
1108 return ReplaceInstUsesWith(I, RHS);
1109
1110 // uno && oeq -> uno && (ord && eq) -> false
1111 // uno && ord -> false
1112 if (!Op0Ordered)
Chris Lattner4de84762010-01-04 07:02:48 +00001113 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getContext()));
Chris Lattner42d1be02009-07-23 05:14:02 +00001114 // ord && ueq -> ord && (uno || eq) -> oeq
Chris Lattner4de84762010-01-04 07:02:48 +00001115 return cast<Instruction>(getFCmpValue(true, Op1Pred, Op0LHS, Op0RHS));
Chris Lattner42d1be02009-07-23 05:14:02 +00001116 }
1117 }
1118
1119 return 0;
1120}
1121
Chris Lattner29cd5ba2008-11-16 05:06:21 +00001122
Chris Lattner7e708292002-06-25 16:13:24 +00001123Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00001124 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00001125 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00001126
Chris Lattnerd06094f2009-11-10 00:55:12 +00001127 if (Value *V = SimplifyAndInst(Op0, Op1, TD))
1128 return ReplaceInstUsesWith(I, V);
Chris Lattner3f5b8772002-05-06 16:14:14 +00001129
Chris Lattnerf8c36f52006-02-12 08:02:11 +00001130 // See if we can simplify any instructions used by the instruction whose sole
Chris Lattner9ca96412006-02-08 03:25:32 +00001131 // purpose is to compute bits we don't care about.
Dan Gohman6de29f82009-06-15 22:12:54 +00001132 if (SimplifyDemandedInstructionBits(I))
Nick Lewycky546d6312010-01-02 15:25:44 +00001133 return &I;
Dan Gohman6de29f82009-06-15 22:12:54 +00001134
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00001135 if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner7acdf1d2009-10-11 22:00:32 +00001136 const APInt &AndRHSMask = AndRHS->getValue();
Zhou Sheng3a507fd2007-04-01 17:13:37 +00001137 APInt NotAndRHS(~AndRHSMask);
Chris Lattner6e7ba452005-01-01 16:22:27 +00001138
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00001139 // Optimize a variety of ((val OP C1) & C2) combinations...
Chris Lattner7acdf1d2009-10-11 22:00:32 +00001140 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Chris Lattner6e7ba452005-01-01 16:22:27 +00001141 Value *Op0LHS = Op0I->getOperand(0);
1142 Value *Op0RHS = Op0I->getOperand(1);
1143 switch (Op0I->getOpcode()) {
Chris Lattner7acdf1d2009-10-11 22:00:32 +00001144 default: break;
Chris Lattner6e7ba452005-01-01 16:22:27 +00001145 case Instruction::Xor:
1146 case Instruction::Or:
Chris Lattnerad1e3022005-01-23 20:26:55 +00001147 // If the mask is only needed on one incoming arm, push it up.
Chris Lattner7acdf1d2009-10-11 22:00:32 +00001148 if (!Op0I->hasOneUse()) break;
1149
1150 if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
1151 // Not masking anything out for the LHS, move to RHS.
1152 Value *NewRHS = Builder->CreateAnd(Op0RHS, AndRHS,
1153 Op0RHS->getName()+".masked");
1154 return BinaryOperator::Create(Op0I->getOpcode(), Op0LHS, NewRHS);
1155 }
1156 if (!isa<Constant>(Op0RHS) &&
1157 MaskedValueIsZero(Op0RHS, NotAndRHS)) {
1158 // Not masking anything out for the RHS, move to LHS.
1159 Value *NewLHS = Builder->CreateAnd(Op0LHS, AndRHS,
1160 Op0LHS->getName()+".masked");
1161 return BinaryOperator::Create(Op0I->getOpcode(), NewLHS, Op0RHS);
Chris Lattnerad1e3022005-01-23 20:26:55 +00001162 }
1163
Chris Lattner6e7ba452005-01-01 16:22:27 +00001164 break;
Chris Lattnerc8e77562005-09-18 04:24:45 +00001165 case Instruction::Add:
Chris Lattner7203e152005-09-18 07:22:02 +00001166 // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
1167 // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
1168 // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
1169 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001170 return BinaryOperator::CreateAnd(V, AndRHS);
Chris Lattner7203e152005-09-18 07:22:02 +00001171 if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001172 return BinaryOperator::CreateAnd(V, AndRHS); // Add commutes
Chris Lattnerc8e77562005-09-18 04:24:45 +00001173 break;
1174
1175 case Instruction::Sub:
Chris Lattner7203e152005-09-18 07:22:02 +00001176 // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
1177 // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
1178 // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
1179 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001180 return BinaryOperator::CreateAnd(V, AndRHS);
Nick Lewyckyb4d1bc92008-07-09 04:32:37 +00001181
Nick Lewycky5dcc41f2008-07-10 05:51:40 +00001182 // (A - N) & AndRHS -> -N & AndRHS iff A&AndRHS==0 and AndRHS
1183 // has 1's for all bits that the subtraction with A might affect.
1184 if (Op0I->hasOneUse()) {
1185 uint32_t BitWidth = AndRHSMask.getBitWidth();
1186 uint32_t Zeros = AndRHSMask.countLeadingZeros();
1187 APInt Mask = APInt::getLowBitsSet(BitWidth, BitWidth - Zeros);
1188
Nick Lewyckyb4d1bc92008-07-09 04:32:37 +00001189 ConstantInt *A = dyn_cast<ConstantInt>(Op0LHS);
Nick Lewycky5dcc41f2008-07-10 05:51:40 +00001190 if (!(A && A->isZero()) && // avoid infinite recursion.
1191 MaskedValueIsZero(Op0LHS, Mask)) {
Chris Lattner74381062009-08-30 07:44:24 +00001192 Value *NewNeg = Builder->CreateNeg(Op0RHS);
Nick Lewyckyb4d1bc92008-07-09 04:32:37 +00001193 return BinaryOperator::CreateAnd(NewNeg, AndRHS);
1194 }
1195 }
Chris Lattnerc8e77562005-09-18 04:24:45 +00001196 break;
Nick Lewyckyd1f77bf2008-07-09 05:20:13 +00001197
1198 case Instruction::Shl:
1199 case Instruction::LShr:
1200 // (1 << x) & 1 --> zext(x == 0)
1201 // (1 >> x) & 1 --> zext(x == 0)
Nick Lewyckyd8ad4922008-07-09 07:35:26 +00001202 if (AndRHSMask == 1 && Op0LHS == AndRHS) {
Chris Lattner74381062009-08-30 07:44:24 +00001203 Value *NewICmp =
1204 Builder->CreateICmpEQ(Op0RHS, Constant::getNullValue(I.getType()));
Nick Lewyckyd1f77bf2008-07-09 05:20:13 +00001205 return new ZExtInst(NewICmp, I.getType());
1206 }
1207 break;
Chris Lattner6e7ba452005-01-01 16:22:27 +00001208 }
1209
Chris Lattner58403262003-07-23 19:25:52 +00001210 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattner6e7ba452005-01-01 16:22:27 +00001211 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00001212 return Res;
Chris Lattner6e7ba452005-01-01 16:22:27 +00001213 } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
Chris Lattner2b83af22005-08-07 07:03:10 +00001214 // If this is an integer truncation or change from signed-to-unsigned, and
1215 // if the source is an and/or with immediate, transform it. This
1216 // frequently occurs for bitfield accesses.
1217 if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
Reid Spencer3da59db2006-11-27 01:05:10 +00001218 if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
Chris Lattner2b83af22005-08-07 07:03:10 +00001219 CastOp->getNumOperands() == 2)
Chris Lattner48b59ec2009-10-26 15:40:07 +00001220 if (ConstantInt *AndCI =dyn_cast<ConstantInt>(CastOp->getOperand(1))){
Chris Lattner2b83af22005-08-07 07:03:10 +00001221 if (CastOp->getOpcode() == Instruction::And) {
1222 // Change: and (cast (and X, C1) to T), C2
Reid Spencer3da59db2006-11-27 01:05:10 +00001223 // into : and (cast X to T), trunc_or_bitcast(C1)&C2
1224 // This will fold the two constants together, which may allow
1225 // other simplifications.
Chris Lattner74381062009-08-30 07:44:24 +00001226 Value *NewCast = Builder->CreateTruncOrBitCast(
Reid Spencerd977d862006-12-12 23:36:14 +00001227 CastOp->getOperand(0), I.getType(),
1228 CastOp->getName()+".shrunk");
Reid Spencer3da59db2006-11-27 01:05:10 +00001229 // trunc_or_bitcast(C1)&C2
Chris Lattner74381062009-08-30 07:44:24 +00001230 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
Owen Andersonbaf3c402009-07-29 18:55:55 +00001231 C3 = ConstantExpr::getAnd(C3, AndRHS);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001232 return BinaryOperator::CreateAnd(NewCast, C3);
Chris Lattner2b83af22005-08-07 07:03:10 +00001233 } else if (CastOp->getOpcode() == Instruction::Or) {
1234 // Change: and (cast (or X, C1) to T), C2
1235 // into : trunc(C1)&C2 iff trunc(C1)&C2 == C2
Chris Lattner74381062009-08-30 07:44:24 +00001236 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
Owen Andersonbaf3c402009-07-29 18:55:55 +00001237 if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS)
Owen Andersond672ecb2009-07-03 00:17:18 +00001238 // trunc(C1)&C2
Chris Lattner2b83af22005-08-07 07:03:10 +00001239 return ReplaceInstUsesWith(I, AndRHS);
1240 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00001241 }
Chris Lattner2b83af22005-08-07 07:03:10 +00001242 }
Chris Lattner06782f82003-07-23 19:36:21 +00001243 }
Chris Lattner2eefe512004-04-09 19:05:30 +00001244
1245 // Try to fold constant and into select arguments.
1246 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner80f43d32010-01-04 07:53:58 +00001247 if (Instruction *R = FoldOpIntoSelect(I, SI))
Chris Lattner2eefe512004-04-09 19:05:30 +00001248 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00001249 if (isa<PHINode>(Op0))
1250 if (Instruction *NV = FoldOpIntoPhi(I))
1251 return NV;
Chris Lattnerc6a8aff2003-07-23 17:57:01 +00001252 }
1253
Chris Lattner5b62aa72004-06-18 06:07:51 +00001254
Misha Brukmancb6267b2004-07-30 12:50:08 +00001255 // (~A & ~B) == (~(A | B)) - De Morgan's Law
Chris Lattnerd06094f2009-11-10 00:55:12 +00001256 if (Value *Op0NotVal = dyn_castNotVal(Op0))
1257 if (Value *Op1NotVal = dyn_castNotVal(Op1))
1258 if (Op0->hasOneUse() && Op1->hasOneUse()) {
1259 Value *Or = Builder->CreateOr(Op0NotVal, Op1NotVal,
1260 I.getName()+".demorgan");
1261 return BinaryOperator::CreateNot(Or);
1262 }
1263
Chris Lattner2082ad92006-02-13 23:07:23 +00001264 {
Chris Lattner003b6202007-06-15 05:58:24 +00001265 Value *A = 0, *B = 0, *C = 0, *D = 0;
Chris Lattnerd06094f2009-11-10 00:55:12 +00001266 // (A|B) & ~(A&B) -> A^B
1267 if (match(Op0, m_Or(m_Value(A), m_Value(B))) &&
1268 match(Op1, m_Not(m_And(m_Value(C), m_Value(D)))) &&
1269 ((A == C && B == D) || (A == D && B == C)))
1270 return BinaryOperator::CreateXor(A, B);
Chris Lattner003b6202007-06-15 05:58:24 +00001271
Chris Lattnerd06094f2009-11-10 00:55:12 +00001272 // ~(A&B) & (A|B) -> A^B
1273 if (match(Op1, m_Or(m_Value(A), m_Value(B))) &&
1274 match(Op0, m_Not(m_And(m_Value(C), m_Value(D)))) &&
1275 ((A == C && B == D) || (A == D && B == C)))
1276 return BinaryOperator::CreateXor(A, B);
Chris Lattner64daab52006-04-01 08:03:55 +00001277
1278 if (Op0->hasOneUse() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00001279 match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
Chris Lattner64daab52006-04-01 08:03:55 +00001280 if (A == Op1) { // (A^B)&A -> A&(A^B)
1281 I.swapOperands(); // Simplify below
1282 std::swap(Op0, Op1);
1283 } else if (B == Op1) { // (A^B)&B -> B&(B^A)
1284 cast<BinaryOperator>(Op0)->swapOperands();
1285 I.swapOperands(); // Simplify below
1286 std::swap(Op0, Op1);
1287 }
1288 }
Bill Wendling7f0ef6b2008-11-30 13:08:13 +00001289
Chris Lattner64daab52006-04-01 08:03:55 +00001290 if (Op1->hasOneUse() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00001291 match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
Chris Lattner64daab52006-04-01 08:03:55 +00001292 if (B == Op0) { // B&(A^B) -> B&(B^A)
1293 cast<BinaryOperator>(Op1)->swapOperands();
1294 std::swap(A, B);
1295 }
Chris Lattner74381062009-08-30 07:44:24 +00001296 if (A == Op0) // A&(A^B) -> A & ~B
1297 return BinaryOperator::CreateAnd(A, Builder->CreateNot(B, "tmp"));
Chris Lattner64daab52006-04-01 08:03:55 +00001298 }
Bill Wendling7f0ef6b2008-11-30 13:08:13 +00001299
1300 // (A&((~A)|B)) -> A&B
Dan Gohman4ae51262009-08-12 16:23:25 +00001301 if (match(Op0, m_Or(m_Not(m_Specific(Op1)), m_Value(A))) ||
1302 match(Op0, m_Or(m_Value(A), m_Not(m_Specific(Op1)))))
Chris Lattnerd8aafcb2008-12-01 05:16:26 +00001303 return BinaryOperator::CreateAnd(A, Op1);
Dan Gohman4ae51262009-08-12 16:23:25 +00001304 if (match(Op1, m_Or(m_Not(m_Specific(Op0)), m_Value(A))) ||
1305 match(Op1, m_Or(m_Value(A), m_Not(m_Specific(Op0)))))
Chris Lattnerd8aafcb2008-12-01 05:16:26 +00001306 return BinaryOperator::CreateAnd(A, Op0);
Chris Lattner2082ad92006-02-13 23:07:23 +00001307 }
1308
Chris Lattnera317e042010-01-05 06:59:49 +00001309 if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1))
Chris Lattner29cd5ba2008-11-16 05:06:21 +00001310 if (ICmpInst *LHS = dyn_cast<ICmpInst>(Op0))
1311 if (Instruction *Res = FoldAndOfICmps(I, LHS, RHS))
1312 return Res;
Chris Lattner955f3312004-09-28 21:48:02 +00001313
Chris Lattner6fc205f2006-05-05 06:39:07 +00001314 // fold (and (cast A), (cast B)) -> (cast (and A, B))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00001315 if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
1316 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
1317 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind ?
1318 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattnerf98d2532009-07-23 05:32:17 +00001319 if (SrcTy == Op1C->getOperand(0)->getType() &&
1320 SrcTy->isIntOrIntVector() &&
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00001321 // Only do this if the casts both really cause code to be generated.
Chris Lattner80f43d32010-01-04 07:53:58 +00001322 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
1323 I.getType()) &&
Reid Spencere4d87aa2006-12-23 06:05:41 +00001324 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
Chris Lattner80f43d32010-01-04 07:53:58 +00001325 I.getType())) {
Chris Lattner74381062009-08-30 07:44:24 +00001326 Value *NewOp = Builder->CreateAnd(Op0C->getOperand(0),
1327 Op1C->getOperand(0), I.getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001328 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00001329 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00001330 }
Chris Lattnere511b742006-11-14 07:46:50 +00001331
1332 // (X >> Z) & (Y >> Z) -> (X&Y) >> Z for all shifts.
Reid Spencer832254e2007-02-02 02:16:23 +00001333 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
1334 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
1335 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
Chris Lattnere511b742006-11-14 07:46:50 +00001336 SI0->getOperand(1) == SI1->getOperand(1) &&
1337 (SI0->hasOneUse() || SI1->hasOneUse())) {
Chris Lattner74381062009-08-30 07:44:24 +00001338 Value *NewOp =
1339 Builder->CreateAnd(SI0->getOperand(0), SI1->getOperand(0),
1340 SI0->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001341 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
Reid Spencer832254e2007-02-02 02:16:23 +00001342 SI1->getOperand(1));
Chris Lattnere511b742006-11-14 07:46:50 +00001343 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00001344 }
1345
Evan Cheng8db90722008-10-14 17:15:11 +00001346 // If and'ing two fcmp, try combine them into one.
Chris Lattner99c65742007-10-24 05:38:08 +00001347 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
Chris Lattner42d1be02009-07-23 05:14:02 +00001348 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
1349 if (Instruction *Res = FoldAndOfFCmps(I, LHS, RHS))
1350 return Res;
Chris Lattner99c65742007-10-24 05:38:08 +00001351 }
Nick Lewyckyb4d1bc92008-07-09 04:32:37 +00001352
Chris Lattner7e708292002-06-25 16:13:24 +00001353 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00001354}
1355
Chris Lattner8c34cd22008-10-05 02:13:19 +00001356/// CollectBSwapParts - Analyze the specified subexpression and see if it is
1357/// capable of providing pieces of a bswap. The subexpression provides pieces
1358/// of a bswap if it is proven that each of the non-zero bytes in the output of
1359/// the expression came from the corresponding "byte swapped" byte in some other
1360/// value. For example, if the current subexpression is "(shl i32 %X, 24)" then
1361/// we know that the expression deposits the low byte of %X into the high byte
1362/// of the bswap result and that all other bytes are zero. This expression is
1363/// accepted, the high byte of ByteValues is set to X to indicate a correct
1364/// match.
1365///
1366/// This function returns true if the match was unsuccessful and false if so.
1367/// On entry to the function the "OverallLeftShift" is a signed integer value
1368/// indicating the number of bytes that the subexpression is later shifted. For
1369/// example, if the expression is later right shifted by 16 bits, the
1370/// OverallLeftShift value would be -2 on entry. This is used to specify which
1371/// byte of ByteValues is actually being set.
1372///
1373/// Similarly, ByteMask is a bitmask where a bit is clear if its corresponding
1374/// byte is masked to zero by a user. For example, in (X & 255), X will be
1375/// processed with a bytemask of 1. Because bytemask is 32-bits, this limits
1376/// this function to working on up to 32-byte (256 bit) values. ByteMask is
1377/// always in the local (OverallLeftShift) coordinate space.
1378///
1379static bool CollectBSwapParts(Value *V, int OverallLeftShift, uint32_t ByteMask,
1380 SmallVector<Value*, 8> &ByteValues) {
1381 if (Instruction *I = dyn_cast<Instruction>(V)) {
1382 // If this is an or instruction, it may be an inner node of the bswap.
1383 if (I->getOpcode() == Instruction::Or) {
1384 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
1385 ByteValues) ||
1386 CollectBSwapParts(I->getOperand(1), OverallLeftShift, ByteMask,
1387 ByteValues);
Chris Lattnerafe91a52006-06-15 19:07:26 +00001388 }
Chris Lattner8c34cd22008-10-05 02:13:19 +00001389
1390 // If this is a logical shift by a constant multiple of 8, recurse with
1391 // OverallLeftShift and ByteMask adjusted.
1392 if (I->isLogicalShift() && isa<ConstantInt>(I->getOperand(1))) {
1393 unsigned ShAmt =
1394 cast<ConstantInt>(I->getOperand(1))->getLimitedValue(~0U);
1395 // Ensure the shift amount is defined and of a byte value.
1396 if ((ShAmt & 7) || (ShAmt > 8*ByteValues.size()))
1397 return true;
1398
1399 unsigned ByteShift = ShAmt >> 3;
1400 if (I->getOpcode() == Instruction::Shl) {
1401 // X << 2 -> collect(X, +2)
1402 OverallLeftShift += ByteShift;
1403 ByteMask >>= ByteShift;
1404 } else {
1405 // X >>u 2 -> collect(X, -2)
1406 OverallLeftShift -= ByteShift;
1407 ByteMask <<= ByteShift;
Chris Lattnerde17ddc2008-10-08 06:42:28 +00001408 ByteMask &= (~0U >> (32-ByteValues.size()));
Chris Lattner8c34cd22008-10-05 02:13:19 +00001409 }
1410
1411 if (OverallLeftShift >= (int)ByteValues.size()) return true;
1412 if (OverallLeftShift <= -(int)ByteValues.size()) return true;
1413
1414 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
1415 ByteValues);
1416 }
1417
1418 // If this is a logical 'and' with a mask that clears bytes, clear the
1419 // corresponding bytes in ByteMask.
1420 if (I->getOpcode() == Instruction::And &&
1421 isa<ConstantInt>(I->getOperand(1))) {
1422 // Scan every byte of the and mask, seeing if the byte is either 0 or 255.
1423 unsigned NumBytes = ByteValues.size();
1424 APInt Byte(I->getType()->getPrimitiveSizeInBits(), 255);
1425 const APInt &AndMask = cast<ConstantInt>(I->getOperand(1))->getValue();
1426
1427 for (unsigned i = 0; i != NumBytes; ++i, Byte <<= 8) {
1428 // If this byte is masked out by a later operation, we don't care what
1429 // the and mask is.
1430 if ((ByteMask & (1 << i)) == 0)
1431 continue;
1432
1433 // If the AndMask is all zeros for this byte, clear the bit.
1434 APInt MaskB = AndMask & Byte;
1435 if (MaskB == 0) {
1436 ByteMask &= ~(1U << i);
1437 continue;
1438 }
1439
1440 // If the AndMask is not all ones for this byte, it's not a bytezap.
1441 if (MaskB != Byte)
1442 return true;
1443
1444 // Otherwise, this byte is kept.
1445 }
1446
1447 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
1448 ByteValues);
1449 }
Chris Lattnerafe91a52006-06-15 19:07:26 +00001450 }
1451
Chris Lattner8c34cd22008-10-05 02:13:19 +00001452 // Okay, we got to something that isn't a shift, 'or' or 'and'. This must be
1453 // the input value to the bswap. Some observations: 1) if more than one byte
1454 // is demanded from this input, then it could not be successfully assembled
1455 // into a byteswap. At least one of the two bytes would not be aligned with
1456 // their ultimate destination.
1457 if (!isPowerOf2_32(ByteMask)) return true;
1458 unsigned InputByteNo = CountTrailingZeros_32(ByteMask);
Chris Lattnerafe91a52006-06-15 19:07:26 +00001459
Chris Lattner8c34cd22008-10-05 02:13:19 +00001460 // 2) The input and ultimate destinations must line up: if byte 3 of an i32
1461 // is demanded, it needs to go into byte 0 of the result. This means that the
1462 // byte needs to be shifted until it lands in the right byte bucket. The
1463 // shift amount depends on the position: if the byte is coming from the high
1464 // part of the value (e.g. byte 3) then it must be shifted right. If from the
1465 // low part, it must be shifted left.
1466 unsigned DestByteNo = InputByteNo + OverallLeftShift;
1467 if (InputByteNo < ByteValues.size()/2) {
1468 if (ByteValues.size()-1-DestByteNo != InputByteNo)
1469 return true;
1470 } else {
1471 if (ByteValues.size()-1-DestByteNo != InputByteNo)
1472 return true;
1473 }
Chris Lattnerafe91a52006-06-15 19:07:26 +00001474
1475 // If the destination byte value is already defined, the values are or'd
1476 // together, which isn't a bswap (unless it's an or of the same bits).
Chris Lattner8c34cd22008-10-05 02:13:19 +00001477 if (ByteValues[DestByteNo] && ByteValues[DestByteNo] != V)
Chris Lattnerafe91a52006-06-15 19:07:26 +00001478 return true;
Chris Lattner8c34cd22008-10-05 02:13:19 +00001479 ByteValues[DestByteNo] = V;
Chris Lattnerafe91a52006-06-15 19:07:26 +00001480 return false;
1481}
1482
1483/// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
1484/// If so, insert the new bswap intrinsic and return it.
1485Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
Chris Lattner55fc8c42007-04-01 20:57:36 +00001486 const IntegerType *ITy = dyn_cast<IntegerType>(I.getType());
Chris Lattner8c34cd22008-10-05 02:13:19 +00001487 if (!ITy || ITy->getBitWidth() % 16 ||
1488 // ByteMask only allows up to 32-byte values.
1489 ITy->getBitWidth() > 32*8)
Chris Lattner55fc8c42007-04-01 20:57:36 +00001490 return 0; // Can only bswap pairs of bytes. Can't do vectors.
Chris Lattnerafe91a52006-06-15 19:07:26 +00001491
1492 /// ByteValues - For each byte of the result, we keep track of which value
1493 /// defines each byte.
Chris Lattner535014f2007-02-15 22:52:10 +00001494 SmallVector<Value*, 8> ByteValues;
Chris Lattner55fc8c42007-04-01 20:57:36 +00001495 ByteValues.resize(ITy->getBitWidth()/8);
Chris Lattnerafe91a52006-06-15 19:07:26 +00001496
1497 // Try to find all the pieces corresponding to the bswap.
Chris Lattner8c34cd22008-10-05 02:13:19 +00001498 uint32_t ByteMask = ~0U >> (32-ByteValues.size());
1499 if (CollectBSwapParts(&I, 0, ByteMask, ByteValues))
Chris Lattnerafe91a52006-06-15 19:07:26 +00001500 return 0;
1501
1502 // Check to see if all of the bytes come from the same value.
1503 Value *V = ByteValues[0];
1504 if (V == 0) return 0; // Didn't find a byte? Must be zero.
1505
1506 // Check to make sure that all of the bytes come from the same value.
1507 for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
1508 if (ByteValues[i] != V)
1509 return 0;
Chandler Carruth69940402007-08-04 01:51:18 +00001510 const Type *Tys[] = { ITy };
Chris Lattnerafe91a52006-06-15 19:07:26 +00001511 Module *M = I.getParent()->getParent()->getParent();
Chandler Carruth69940402007-08-04 01:51:18 +00001512 Function *F = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 1);
Gabor Greif051a9502008-04-06 20:25:17 +00001513 return CallInst::Create(F, V);
Chris Lattnerafe91a52006-06-15 19:07:26 +00001514}
1515
Chris Lattnerfaaf9512008-11-16 04:24:12 +00001516/// MatchSelectFromAndOr - We have an expression of the form (A&C)|(B&D). Check
1517/// If A is (cond?-1:0) and either B or D is ~(cond?-1,0) or (cond?0,-1), then
1518/// we can simplify this expression to "cond ? C : D or B".
1519static Instruction *MatchSelectFromAndOr(Value *A, Value *B,
Chris Lattner4de84762010-01-04 07:02:48 +00001520 Value *C, Value *D) {
Chris Lattnera6a474d2008-11-16 04:26:55 +00001521 // If A is not a select of -1/0, this cannot match.
Chris Lattner6046fb72008-11-16 04:46:19 +00001522 Value *Cond = 0;
Dan Gohman4ae51262009-08-12 16:23:25 +00001523 if (!match(A, m_SelectCst<-1, 0>(m_Value(Cond))))
Chris Lattnerfaaf9512008-11-16 04:24:12 +00001524 return 0;
1525
Chris Lattnera6a474d2008-11-16 04:26:55 +00001526 // ((cond?-1:0)&C) | (B&(cond?0:-1)) -> cond ? C : B.
Dan Gohman4ae51262009-08-12 16:23:25 +00001527 if (match(D, m_SelectCst<0, -1>(m_Specific(Cond))))
Chris Lattnera6a474d2008-11-16 04:26:55 +00001528 return SelectInst::Create(Cond, C, B);
Dan Gohman4ae51262009-08-12 16:23:25 +00001529 if (match(D, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond)))))
Chris Lattnera6a474d2008-11-16 04:26:55 +00001530 return SelectInst::Create(Cond, C, B);
1531 // ((cond?-1:0)&C) | ((cond?0:-1)&D) -> cond ? C : D.
Dan Gohman4ae51262009-08-12 16:23:25 +00001532 if (match(B, m_SelectCst<0, -1>(m_Specific(Cond))))
Chris Lattnera6a474d2008-11-16 04:26:55 +00001533 return SelectInst::Create(Cond, C, D);
Dan Gohman4ae51262009-08-12 16:23:25 +00001534 if (match(B, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond)))))
Chris Lattnera6a474d2008-11-16 04:26:55 +00001535 return SelectInst::Create(Cond, C, D);
Chris Lattnerfaaf9512008-11-16 04:24:12 +00001536 return 0;
1537}
Chris Lattnerafe91a52006-06-15 19:07:26 +00001538
Chris Lattner69d4ced2008-11-16 05:20:07 +00001539/// FoldOrOfICmps - Fold (icmp)|(icmp) if possible.
1540Instruction *InstCombiner::FoldOrOfICmps(Instruction &I,
1541 ICmpInst *LHS, ICmpInst *RHS) {
Chris Lattnera317e042010-01-05 06:59:49 +00001542 ICmpInst::Predicate LHSCC = LHS->getPredicate(), RHSCC = RHS->getPredicate();
1543
1544 // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
1545 if (PredicatesFoldable(LHSCC, RHSCC)) {
1546 if (LHS->getOperand(0) == RHS->getOperand(1) &&
1547 LHS->getOperand(1) == RHS->getOperand(0))
1548 LHS->swapOperands();
1549 if (LHS->getOperand(0) == RHS->getOperand(0) &&
1550 LHS->getOperand(1) == RHS->getOperand(1)) {
1551 Value *Op0 = LHS->getOperand(0), *Op1 = LHS->getOperand(1);
1552 unsigned Code = getICmpCode(LHS) | getICmpCode(RHS);
1553 bool isSigned = LHS->isSigned() || RHS->isSigned();
1554 Value *RV = getICmpValue(isSigned, Code, Op0, Op1);
1555 if (Instruction *I = dyn_cast<Instruction>(RV))
1556 return I;
1557 // Otherwise, it's a constant boolean value.
1558 return ReplaceInstUsesWith(I, RV);
1559 }
1560 }
Chris Lattner69d4ced2008-11-16 05:20:07 +00001561
1562 // This only handles icmp of constants: (icmp1 A, C1) | (icmp2 B, C2).
Chris Lattnera317e042010-01-05 06:59:49 +00001563 Value *Val = LHS->getOperand(0), *Val2 = RHS->getOperand(0);
1564 ConstantInt *LHSCst = dyn_cast<ConstantInt>(LHS->getOperand(1));
1565 ConstantInt *RHSCst = dyn_cast<ConstantInt>(RHS->getOperand(1));
1566 if (LHSCst == 0 || RHSCst == 0) return 0;
Chris Lattner3f40e232009-11-29 00:51:17 +00001567
Chris Lattner3f40e232009-11-29 00:51:17 +00001568 // (icmp ne A, 0) | (icmp ne B, 0) --> (icmp ne (A|B), 0)
1569 if (LHSCst == RHSCst && LHSCC == RHSCC &&
1570 LHSCC == ICmpInst::ICMP_NE && LHSCst->isZero()) {
1571 Value *NewOr = Builder->CreateOr(Val, Val2);
1572 return new ICmpInst(LHSCC, NewOr, LHSCst);
1573 }
Chris Lattner69d4ced2008-11-16 05:20:07 +00001574
1575 // From here on, we only handle:
1576 // (icmp1 A, C1) | (icmp2 A, C2) --> something simpler.
1577 if (Val != Val2) return 0;
1578
1579 // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
1580 if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
1581 RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
1582 LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
1583 RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
1584 return 0;
1585
1586 // We can't fold (ugt x, C) | (sgt x, C2).
1587 if (!PredicatesFoldable(LHSCC, RHSCC))
1588 return 0;
1589
1590 // Ensure that the larger constant is on the RHS.
1591 bool ShouldSwap;
Nick Lewycky4a134af2009-10-25 05:20:17 +00001592 if (CmpInst::isSigned(LHSCC) ||
Chris Lattner69d4ced2008-11-16 05:20:07 +00001593 (ICmpInst::isEquality(LHSCC) &&
Nick Lewycky4a134af2009-10-25 05:20:17 +00001594 CmpInst::isSigned(RHSCC)))
Chris Lattner69d4ced2008-11-16 05:20:07 +00001595 ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
1596 else
1597 ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
1598
1599 if (ShouldSwap) {
1600 std::swap(LHS, RHS);
1601 std::swap(LHSCst, RHSCst);
1602 std::swap(LHSCC, RHSCC);
1603 }
1604
1605 // At this point, we know we have have two icmp instructions
1606 // comparing a value against two constants and or'ing the result
1607 // together. Because of the above check, we know that we only have
1608 // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
Chris Lattnera317e042010-01-05 06:59:49 +00001609 // icmp folding check above), that the two constants are not
Chris Lattner69d4ced2008-11-16 05:20:07 +00001610 // equal.
1611 assert(LHSCst != RHSCst && "Compares not folded above?");
1612
1613 switch (LHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00001614 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00001615 case ICmpInst::ICMP_EQ:
1616 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00001617 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00001618 case ICmpInst::ICMP_EQ:
Dan Gohman186a6362009-08-12 16:04:34 +00001619 if (LHSCst == SubOne(RHSCst)) {
Owen Andersond672ecb2009-07-03 00:17:18 +00001620 // (X == 13 | X == 14) -> X-13 <u 2
Owen Andersonbaf3c402009-07-29 18:55:55 +00001621 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
Chris Lattner74381062009-08-30 07:44:24 +00001622 Value *Add = Builder->CreateAdd(Val, AddCST, Val->getName()+".off");
Dan Gohman186a6362009-08-12 16:04:34 +00001623 AddCST = ConstantExpr::getSub(AddOne(RHSCst), LHSCst);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00001624 return new ICmpInst(ICmpInst::ICMP_ULT, Add, AddCST);
Chris Lattner69d4ced2008-11-16 05:20:07 +00001625 }
1626 break; // (X == 13 | X == 15) -> no change
1627 case ICmpInst::ICMP_UGT: // (X == 13 | X u> 14) -> no change
1628 case ICmpInst::ICMP_SGT: // (X == 13 | X s> 14) -> no change
1629 break;
1630 case ICmpInst::ICMP_NE: // (X == 13 | X != 15) -> X != 15
1631 case ICmpInst::ICMP_ULT: // (X == 13 | X u< 15) -> X u< 15
1632 case ICmpInst::ICMP_SLT: // (X == 13 | X s< 15) -> X s< 15
1633 return ReplaceInstUsesWith(I, RHS);
1634 }
1635 break;
1636 case ICmpInst::ICMP_NE:
1637 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00001638 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00001639 case ICmpInst::ICMP_EQ: // (X != 13 | X == 15) -> X != 13
1640 case ICmpInst::ICMP_UGT: // (X != 13 | X u> 15) -> X != 13
1641 case ICmpInst::ICMP_SGT: // (X != 13 | X s> 15) -> X != 13
1642 return ReplaceInstUsesWith(I, LHS);
1643 case ICmpInst::ICMP_NE: // (X != 13 | X != 15) -> true
1644 case ICmpInst::ICMP_ULT: // (X != 13 | X u< 15) -> true
1645 case ICmpInst::ICMP_SLT: // (X != 13 | X s< 15) -> true
Chris Lattner4de84762010-01-04 07:02:48 +00001646 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getContext()));
Chris Lattner69d4ced2008-11-16 05:20:07 +00001647 }
1648 break;
1649 case ICmpInst::ICMP_ULT:
1650 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00001651 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00001652 case ICmpInst::ICMP_EQ: // (X u< 13 | X == 14) -> no change
1653 break;
1654 case ICmpInst::ICMP_UGT: // (X u< 13 | X u> 15) -> (X-13) u> 2
1655 // If RHSCst is [us]MAXINT, it is always false. Not handling
1656 // this can cause overflow.
1657 if (RHSCst->isMaxValue(false))
1658 return ReplaceInstUsesWith(I, LHS);
Dan Gohman186a6362009-08-12 16:04:34 +00001659 return InsertRangeTest(Val, LHSCst, AddOne(RHSCst),
Owen Andersond672ecb2009-07-03 00:17:18 +00001660 false, false, I);
Chris Lattner69d4ced2008-11-16 05:20:07 +00001661 case ICmpInst::ICMP_SGT: // (X u< 13 | X s> 15) -> no change
1662 break;
1663 case ICmpInst::ICMP_NE: // (X u< 13 | X != 15) -> X != 15
1664 case ICmpInst::ICMP_ULT: // (X u< 13 | X u< 15) -> X u< 15
1665 return ReplaceInstUsesWith(I, RHS);
1666 case ICmpInst::ICMP_SLT: // (X u< 13 | X s< 15) -> no change
1667 break;
1668 }
1669 break;
1670 case ICmpInst::ICMP_SLT:
1671 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00001672 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00001673 case ICmpInst::ICMP_EQ: // (X s< 13 | X == 14) -> no change
1674 break;
1675 case ICmpInst::ICMP_SGT: // (X s< 13 | X s> 15) -> (X-13) s> 2
1676 // If RHSCst is [us]MAXINT, it is always false. Not handling
1677 // this can cause overflow.
1678 if (RHSCst->isMaxValue(true))
1679 return ReplaceInstUsesWith(I, LHS);
Dan Gohman186a6362009-08-12 16:04:34 +00001680 return InsertRangeTest(Val, LHSCst, AddOne(RHSCst),
Owen Andersond672ecb2009-07-03 00:17:18 +00001681 true, false, I);
Chris Lattner69d4ced2008-11-16 05:20:07 +00001682 case ICmpInst::ICMP_UGT: // (X s< 13 | X u> 15) -> no change
1683 break;
1684 case ICmpInst::ICMP_NE: // (X s< 13 | X != 15) -> X != 15
1685 case ICmpInst::ICMP_SLT: // (X s< 13 | X s< 15) -> X s< 15
1686 return ReplaceInstUsesWith(I, RHS);
1687 case ICmpInst::ICMP_ULT: // (X s< 13 | X u< 15) -> no change
1688 break;
1689 }
1690 break;
1691 case ICmpInst::ICMP_UGT:
1692 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00001693 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00001694 case ICmpInst::ICMP_EQ: // (X u> 13 | X == 15) -> X u> 13
1695 case ICmpInst::ICMP_UGT: // (X u> 13 | X u> 15) -> X u> 13
1696 return ReplaceInstUsesWith(I, LHS);
1697 case ICmpInst::ICMP_SGT: // (X u> 13 | X s> 15) -> no change
1698 break;
1699 case ICmpInst::ICMP_NE: // (X u> 13 | X != 15) -> true
1700 case ICmpInst::ICMP_ULT: // (X u> 13 | X u< 15) -> true
Chris Lattner4de84762010-01-04 07:02:48 +00001701 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getContext()));
Chris Lattner69d4ced2008-11-16 05:20:07 +00001702 case ICmpInst::ICMP_SLT: // (X u> 13 | X s< 15) -> no change
1703 break;
1704 }
1705 break;
1706 case ICmpInst::ICMP_SGT:
1707 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00001708 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00001709 case ICmpInst::ICMP_EQ: // (X s> 13 | X == 15) -> X > 13
1710 case ICmpInst::ICMP_SGT: // (X s> 13 | X s> 15) -> X > 13
1711 return ReplaceInstUsesWith(I, LHS);
1712 case ICmpInst::ICMP_UGT: // (X s> 13 | X u> 15) -> no change
1713 break;
1714 case ICmpInst::ICMP_NE: // (X s> 13 | X != 15) -> true
1715 case ICmpInst::ICMP_SLT: // (X s> 13 | X s< 15) -> true
Chris Lattner4de84762010-01-04 07:02:48 +00001716 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getContext()));
Chris Lattner69d4ced2008-11-16 05:20:07 +00001717 case ICmpInst::ICMP_ULT: // (X s> 13 | X u< 15) -> no change
1718 break;
1719 }
1720 break;
1721 }
1722 return 0;
1723}
1724
Chris Lattner5414cc52009-07-23 05:46:22 +00001725Instruction *InstCombiner::FoldOrOfFCmps(Instruction &I, FCmpInst *LHS,
1726 FCmpInst *RHS) {
1727 if (LHS->getPredicate() == FCmpInst::FCMP_UNO &&
1728 RHS->getPredicate() == FCmpInst::FCMP_UNO &&
1729 LHS->getOperand(0)->getType() == RHS->getOperand(0)->getType()) {
1730 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
1731 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
1732 // If either of the constants are nans, then the whole thing returns
1733 // true.
1734 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Chris Lattner4de84762010-01-04 07:02:48 +00001735 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getContext()));
Chris Lattner5414cc52009-07-23 05:46:22 +00001736
1737 // Otherwise, no need to compare the two constants, compare the
1738 // rest.
Dan Gohman1c8a23c2009-08-25 23:17:54 +00001739 return new FCmpInst(FCmpInst::FCMP_UNO,
Chris Lattner5414cc52009-07-23 05:46:22 +00001740 LHS->getOperand(0), RHS->getOperand(0));
1741 }
1742
1743 // Handle vector zeros. This occurs because the canonical form of
1744 // "fcmp uno x,x" is "fcmp uno x, 0".
1745 if (isa<ConstantAggregateZero>(LHS->getOperand(1)) &&
1746 isa<ConstantAggregateZero>(RHS->getOperand(1)))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00001747 return new FCmpInst(FCmpInst::FCMP_UNO,
Chris Lattner5414cc52009-07-23 05:46:22 +00001748 LHS->getOperand(0), RHS->getOperand(0));
1749
1750 return 0;
1751 }
1752
1753 Value *Op0LHS = LHS->getOperand(0), *Op0RHS = LHS->getOperand(1);
1754 Value *Op1LHS = RHS->getOperand(0), *Op1RHS = RHS->getOperand(1);
1755 FCmpInst::Predicate Op0CC = LHS->getPredicate(), Op1CC = RHS->getPredicate();
1756
1757 if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
1758 // Swap RHS operands to match LHS.
1759 Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
1760 std::swap(Op1LHS, Op1RHS);
1761 }
1762 if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
1763 // Simplify (fcmp cc0 x, y) | (fcmp cc1 x, y).
1764 if (Op0CC == Op1CC)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00001765 return new FCmpInst((FCmpInst::Predicate)Op0CC,
Chris Lattner5414cc52009-07-23 05:46:22 +00001766 Op0LHS, Op0RHS);
1767 if (Op0CC == FCmpInst::FCMP_TRUE || Op1CC == FCmpInst::FCMP_TRUE)
Chris Lattner4de84762010-01-04 07:02:48 +00001768 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getContext()));
Chris Lattner5414cc52009-07-23 05:46:22 +00001769 if (Op0CC == FCmpInst::FCMP_FALSE)
1770 return ReplaceInstUsesWith(I, RHS);
1771 if (Op1CC == FCmpInst::FCMP_FALSE)
1772 return ReplaceInstUsesWith(I, LHS);
1773 bool Op0Ordered;
1774 bool Op1Ordered;
1775 unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
1776 unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
1777 if (Op0Ordered == Op1Ordered) {
1778 // If both are ordered or unordered, return a new fcmp with
1779 // or'ed predicates.
Chris Lattner4de84762010-01-04 07:02:48 +00001780 Value *RV = getFCmpValue(Op0Ordered, Op0Pred|Op1Pred, Op0LHS, Op0RHS);
Chris Lattner5414cc52009-07-23 05:46:22 +00001781 if (Instruction *I = dyn_cast<Instruction>(RV))
1782 return I;
1783 // Otherwise, it's a constant boolean value...
1784 return ReplaceInstUsesWith(I, RV);
1785 }
1786 }
1787 return 0;
1788}
1789
Bill Wendlinga698a472008-12-01 08:23:25 +00001790/// FoldOrWithConstants - This helper function folds:
1791///
Bill Wendlinga8bb13f2008-12-02 05:09:00 +00001792/// ((A | B) & C1) | (B & C2)
Bill Wendlinga698a472008-12-01 08:23:25 +00001793///
1794/// into:
1795///
Bill Wendlinga8bb13f2008-12-02 05:09:00 +00001796/// (A & C1) | B
Bill Wendlingd54d8602008-12-01 08:32:40 +00001797///
Bill Wendlinga8bb13f2008-12-02 05:09:00 +00001798/// when the XOR of the two constants is "all ones" (-1).
Bill Wendlingd54d8602008-12-01 08:32:40 +00001799Instruction *InstCombiner::FoldOrWithConstants(BinaryOperator &I, Value *Op,
Bill Wendlinga698a472008-12-01 08:23:25 +00001800 Value *A, Value *B, Value *C) {
Bill Wendlingdda74e02008-12-02 05:06:43 +00001801 ConstantInt *CI1 = dyn_cast<ConstantInt>(C);
1802 if (!CI1) return 0;
Bill Wendlinga698a472008-12-01 08:23:25 +00001803
Bill Wendling286a0542008-12-02 06:24:20 +00001804 Value *V1 = 0;
1805 ConstantInt *CI2 = 0;
Dan Gohman4ae51262009-08-12 16:23:25 +00001806 if (!match(Op, m_And(m_Value(V1), m_ConstantInt(CI2)))) return 0;
Bill Wendlinga698a472008-12-01 08:23:25 +00001807
Bill Wendling29976b92008-12-02 06:18:11 +00001808 APInt Xor = CI1->getValue() ^ CI2->getValue();
1809 if (!Xor.isAllOnesValue()) return 0;
1810
Bill Wendling286a0542008-12-02 06:24:20 +00001811 if (V1 == A || V1 == B) {
Chris Lattner74381062009-08-30 07:44:24 +00001812 Value *NewOp = Builder->CreateAnd((V1 == A) ? B : A, CI1);
Bill Wendlingd16c6e92008-12-02 06:22:04 +00001813 return BinaryOperator::CreateOr(NewOp, V1);
Bill Wendlinga698a472008-12-01 08:23:25 +00001814 }
1815
1816 return 0;
1817}
1818
Chris Lattner7e708292002-06-25 16:13:24 +00001819Instruction *InstCombiner::visitOr(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00001820 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00001821 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00001822
Chris Lattnerd06094f2009-11-10 00:55:12 +00001823 if (Value *V = SimplifyOrInst(Op0, Op1, TD))
1824 return ReplaceInstUsesWith(I, V);
1825
1826
Chris Lattnerf8c36f52006-02-12 08:02:11 +00001827 // See if we can simplify any instructions used by the instruction whose sole
1828 // purpose is to compute bits we don't care about.
Dan Gohman6de29f82009-06-15 22:12:54 +00001829 if (SimplifyDemandedInstructionBits(I))
1830 return &I;
Chris Lattner041a6c92007-06-15 05:26:55 +00001831
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00001832 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner4f637d42006-01-06 17:59:59 +00001833 ConstantInt *C1 = 0; Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +00001834 // (X & C1) | C2 --> (X | C2) & (C1|C2)
Dan Gohman4ae51262009-08-12 16:23:25 +00001835 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) &&
Chris Lattner248a84b2010-01-05 07:04:23 +00001836 Op0->hasOneUse()) {
Chris Lattner74381062009-08-30 07:44:24 +00001837 Value *Or = Builder->CreateOr(X, RHS);
Chris Lattner6934a042007-02-11 01:23:03 +00001838 Or->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001839 return BinaryOperator::CreateAnd(Or,
Chris Lattner4de84762010-01-04 07:02:48 +00001840 ConstantInt::get(I.getContext(),
1841 RHS->getValue() | C1->getValue()));
Chris Lattneracd1f0f2004-07-30 07:50:03 +00001842 }
Chris Lattnerad44ebf2003-07-23 18:29:44 +00001843
Chris Lattneracd1f0f2004-07-30 07:50:03 +00001844 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
Dan Gohman4ae51262009-08-12 16:23:25 +00001845 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) &&
Chris Lattner248a84b2010-01-05 07:04:23 +00001846 Op0->hasOneUse()) {
Chris Lattner74381062009-08-30 07:44:24 +00001847 Value *Or = Builder->CreateOr(X, RHS);
Chris Lattner6934a042007-02-11 01:23:03 +00001848 Or->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001849 return BinaryOperator::CreateXor(Or,
Chris Lattner4de84762010-01-04 07:02:48 +00001850 ConstantInt::get(I.getContext(),
1851 C1->getValue() & ~RHS->getValue()));
Chris Lattnerad44ebf2003-07-23 18:29:44 +00001852 }
Chris Lattner2eefe512004-04-09 19:05:30 +00001853
1854 // Try to fold constant and into select arguments.
1855 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner80f43d32010-01-04 07:53:58 +00001856 if (Instruction *R = FoldOpIntoSelect(I, SI))
Chris Lattner2eefe512004-04-09 19:05:30 +00001857 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00001858 if (isa<PHINode>(Op0))
1859 if (Instruction *NV = FoldOpIntoPhi(I))
1860 return NV;
Chris Lattnerad44ebf2003-07-23 18:29:44 +00001861 }
1862
Chris Lattner4f637d42006-01-06 17:59:59 +00001863 Value *A = 0, *B = 0;
1864 ConstantInt *C1 = 0, *C2 = 0;
Chris Lattnerf4d4c872005-05-07 23:49:08 +00001865
Chris Lattner6423d4c2006-07-10 20:25:24 +00001866 // (A | B) | C and A | (B | C) -> bswap if possible.
1867 // (A >> B) | (C << D) and (A << B) | (B >> C) -> bswap if possible.
Dan Gohman4ae51262009-08-12 16:23:25 +00001868 if (match(Op0, m_Or(m_Value(), m_Value())) ||
1869 match(Op1, m_Or(m_Value(), m_Value())) ||
1870 (match(Op0, m_Shift(m_Value(), m_Value())) &&
1871 match(Op1, m_Shift(m_Value(), m_Value())))) {
Chris Lattnerafe91a52006-06-15 19:07:26 +00001872 if (Instruction *BSwap = MatchBSwap(I))
1873 return BSwap;
1874 }
1875
Chris Lattner6e4c6492005-05-09 04:58:36 +00001876 // (X^C)|Y -> (X|Y)^C iff Y&C == 0
Owen Andersonc7d2ce72009-07-10 17:35:01 +00001877 if (Op0->hasOneUse() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00001878 match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Reid Spencera03d45f2007-03-22 22:19:58 +00001879 MaskedValueIsZero(Op1, C1->getValue())) {
Chris Lattner74381062009-08-30 07:44:24 +00001880 Value *NOr = Builder->CreateOr(A, Op1);
Chris Lattner6934a042007-02-11 01:23:03 +00001881 NOr->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001882 return BinaryOperator::CreateXor(NOr, C1);
Chris Lattner6e4c6492005-05-09 04:58:36 +00001883 }
1884
1885 // Y|(X^C) -> (X|Y)^C iff Y&C == 0
Owen Andersonc7d2ce72009-07-10 17:35:01 +00001886 if (Op1->hasOneUse() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00001887 match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Reid Spencera03d45f2007-03-22 22:19:58 +00001888 MaskedValueIsZero(Op0, C1->getValue())) {
Chris Lattner74381062009-08-30 07:44:24 +00001889 Value *NOr = Builder->CreateOr(A, Op0);
Chris Lattner6934a042007-02-11 01:23:03 +00001890 NOr->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001891 return BinaryOperator::CreateXor(NOr, C1);
Chris Lattner6e4c6492005-05-09 04:58:36 +00001892 }
1893
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00001894 // (A & C)|(B & D)
Chris Lattner2384d7b2007-06-19 05:43:49 +00001895 Value *C = 0, *D = 0;
Dan Gohman4ae51262009-08-12 16:23:25 +00001896 if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
1897 match(Op1, m_And(m_Value(B), m_Value(D)))) {
Chris Lattner6cae0e02007-04-08 07:55:22 +00001898 Value *V1 = 0, *V2 = 0, *V3 = 0;
1899 C1 = dyn_cast<ConstantInt>(C);
1900 C2 = dyn_cast<ConstantInt>(D);
1901 if (C1 && C2) { // (A & C1)|(B & C2)
1902 // If we have: ((V + N) & C1) | (V & C2)
1903 // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
1904 // replace with V+N.
1905 if (C1->getValue() == ~C2->getValue()) {
1906 if ((C2->getValue() & (C2->getValue()+1)) == 0 && // C2 == 0+1+
Dan Gohman4ae51262009-08-12 16:23:25 +00001907 match(A, m_Add(m_Value(V1), m_Value(V2)))) {
Chris Lattner6cae0e02007-04-08 07:55:22 +00001908 // Add commutes, try both ways.
1909 if (V1 == B && MaskedValueIsZero(V2, C2->getValue()))
1910 return ReplaceInstUsesWith(I, A);
1911 if (V2 == B && MaskedValueIsZero(V1, C2->getValue()))
1912 return ReplaceInstUsesWith(I, A);
1913 }
1914 // Or commutes, try both ways.
1915 if ((C1->getValue() & (C1->getValue()+1)) == 0 &&
Dan Gohman4ae51262009-08-12 16:23:25 +00001916 match(B, m_Add(m_Value(V1), m_Value(V2)))) {
Chris Lattner6cae0e02007-04-08 07:55:22 +00001917 // Add commutes, try both ways.
1918 if (V1 == A && MaskedValueIsZero(V2, C1->getValue()))
1919 return ReplaceInstUsesWith(I, B);
1920 if (V2 == A && MaskedValueIsZero(V1, C1->getValue()))
1921 return ReplaceInstUsesWith(I, B);
1922 }
1923 }
Chris Lattnere4412c12010-01-04 06:03:59 +00001924
1925 // ((V | N) & C1) | (V & C2) --> (V|N) & (C1|C2)
1926 // iff (C1&C2) == 0 and (N&~C1) == 0
1927 if ((C1->getValue() & C2->getValue()) == 0) {
1928 if (match(A, m_Or(m_Value(V1), m_Value(V2))) &&
1929 ((V1 == B && MaskedValueIsZero(V2, ~C1->getValue())) || // (V|N)
1930 (V2 == B && MaskedValueIsZero(V1, ~C1->getValue())))) // (N|V)
1931 return BinaryOperator::CreateAnd(A,
1932 ConstantInt::get(A->getContext(),
1933 C1->getValue()|C2->getValue()));
1934 // Or commutes, try both ways.
1935 if (match(B, m_Or(m_Value(V1), m_Value(V2))) &&
1936 ((V1 == A && MaskedValueIsZero(V2, ~C2->getValue())) || // (V|N)
1937 (V2 == A && MaskedValueIsZero(V1, ~C2->getValue())))) // (N|V)
1938 return BinaryOperator::CreateAnd(B,
1939 ConstantInt::get(B->getContext(),
1940 C1->getValue()|C2->getValue()));
1941 }
Chris Lattner6cae0e02007-04-08 07:55:22 +00001942 }
1943
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00001944 // Check to see if we have any common things being and'ed. If so, find the
1945 // terms for V1 & (V2|V3).
Chris Lattner248a84b2010-01-05 07:04:23 +00001946 if (Op0->hasOneUse() || Op1->hasOneUse()) {
Chris Lattnere4412c12010-01-04 06:03:59 +00001947 V1 = 0;
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00001948 if (A == B) // (A & C)|(A & D) == A & (C|D)
1949 V1 = A, V2 = C, V3 = D;
1950 else if (A == D) // (A & C)|(B & A) == A & (B|C)
1951 V1 = A, V2 = B, V3 = C;
1952 else if (C == B) // (A & C)|(C & D) == C & (A|D)
1953 V1 = C, V2 = A, V3 = D;
1954 else if (C == D) // (A & C)|(B & C) == C & (A|B)
1955 V1 = C, V2 = A, V3 = B;
1956
1957 if (V1) {
Chris Lattner74381062009-08-30 07:44:24 +00001958 Value *Or = Builder->CreateOr(V2, V3, "tmp");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001959 return BinaryOperator::CreateAnd(V1, Or);
Chris Lattner0b7c0bf2005-09-18 06:02:59 +00001960 }
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00001961 }
Dan Gohmanb493b272008-10-28 22:38:57 +00001962
Dan Gohman1975d032008-10-30 20:40:10 +00001963 // (A & (C0?-1:0)) | (B & ~(C0?-1:0)) -> C0 ? A : B, and commuted variants
Chris Lattner4de84762010-01-04 07:02:48 +00001964 if (Instruction *Match = MatchSelectFromAndOr(A, B, C, D))
Chris Lattnerfaaf9512008-11-16 04:24:12 +00001965 return Match;
Chris Lattner4de84762010-01-04 07:02:48 +00001966 if (Instruction *Match = MatchSelectFromAndOr(B, A, D, C))
Chris Lattnerfaaf9512008-11-16 04:24:12 +00001967 return Match;
Chris Lattner4de84762010-01-04 07:02:48 +00001968 if (Instruction *Match = MatchSelectFromAndOr(C, B, A, D))
Chris Lattnerfaaf9512008-11-16 04:24:12 +00001969 return Match;
Chris Lattner4de84762010-01-04 07:02:48 +00001970 if (Instruction *Match = MatchSelectFromAndOr(D, A, B, C))
Chris Lattnerfaaf9512008-11-16 04:24:12 +00001971 return Match;
Bill Wendlingb01865c2008-11-30 13:52:49 +00001972
Bill Wendlingb01865c2008-11-30 13:52:49 +00001973 // ((A&~B)|(~A&B)) -> A^B
Dan Gohman4ae51262009-08-12 16:23:25 +00001974 if ((match(C, m_Not(m_Specific(D))) &&
1975 match(B, m_Not(m_Specific(A)))))
Bill Wendling03aae5f2008-12-01 08:09:47 +00001976 return BinaryOperator::CreateXor(A, D);
Bill Wendlingb01865c2008-11-30 13:52:49 +00001977 // ((~B&A)|(~A&B)) -> A^B
Dan Gohman4ae51262009-08-12 16:23:25 +00001978 if ((match(A, m_Not(m_Specific(D))) &&
1979 match(B, m_Not(m_Specific(C)))))
Bill Wendling03aae5f2008-12-01 08:09:47 +00001980 return BinaryOperator::CreateXor(C, D);
Bill Wendlingb01865c2008-11-30 13:52:49 +00001981 // ((A&~B)|(B&~A)) -> A^B
Dan Gohman4ae51262009-08-12 16:23:25 +00001982 if ((match(C, m_Not(m_Specific(B))) &&
1983 match(D, m_Not(m_Specific(A)))))
Bill Wendling03aae5f2008-12-01 08:09:47 +00001984 return BinaryOperator::CreateXor(A, B);
Bill Wendlingb01865c2008-11-30 13:52:49 +00001985 // ((~B&A)|(B&~A)) -> A^B
Dan Gohman4ae51262009-08-12 16:23:25 +00001986 if ((match(A, m_Not(m_Specific(B))) &&
1987 match(D, m_Not(m_Specific(C)))))
Bill Wendling03aae5f2008-12-01 08:09:47 +00001988 return BinaryOperator::CreateXor(C, B);
Chris Lattnere9bed7d2005-09-18 03:42:07 +00001989 }
Chris Lattnere511b742006-11-14 07:46:50 +00001990
1991 // (X >> Z) | (Y >> Z) -> (X|Y) >> Z for all shifts.
Reid Spencer832254e2007-02-02 02:16:23 +00001992 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
1993 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
1994 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
Chris Lattnere511b742006-11-14 07:46:50 +00001995 SI0->getOperand(1) == SI1->getOperand(1) &&
1996 (SI0->hasOneUse() || SI1->hasOneUse())) {
Chris Lattner74381062009-08-30 07:44:24 +00001997 Value *NewOp = Builder->CreateOr(SI0->getOperand(0), SI1->getOperand(0),
1998 SI0->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001999 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
Reid Spencer832254e2007-02-02 02:16:23 +00002000 SI1->getOperand(1));
Chris Lattnere511b742006-11-14 07:46:50 +00002001 }
2002 }
Chris Lattner67ca7682003-08-12 19:11:07 +00002003
Bill Wendlingb3833d12008-12-01 01:07:11 +00002004 // ((A|B)&1)|(B&-2) -> (A&1) | B
Dan Gohman4ae51262009-08-12 16:23:25 +00002005 if (match(Op0, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C))) ||
2006 match(Op0, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))))) {
Bill Wendlingd54d8602008-12-01 08:32:40 +00002007 Instruction *Ret = FoldOrWithConstants(I, Op1, A, B, C);
Bill Wendlinga698a472008-12-01 08:23:25 +00002008 if (Ret) return Ret;
Bill Wendlingb3833d12008-12-01 01:07:11 +00002009 }
2010 // (B&-2)|((A|B)&1) -> (A&1) | B
Dan Gohman4ae51262009-08-12 16:23:25 +00002011 if (match(Op1, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C))) ||
2012 match(Op1, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))))) {
Bill Wendlingd54d8602008-12-01 08:32:40 +00002013 Instruction *Ret = FoldOrWithConstants(I, Op0, A, B, C);
Bill Wendlinga698a472008-12-01 08:23:25 +00002014 if (Ret) return Ret;
Bill Wendlingb3833d12008-12-01 01:07:11 +00002015 }
2016
Chris Lattnerd06094f2009-11-10 00:55:12 +00002017 // (~A | ~B) == (~(A & B)) - De Morgan's Law
2018 if (Value *Op0NotVal = dyn_castNotVal(Op0))
2019 if (Value *Op1NotVal = dyn_castNotVal(Op1))
2020 if (Op0->hasOneUse() && Op1->hasOneUse()) {
2021 Value *And = Builder->CreateAnd(Op0NotVal, Op1NotVal,
2022 I.getName()+".demorgan");
2023 return BinaryOperator::CreateNot(And);
2024 }
Chris Lattnera2881962003-02-18 19:28:33 +00002025
Chris Lattnera317e042010-01-05 06:59:49 +00002026 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
Chris Lattner69d4ced2008-11-16 05:20:07 +00002027 if (ICmpInst *LHS = dyn_cast<ICmpInst>(I.getOperand(0)))
2028 if (Instruction *Res = FoldOrOfICmps(I, LHS, RHS))
2029 return Res;
Chris Lattner6fc205f2006-05-05 06:39:07 +00002030
2031 // fold (or (cast A), (cast B)) -> (cast (or A, B))
Chris Lattner99c65742007-10-24 05:38:08 +00002032 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Chris Lattner6fc205f2006-05-05 06:39:07 +00002033 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00002034 if (Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
Evan Chengb98a10e2008-03-24 00:21:34 +00002035 if (!isa<ICmpInst>(Op0C->getOperand(0)) ||
2036 !isa<ICmpInst>(Op1C->getOperand(0))) {
2037 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattnerf98d2532009-07-23 05:32:17 +00002038 if (SrcTy == Op1C->getOperand(0)->getType() &&
2039 SrcTy->isIntOrIntVector() &&
Evan Chengb98a10e2008-03-24 00:21:34 +00002040 // Only do this if the casts both really cause code to be
2041 // generated.
2042 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
Chris Lattner80f43d32010-01-04 07:53:58 +00002043 I.getType()) &&
Evan Chengb98a10e2008-03-24 00:21:34 +00002044 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
Chris Lattner80f43d32010-01-04 07:53:58 +00002045 I.getType())) {
Chris Lattner74381062009-08-30 07:44:24 +00002046 Value *NewOp = Builder->CreateOr(Op0C->getOperand(0),
2047 Op1C->getOperand(0), I.getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002048 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Evan Chengb98a10e2008-03-24 00:21:34 +00002049 }
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00002050 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00002051 }
Chris Lattner99c65742007-10-24 05:38:08 +00002052 }
2053
2054
2055 // (fcmp uno x, c) | (fcmp uno y, c) -> (fcmp uno x, y)
2056 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
Chris Lattner5414cc52009-07-23 05:46:22 +00002057 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
2058 if (Instruction *Res = FoldOrOfFCmps(I, LHS, RHS))
2059 return Res;
Chris Lattner99c65742007-10-24 05:38:08 +00002060 }
Chris Lattnere9bed7d2005-09-18 03:42:07 +00002061
Chris Lattner7e708292002-06-25 16:13:24 +00002062 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00002063}
2064
Chris Lattner7e708292002-06-25 16:13:24 +00002065Instruction *InstCombiner::visitXor(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00002066 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00002067 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00002068
Evan Chengd34af782008-03-25 20:07:13 +00002069 if (isa<UndefValue>(Op1)) {
2070 if (isa<UndefValue>(Op0))
2071 // Handle undef ^ undef -> 0 special case. This is a common
2072 // idiom (misuse).
Owen Andersona7235ea2009-07-31 20:28:14 +00002073 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00002074 return ReplaceInstUsesWith(I, Op1); // X ^ undef -> undef
Evan Chengd34af782008-03-25 20:07:13 +00002075 }
Chris Lattnere87597f2004-10-16 18:11:37 +00002076
Chris Lattnerdea34da2010-01-05 07:01:16 +00002077 // xor X, X = 0
2078 if (Op0 == Op1)
Owen Andersona7235ea2009-07-31 20:28:14 +00002079 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerf8c36f52006-02-12 08:02:11 +00002080
2081 // See if we can simplify any instructions used by the instruction whose sole
2082 // purpose is to compute bits we don't care about.
Dan Gohman6de29f82009-06-15 22:12:54 +00002083 if (SimplifyDemandedInstructionBits(I))
2084 return &I;
2085 if (isa<VectorType>(I.getType()))
2086 if (isa<ConstantAggregateZero>(Op1))
2087 return ReplaceInstUsesWith(I, Op0); // X ^ <0,0> -> X
Chris Lattner3f5b8772002-05-06 16:14:14 +00002088
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00002089 // Is this a ~ operation?
Dan Gohman186a6362009-08-12 16:04:34 +00002090 if (Value *NotOp = dyn_castNotVal(&I)) {
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00002091 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(NotOp)) {
2092 if (Op0I->getOpcode() == Instruction::And ||
2093 Op0I->getOpcode() == Instruction::Or) {
Chris Lattner48b59ec2009-10-26 15:40:07 +00002094 // ~(~X & Y) --> (X | ~Y) - De Morgan's Law
2095 // ~(~X | Y) === (X & ~Y) - De Morgan's Law
2096 if (dyn_castNotVal(Op0I->getOperand(1)))
2097 Op0I->swapOperands();
Dan Gohman186a6362009-08-12 16:04:34 +00002098 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
Chris Lattner74381062009-08-30 07:44:24 +00002099 Value *NotY =
2100 Builder->CreateNot(Op0I->getOperand(1),
2101 Op0I->getOperand(1)->getName()+".not");
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00002102 if (Op0I->getOpcode() == Instruction::And)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002103 return BinaryOperator::CreateOr(Op0NotVal, NotY);
Chris Lattner74381062009-08-30 07:44:24 +00002104 return BinaryOperator::CreateAnd(Op0NotVal, NotY);
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00002105 }
Chris Lattner48b59ec2009-10-26 15:40:07 +00002106
2107 // ~(X & Y) --> (~X | ~Y) - De Morgan's Law
2108 // ~(X | Y) === (~X & ~Y) - De Morgan's Law
2109 if (isFreeToInvert(Op0I->getOperand(0)) &&
2110 isFreeToInvert(Op0I->getOperand(1))) {
2111 Value *NotX =
2112 Builder->CreateNot(Op0I->getOperand(0), "notlhs");
2113 Value *NotY =
2114 Builder->CreateNot(Op0I->getOperand(1), "notrhs");
2115 if (Op0I->getOpcode() == Instruction::And)
2116 return BinaryOperator::CreateOr(NotX, NotY);
2117 return BinaryOperator::CreateAnd(NotX, NotY);
2118 }
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00002119 }
2120 }
2121 }
2122
2123
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002124 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner7acdf1d2009-10-11 22:00:32 +00002125 if (RHS->isOne() && Op0->hasOneUse()) {
Bill Wendling3479be92009-01-01 01:18:23 +00002126 // xor (cmp A, B), true = not (cmp A, B) = !cmp A, B
Nick Lewyckyf947b3e2007-08-06 20:04:16 +00002127 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Op0))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00002128 return new ICmpInst(ICI->getInversePredicate(),
Reid Spencere4d87aa2006-12-23 06:05:41 +00002129 ICI->getOperand(0), ICI->getOperand(1));
Chris Lattnerad5b4fb2003-11-04 23:50:51 +00002130
Nick Lewyckyf947b3e2007-08-06 20:04:16 +00002131 if (FCmpInst *FCI = dyn_cast<FCmpInst>(Op0))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00002132 return new FCmpInst(FCI->getInversePredicate(),
Nick Lewyckyf947b3e2007-08-06 20:04:16 +00002133 FCI->getOperand(0), FCI->getOperand(1));
2134 }
2135
Nick Lewycky517e1f52008-05-31 19:01:33 +00002136 // fold (xor(zext(cmp)), 1) and (xor(sext(cmp)), -1) to ext(!cmp).
2137 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
2138 if (CmpInst *CI = dyn_cast<CmpInst>(Op0C->getOperand(0))) {
2139 if (CI->hasOneUse() && Op0C->hasOneUse()) {
2140 Instruction::CastOps Opcode = Op0C->getOpcode();
Chris Lattner74381062009-08-30 07:44:24 +00002141 if ((Opcode == Instruction::ZExt || Opcode == Instruction::SExt) &&
2142 (RHS == ConstantExpr::getCast(Opcode,
Chris Lattner4de84762010-01-04 07:02:48 +00002143 ConstantInt::getTrue(I.getContext()),
Chris Lattner74381062009-08-30 07:44:24 +00002144 Op0C->getDestTy()))) {
2145 CI->setPredicate(CI->getInversePredicate());
2146 return CastInst::Create(Opcode, CI, Op0C->getType());
Nick Lewycky517e1f52008-05-31 19:01:33 +00002147 }
2148 }
2149 }
2150 }
2151
Reid Spencere4d87aa2006-12-23 06:05:41 +00002152 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Chris Lattnerd65460f2003-11-05 01:06:05 +00002153 // ~(c-X) == X-c-1 == X+(-c-1)
Chris Lattner7c4049c2004-01-12 19:35:11 +00002154 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
2155 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00002156 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
2157 Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
Owen Andersoneed707b2009-07-24 23:12:02 +00002158 ConstantInt::get(I.getType(), 1));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002159 return BinaryOperator::CreateAdd(Op0I->getOperand(1), ConstantRHS);
Chris Lattner7c4049c2004-01-12 19:35:11 +00002160 }
Chris Lattner5c6e2db2007-04-02 05:36:22 +00002161
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00002162 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
Chris Lattnerf8c36f52006-02-12 08:02:11 +00002163 if (Op0I->getOpcode() == Instruction::Add) {
Chris Lattner689d24b2003-11-04 23:37:10 +00002164 // ~(X-c) --> (-c-1)-X
Chris Lattner7c4049c2004-01-12 19:35:11 +00002165 if (RHS->isAllOnesValue()) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00002166 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002167 return BinaryOperator::CreateSub(
Owen Andersonbaf3c402009-07-29 18:55:55 +00002168 ConstantExpr::getSub(NegOp0CI,
Owen Andersoneed707b2009-07-24 23:12:02 +00002169 ConstantInt::get(I.getType(), 1)),
Owen Andersond672ecb2009-07-03 00:17:18 +00002170 Op0I->getOperand(0));
Chris Lattneracf4e072007-04-02 05:42:22 +00002171 } else if (RHS->getValue().isSignBit()) {
Chris Lattner5c6e2db2007-04-02 05:36:22 +00002172 // (X + C) ^ signbit -> (X + C + signbit)
Chris Lattner4de84762010-01-04 07:02:48 +00002173 Constant *C = ConstantInt::get(I.getContext(),
Owen Andersoneed707b2009-07-24 23:12:02 +00002174 RHS->getValue() + Op0CI->getValue());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002175 return BinaryOperator::CreateAdd(Op0I->getOperand(0), C);
Chris Lattnercd1d6d52007-04-02 05:48:58 +00002176
Chris Lattner7c4049c2004-01-12 19:35:11 +00002177 }
Chris Lattner02bd1b32006-02-26 19:57:54 +00002178 } else if (Op0I->getOpcode() == Instruction::Or) {
2179 // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
Reid Spencera03d45f2007-03-22 22:19:58 +00002180 if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue())) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00002181 Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
Chris Lattner02bd1b32006-02-26 19:57:54 +00002182 // Anything in both C1 and C2 is known to be zero, remove it from
2183 // NewRHS.
Owen Andersonbaf3c402009-07-29 18:55:55 +00002184 Constant *CommonBits = ConstantExpr::getAnd(Op0CI, RHS);
2185 NewRHS = ConstantExpr::getAnd(NewRHS,
2186 ConstantExpr::getNot(CommonBits));
Chris Lattner7a1e9242009-08-30 06:13:40 +00002187 Worklist.Add(Op0I);
Chris Lattner02bd1b32006-02-26 19:57:54 +00002188 I.setOperand(0, Op0I->getOperand(0));
2189 I.setOperand(1, NewRHS);
2190 return &I;
2191 }
Chris Lattnereca0c5c2003-07-23 21:37:07 +00002192 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00002193 }
Chris Lattner05bd1b22002-08-20 18:24:26 +00002194 }
Chris Lattner2eefe512004-04-09 19:05:30 +00002195
2196 // Try to fold constant and into select arguments.
2197 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner80f43d32010-01-04 07:53:58 +00002198 if (Instruction *R = FoldOpIntoSelect(I, SI))
Chris Lattner2eefe512004-04-09 19:05:30 +00002199 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00002200 if (isa<PHINode>(Op0))
2201 if (Instruction *NV = FoldOpIntoPhi(I))
2202 return NV;
Chris Lattner3f5b8772002-05-06 16:14:14 +00002203 }
2204
Dan Gohman186a6362009-08-12 16:04:34 +00002205 if (Value *X = dyn_castNotVal(Op0)) // ~A ^ A == -1
Chris Lattnera2881962003-02-18 19:28:33 +00002206 if (X == Op1)
Owen Andersona7235ea2009-07-31 20:28:14 +00002207 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00002208
Dan Gohman186a6362009-08-12 16:04:34 +00002209 if (Value *X = dyn_castNotVal(Op1)) // A ^ ~A == -1
Chris Lattnera2881962003-02-18 19:28:33 +00002210 if (X == Op0)
Owen Andersona7235ea2009-07-31 20:28:14 +00002211 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00002212
Chris Lattner318bf792007-03-18 22:51:34 +00002213
2214 BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1);
2215 if (Op1I) {
2216 Value *A, *B;
Dan Gohman4ae51262009-08-12 16:23:25 +00002217 if (match(Op1I, m_Or(m_Value(A), m_Value(B)))) {
Chris Lattner318bf792007-03-18 22:51:34 +00002218 if (A == Op0) { // B^(B|A) == (A|B)^B
Chris Lattner64daab52006-04-01 08:03:55 +00002219 Op1I->swapOperands();
Chris Lattnercb40a372003-03-10 18:24:17 +00002220 I.swapOperands();
2221 std::swap(Op0, Op1);
Chris Lattner318bf792007-03-18 22:51:34 +00002222 } else if (B == Op0) { // B^(A|B) == (A|B)^B
Chris Lattner64daab52006-04-01 08:03:55 +00002223 I.swapOperands(); // Simplified below.
Chris Lattnercb40a372003-03-10 18:24:17 +00002224 std::swap(Op0, Op1);
Misha Brukmanfd939082005-04-21 23:48:37 +00002225 }
Dan Gohman4ae51262009-08-12 16:23:25 +00002226 } else if (match(Op1I, m_Xor(m_Specific(Op0), m_Value(B)))) {
Chris Lattnercb504b92008-11-16 05:38:51 +00002227 return ReplaceInstUsesWith(I, B); // A^(A^B) == B
Dan Gohman4ae51262009-08-12 16:23:25 +00002228 } else if (match(Op1I, m_Xor(m_Value(A), m_Specific(Op0)))) {
Chris Lattnercb504b92008-11-16 05:38:51 +00002229 return ReplaceInstUsesWith(I, A); // A^(B^A) == B
Dan Gohman4ae51262009-08-12 16:23:25 +00002230 } else if (match(Op1I, m_And(m_Value(A), m_Value(B))) &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00002231 Op1I->hasOneUse()){
Chris Lattner6abbdf92007-04-01 05:36:37 +00002232 if (A == Op0) { // A^(A&B) -> A^(B&A)
Chris Lattner64daab52006-04-01 08:03:55 +00002233 Op1I->swapOperands();
Chris Lattner6abbdf92007-04-01 05:36:37 +00002234 std::swap(A, B);
2235 }
Chris Lattner318bf792007-03-18 22:51:34 +00002236 if (B == Op0) { // A^(B&A) -> (B&A)^A
Chris Lattner64daab52006-04-01 08:03:55 +00002237 I.swapOperands(); // Simplified below.
2238 std::swap(Op0, Op1);
2239 }
Chris Lattner26ca7e12004-02-16 03:54:20 +00002240 }
Chris Lattner318bf792007-03-18 22:51:34 +00002241 }
2242
2243 BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0);
2244 if (Op0I) {
2245 Value *A, *B;
Dan Gohman4ae51262009-08-12 16:23:25 +00002246 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00002247 Op0I->hasOneUse()) {
Chris Lattner318bf792007-03-18 22:51:34 +00002248 if (A == Op1) // (B|A)^B == (A|B)^B
2249 std::swap(A, B);
Chris Lattner74381062009-08-30 07:44:24 +00002250 if (B == Op1) // (A|B)^B == A & ~B
2251 return BinaryOperator::CreateAnd(A, Builder->CreateNot(Op1, "tmp"));
Dan Gohman4ae51262009-08-12 16:23:25 +00002252 } else if (match(Op0I, m_Xor(m_Specific(Op1), m_Value(B)))) {
Chris Lattnercb504b92008-11-16 05:38:51 +00002253 return ReplaceInstUsesWith(I, B); // (A^B)^A == B
Dan Gohman4ae51262009-08-12 16:23:25 +00002254 } else if (match(Op0I, m_Xor(m_Value(A), m_Specific(Op1)))) {
Chris Lattnercb504b92008-11-16 05:38:51 +00002255 return ReplaceInstUsesWith(I, A); // (B^A)^A == B
Dan Gohman4ae51262009-08-12 16:23:25 +00002256 } else if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00002257 Op0I->hasOneUse()){
Chris Lattner318bf792007-03-18 22:51:34 +00002258 if (A == Op1) // (A&B)^A -> (B&A)^A
2259 std::swap(A, B);
2260 if (B == Op1 && // (B&A)^A == ~B & A
Chris Lattnerae1ab392006-04-01 22:05:01 +00002261 !isa<ConstantInt>(Op1)) { // Canonical form is (B&C)^C
Chris Lattner74381062009-08-30 07:44:24 +00002262 return BinaryOperator::CreateAnd(Builder->CreateNot(A, "tmp"), Op1);
Chris Lattner64daab52006-04-01 08:03:55 +00002263 }
Chris Lattnercb40a372003-03-10 18:24:17 +00002264 }
Chris Lattner318bf792007-03-18 22:51:34 +00002265 }
2266
2267 // (X >> Z) ^ (Y >> Z) -> (X^Y) >> Z for all shifts.
2268 if (Op0I && Op1I && Op0I->isShift() &&
2269 Op0I->getOpcode() == Op1I->getOpcode() &&
2270 Op0I->getOperand(1) == Op1I->getOperand(1) &&
2271 (Op1I->hasOneUse() || Op1I->hasOneUse())) {
Chris Lattner74381062009-08-30 07:44:24 +00002272 Value *NewOp =
2273 Builder->CreateXor(Op0I->getOperand(0), Op1I->getOperand(0),
2274 Op0I->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002275 return BinaryOperator::Create(Op1I->getOpcode(), NewOp,
Chris Lattner318bf792007-03-18 22:51:34 +00002276 Op1I->getOperand(1));
2277 }
2278
2279 if (Op0I && Op1I) {
2280 Value *A, *B, *C, *D;
2281 // (A & B)^(A | B) -> A ^ B
Dan Gohman4ae51262009-08-12 16:23:25 +00002282 if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
2283 match(Op1I, m_Or(m_Value(C), m_Value(D)))) {
Chris Lattner318bf792007-03-18 22:51:34 +00002284 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002285 return BinaryOperator::CreateXor(A, B);
Chris Lattner318bf792007-03-18 22:51:34 +00002286 }
2287 // (A | B)^(A & B) -> A ^ B
Dan Gohman4ae51262009-08-12 16:23:25 +00002288 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
2289 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
Chris Lattner318bf792007-03-18 22:51:34 +00002290 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002291 return BinaryOperator::CreateXor(A, B);
Chris Lattner318bf792007-03-18 22:51:34 +00002292 }
2293
2294 // (A & B)^(C & D)
2295 if ((Op0I->hasOneUse() || Op1I->hasOneUse()) &&
Dan Gohman4ae51262009-08-12 16:23:25 +00002296 match(Op0I, m_And(m_Value(A), m_Value(B))) &&
2297 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
Chris Lattner318bf792007-03-18 22:51:34 +00002298 // (X & Y)^(X & Y) -> (Y^Z) & X
2299 Value *X = 0, *Y = 0, *Z = 0;
2300 if (A == C)
2301 X = A, Y = B, Z = D;
2302 else if (A == D)
2303 X = A, Y = B, Z = C;
2304 else if (B == C)
2305 X = B, Y = A, Z = D;
2306 else if (B == D)
2307 X = B, Y = A, Z = C;
2308
2309 if (X) {
Chris Lattner74381062009-08-30 07:44:24 +00002310 Value *NewOp = Builder->CreateXor(Y, Z, Op0->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002311 return BinaryOperator::CreateAnd(NewOp, X);
Chris Lattner318bf792007-03-18 22:51:34 +00002312 }
2313 }
2314 }
2315
Reid Spencere4d87aa2006-12-23 06:05:41 +00002316 // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
2317 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
Chris Lattnera317e042010-01-05 06:59:49 +00002318 if (ICmpInst *LHS = dyn_cast<ICmpInst>(I.getOperand(0)))
2319 if (PredicatesFoldable(LHS->getPredicate(), RHS->getPredicate())) {
2320 if (LHS->getOperand(0) == RHS->getOperand(1) &&
2321 LHS->getOperand(1) == RHS->getOperand(0))
2322 LHS->swapOperands();
2323 if (LHS->getOperand(0) == RHS->getOperand(0) &&
2324 LHS->getOperand(1) == RHS->getOperand(1)) {
2325 Value *Op0 = LHS->getOperand(0), *Op1 = LHS->getOperand(1);
2326 unsigned Code = getICmpCode(LHS) ^ getICmpCode(RHS);
2327 bool isSigned = LHS->isSigned() || RHS->isSigned();
2328 Value *RV = getICmpValue(isSigned, Code, Op0, Op1);
2329 if (Instruction *I = dyn_cast<Instruction>(RV))
2330 return I;
2331 // Otherwise, it's a constant boolean value.
2332 return ReplaceInstUsesWith(I, RV);
2333 }
2334 }
Chris Lattneraa9c1f12003-08-13 20:16:26 +00002335
Chris Lattner6fc205f2006-05-05 06:39:07 +00002336 // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
Chris Lattner99c65742007-10-24 05:38:08 +00002337 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Chris Lattner6fc205f2006-05-05 06:39:07 +00002338 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00002339 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
2340 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner42a75512007-01-15 02:27:26 +00002341 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00002342 // Only do this if the casts both really cause code to be generated.
Reid Spencere4d87aa2006-12-23 06:05:41 +00002343 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
Chris Lattner80f43d32010-01-04 07:53:58 +00002344 I.getType()) &&
Reid Spencere4d87aa2006-12-23 06:05:41 +00002345 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
Chris Lattner80f43d32010-01-04 07:53:58 +00002346 I.getType())) {
Chris Lattner74381062009-08-30 07:44:24 +00002347 Value *NewOp = Builder->CreateXor(Op0C->getOperand(0),
2348 Op1C->getOperand(0), I.getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002349 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00002350 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00002351 }
Chris Lattner99c65742007-10-24 05:38:08 +00002352 }
Nick Lewycky517e1f52008-05-31 19:01:33 +00002353
Chris Lattner7e708292002-06-25 16:13:24 +00002354 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00002355}
2356
Chris Lattner3f5b8772002-05-06 16:14:14 +00002357
Reid Spencer832254e2007-02-02 02:16:23 +00002358Instruction *InstCombiner::visitShl(BinaryOperator &I) {
2359 return commonShiftTransforms(I);
2360}
2361
2362Instruction *InstCombiner::visitLShr(BinaryOperator &I) {
2363 return commonShiftTransforms(I);
2364}
2365
2366Instruction *InstCombiner::visitAShr(BinaryOperator &I) {
Chris Lattner348f6652007-12-06 01:59:46 +00002367 if (Instruction *R = commonShiftTransforms(I))
2368 return R;
2369
2370 Value *Op0 = I.getOperand(0);
2371
2372 // ashr int -1, X = -1 (for any arithmetic shift rights of ~0)
2373 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
2374 if (CSI->isAllOnesValue())
2375 return ReplaceInstUsesWith(I, CSI);
Dan Gohman0001e562009-02-24 02:00:40 +00002376
Dan Gohmanc6ac3222009-06-16 19:55:29 +00002377 // See if we can turn a signed shr into an unsigned shr.
2378 if (MaskedValueIsZero(Op0,
2379 APInt::getSignBit(I.getType()->getScalarSizeInBits())))
2380 return BinaryOperator::CreateLShr(Op0, I.getOperand(1));
2381
2382 // Arithmetic shifting an all-sign-bit value is a no-op.
2383 unsigned NumSignBits = ComputeNumSignBits(Op0);
2384 if (NumSignBits == Op0->getType()->getScalarSizeInBits())
2385 return ReplaceInstUsesWith(I, Op0);
Dan Gohman0001e562009-02-24 02:00:40 +00002386
Chris Lattner348f6652007-12-06 01:59:46 +00002387 return 0;
Reid Spencer832254e2007-02-02 02:16:23 +00002388}
2389
2390Instruction *InstCombiner::commonShiftTransforms(BinaryOperator &I) {
2391 assert(I.getOperand(1)->getType() == I.getOperand(0)->getType());
Chris Lattner7e708292002-06-25 16:13:24 +00002392 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00002393
2394 // shl X, 0 == X and shr X, 0 == X
2395 // shl 0, X == 0 and shr 0, X == 0
Owen Andersona7235ea2009-07-31 20:28:14 +00002396 if (Op1 == Constant::getNullValue(Op1->getType()) ||
2397 Op0 == Constant::getNullValue(Op0->getType()))
Chris Lattner233f7dc2002-08-12 21:17:25 +00002398 return ReplaceInstUsesWith(I, Op0);
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00002399
Reid Spencere4d87aa2006-12-23 06:05:41 +00002400 if (isa<UndefValue>(Op0)) {
2401 if (I.getOpcode() == Instruction::AShr) // undef >>s X -> undef
Chris Lattner79a564c2004-10-16 23:28:04 +00002402 return ReplaceInstUsesWith(I, Op0);
Reid Spencere4d87aa2006-12-23 06:05:41 +00002403 else // undef << X -> 0, undef >>u X -> 0
Owen Andersona7235ea2009-07-31 20:28:14 +00002404 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00002405 }
2406 if (isa<UndefValue>(Op1)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00002407 if (I.getOpcode() == Instruction::AShr) // X >>s undef -> X
2408 return ReplaceInstUsesWith(I, Op0);
2409 else // X << undef, X >>u undef -> 0
Owen Andersona7235ea2009-07-31 20:28:14 +00002410 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00002411 }
2412
Dan Gohman9004c8a2009-05-21 02:28:33 +00002413 // See if we can fold away this shift.
Dan Gohman6de29f82009-06-15 22:12:54 +00002414 if (SimplifyDemandedInstructionBits(I))
Dan Gohman9004c8a2009-05-21 02:28:33 +00002415 return &I;
2416
Chris Lattner2eefe512004-04-09 19:05:30 +00002417 // Try to fold constant and into select arguments.
2418 if (isa<Constant>(Op0))
2419 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner80f43d32010-01-04 07:53:58 +00002420 if (Instruction *R = FoldOpIntoSelect(I, SI))
Chris Lattner2eefe512004-04-09 19:05:30 +00002421 return R;
2422
Reid Spencerb83eb642006-10-20 07:07:24 +00002423 if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
Reid Spencerc5b206b2006-12-31 05:48:39 +00002424 if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
2425 return Res;
Chris Lattner4d5542c2006-01-06 07:12:35 +00002426 return 0;
2427}
2428
Reid Spencerb83eb642006-10-20 07:07:24 +00002429Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
Reid Spencer832254e2007-02-02 02:16:23 +00002430 BinaryOperator &I) {
Chris Lattner4598c942009-01-31 08:24:16 +00002431 bool isLeftShift = I.getOpcode() == Instruction::Shl;
Chris Lattner4d5542c2006-01-06 07:12:35 +00002432
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00002433 // See if we can simplify any instructions used by the instruction whose sole
2434 // purpose is to compute bits we don't care about.
Dan Gohmanc6ac3222009-06-16 19:55:29 +00002435 uint32_t TypeBits = Op0->getType()->getScalarSizeInBits();
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00002436
Dan Gohmana119de82009-06-14 23:30:43 +00002437 // shl i32 X, 32 = 0 and srl i8 Y, 9 = 0, ... just don't eliminate
2438 // a signed shift.
Chris Lattner4d5542c2006-01-06 07:12:35 +00002439 //
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00002440 if (Op1->uge(TypeBits)) {
Chris Lattner0737c242007-02-02 05:29:55 +00002441 if (I.getOpcode() != Instruction::AShr)
Owen Andersona7235ea2009-07-31 20:28:14 +00002442 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
Chris Lattner4d5542c2006-01-06 07:12:35 +00002443 else {
Owen Andersoneed707b2009-07-24 23:12:02 +00002444 I.setOperand(1, ConstantInt::get(I.getType(), TypeBits-1));
Chris Lattner4d5542c2006-01-06 07:12:35 +00002445 return &I;
Chris Lattner8adac752004-02-23 20:30:06 +00002446 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00002447 }
2448
2449 // ((X*C1) << C2) == (X * (C1 << C2))
2450 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
2451 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
2452 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002453 return BinaryOperator::CreateMul(BO->getOperand(0),
Owen Andersonbaf3c402009-07-29 18:55:55 +00002454 ConstantExpr::getShl(BOOp, Op1));
Chris Lattner4d5542c2006-01-06 07:12:35 +00002455
2456 // Try to fold constant and into select arguments.
2457 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner80f43d32010-01-04 07:53:58 +00002458 if (Instruction *R = FoldOpIntoSelect(I, SI))
Chris Lattner4d5542c2006-01-06 07:12:35 +00002459 return R;
2460 if (isa<PHINode>(Op0))
2461 if (Instruction *NV = FoldOpIntoPhi(I))
2462 return NV;
2463
Chris Lattner8999dd32007-12-22 09:07:47 +00002464 // Fold shift2(trunc(shift1(x,c1)), c2) -> trunc(shift2(shift1(x,c1),c2))
2465 if (TruncInst *TI = dyn_cast<TruncInst>(Op0)) {
2466 Instruction *TrOp = dyn_cast<Instruction>(TI->getOperand(0));
2467 // If 'shift2' is an ashr, we would have to get the sign bit into a funny
2468 // place. Don't try to do this transformation in this case. Also, we
2469 // require that the input operand is a shift-by-constant so that we have
2470 // confidence that the shifts will get folded together. We could do this
2471 // xform in more cases, but it is unlikely to be profitable.
2472 if (TrOp && I.isLogicalShift() && TrOp->isShift() &&
2473 isa<ConstantInt>(TrOp->getOperand(1))) {
2474 // Okay, we'll do this xform. Make the shift of shift.
Owen Andersonbaf3c402009-07-29 18:55:55 +00002475 Constant *ShAmt = ConstantExpr::getZExt(Op1, TrOp->getType());
Chris Lattner74381062009-08-30 07:44:24 +00002476 // (shift2 (shift1 & 0x00FF), c2)
2477 Value *NSh = Builder->CreateBinOp(I.getOpcode(), TrOp, ShAmt,I.getName());
Chris Lattner8999dd32007-12-22 09:07:47 +00002478
2479 // For logical shifts, the truncation has the effect of making the high
2480 // part of the register be zeros. Emulate this by inserting an AND to
2481 // clear the top bits as needed. This 'and' will usually be zapped by
2482 // other xforms later if dead.
Dan Gohmanc6ac3222009-06-16 19:55:29 +00002483 unsigned SrcSize = TrOp->getType()->getScalarSizeInBits();
2484 unsigned DstSize = TI->getType()->getScalarSizeInBits();
Chris Lattner8999dd32007-12-22 09:07:47 +00002485 APInt MaskV(APInt::getLowBitsSet(SrcSize, DstSize));
2486
2487 // The mask we constructed says what the trunc would do if occurring
2488 // between the shifts. We want to know the effect *after* the second
2489 // shift. We know that it is a logical shift by a constant, so adjust the
2490 // mask as appropriate.
2491 if (I.getOpcode() == Instruction::Shl)
2492 MaskV <<= Op1->getZExtValue();
2493 else {
2494 assert(I.getOpcode() == Instruction::LShr && "Unknown logical shift");
2495 MaskV = MaskV.lshr(Op1->getZExtValue());
2496 }
2497
Chris Lattner74381062009-08-30 07:44:24 +00002498 // shift1 & 0x00FF
Chris Lattner4de84762010-01-04 07:02:48 +00002499 Value *And = Builder->CreateAnd(NSh,
2500 ConstantInt::get(I.getContext(), MaskV),
Chris Lattner74381062009-08-30 07:44:24 +00002501 TI->getName());
Chris Lattner8999dd32007-12-22 09:07:47 +00002502
2503 // Return the value truncated to the interesting size.
2504 return new TruncInst(And, I.getType());
2505 }
2506 }
2507
Chris Lattner4d5542c2006-01-06 07:12:35 +00002508 if (Op0->hasOneUse()) {
Chris Lattner4d5542c2006-01-06 07:12:35 +00002509 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
2510 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
2511 Value *V1, *V2;
2512 ConstantInt *CC;
2513 switch (Op0BO->getOpcode()) {
Chris Lattner11021cb2005-09-18 05:12:10 +00002514 default: break;
2515 case Instruction::Add:
2516 case Instruction::And:
2517 case Instruction::Or:
Reid Spencera07cb7d2007-02-02 14:41:37 +00002518 case Instruction::Xor: {
Chris Lattner11021cb2005-09-18 05:12:10 +00002519 // These operators commute.
2520 // Turn (Y + (X >> C)) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00002521 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00002522 match(Op0BO->getOperand(1), m_Shr(m_Value(V1),
Chris Lattnerf925cbd2009-08-30 18:50:58 +00002523 m_Specific(Op1)))) {
2524 Value *YS = // (Y << C)
2525 Builder->CreateShl(Op0BO->getOperand(0), Op1, Op0BO->getName());
2526 // (X + (Y << C))
2527 Value *X = Builder->CreateBinOp(Op0BO->getOpcode(), YS, V1,
2528 Op0BO->getOperand(1)->getName());
Zhou Sheng302748d2007-03-30 17:20:39 +00002529 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
Chris Lattner4de84762010-01-04 07:02:48 +00002530 return BinaryOperator::CreateAnd(X, ConstantInt::get(I.getContext(),
Zhou Sheng90b96812007-03-30 05:45:18 +00002531 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
Chris Lattner150f12a2005-09-18 06:30:59 +00002532 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00002533
Chris Lattner150f12a2005-09-18 06:30:59 +00002534 // Turn (Y + ((X >> C) & CC)) << C -> ((X & (CC << C)) + (Y << C))
Reid Spencera07cb7d2007-02-02 14:41:37 +00002535 Value *Op0BOOp1 = Op0BO->getOperand(1);
Chris Lattner3c698492007-03-05 00:11:19 +00002536 if (isLeftShift && Op0BOOp1->hasOneUse() &&
Reid Spencera07cb7d2007-02-02 14:41:37 +00002537 match(Op0BOOp1,
Chris Lattnercb504b92008-11-16 05:38:51 +00002538 m_And(m_Shr(m_Value(V1), m_Specific(Op1)),
Dan Gohman4ae51262009-08-12 16:23:25 +00002539 m_ConstantInt(CC))) &&
Chris Lattnercb504b92008-11-16 05:38:51 +00002540 cast<BinaryOperator>(Op0BOOp1)->getOperand(0)->hasOneUse()) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +00002541 Value *YS = // (Y << C)
2542 Builder->CreateShl(Op0BO->getOperand(0), Op1,
2543 Op0BO->getName());
2544 // X & (CC << C)
2545 Value *XM = Builder->CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
2546 V1->getName()+".mask");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002547 return BinaryOperator::Create(Op0BO->getOpcode(), YS, XM);
Chris Lattner150f12a2005-09-18 06:30:59 +00002548 }
Reid Spencera07cb7d2007-02-02 14:41:37 +00002549 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00002550
Reid Spencera07cb7d2007-02-02 14:41:37 +00002551 // FALL THROUGH.
2552 case Instruction::Sub: {
Chris Lattner11021cb2005-09-18 05:12:10 +00002553 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00002554 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00002555 match(Op0BO->getOperand(0), m_Shr(m_Value(V1),
Dan Gohman4ae51262009-08-12 16:23:25 +00002556 m_Specific(Op1)))) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +00002557 Value *YS = // (Y << C)
2558 Builder->CreateShl(Op0BO->getOperand(1), Op1, Op0BO->getName());
2559 // (X + (Y << C))
2560 Value *X = Builder->CreateBinOp(Op0BO->getOpcode(), V1, YS,
2561 Op0BO->getOperand(0)->getName());
Zhou Sheng302748d2007-03-30 17:20:39 +00002562 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
Chris Lattner4de84762010-01-04 07:02:48 +00002563 return BinaryOperator::CreateAnd(X, ConstantInt::get(I.getContext(),
Zhou Sheng90b96812007-03-30 05:45:18 +00002564 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
Chris Lattner150f12a2005-09-18 06:30:59 +00002565 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00002566
Chris Lattner13d4ab42006-05-31 21:14:00 +00002567 // Turn (((X >> C)&CC) + Y) << C -> (X + (Y << C)) & (CC << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00002568 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
2569 match(Op0BO->getOperand(0),
2570 m_And(m_Shr(m_Value(V1), m_Value(V2)),
Dan Gohman4ae51262009-08-12 16:23:25 +00002571 m_ConstantInt(CC))) && V2 == Op1 &&
Chris Lattner9a4cacb2006-02-09 07:41:14 +00002572 cast<BinaryOperator>(Op0BO->getOperand(0))
2573 ->getOperand(0)->hasOneUse()) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +00002574 Value *YS = // (Y << C)
2575 Builder->CreateShl(Op0BO->getOperand(1), Op1, Op0BO->getName());
2576 // X & (CC << C)
2577 Value *XM = Builder->CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
2578 V1->getName()+".mask");
Chris Lattner150f12a2005-09-18 06:30:59 +00002579
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002580 return BinaryOperator::Create(Op0BO->getOpcode(), XM, YS);
Chris Lattner150f12a2005-09-18 06:30:59 +00002581 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00002582
Chris Lattner11021cb2005-09-18 05:12:10 +00002583 break;
Reid Spencera07cb7d2007-02-02 14:41:37 +00002584 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00002585 }
2586
2587
2588 // If the operand is an bitwise operator with a constant RHS, and the
2589 // shift is the only use, we can pull it out of the shift.
2590 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
2591 bool isValid = true; // Valid only for And, Or, Xor
2592 bool highBitSet = false; // Transform if high bit of constant set?
2593
2594 switch (Op0BO->getOpcode()) {
Chris Lattnerdf17af12003-08-12 21:53:41 +00002595 default: isValid = false; break; // Do not perform transform!
Chris Lattner1f7e1602004-10-08 03:46:20 +00002596 case Instruction::Add:
2597 isValid = isLeftShift;
2598 break;
Chris Lattnerdf17af12003-08-12 21:53:41 +00002599 case Instruction::Or:
2600 case Instruction::Xor:
2601 highBitSet = false;
2602 break;
2603 case Instruction::And:
2604 highBitSet = true;
2605 break;
Chris Lattner4d5542c2006-01-06 07:12:35 +00002606 }
2607
2608 // If this is a signed shift right, and the high bit is modified
2609 // by the logical operation, do not perform the transformation.
2610 // The highBitSet boolean indicates the value of the high bit of
2611 // the constant which would cause it to be modified for this
2612 // operation.
2613 //
Chris Lattnerc95ba442007-12-06 06:25:04 +00002614 if (isValid && I.getOpcode() == Instruction::AShr)
Zhou Shenge9e03f62007-03-28 15:02:20 +00002615 isValid = Op0C->getValue()[TypeBits-1] == highBitSet;
Chris Lattner4d5542c2006-01-06 07:12:35 +00002616
2617 if (isValid) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00002618 Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
Chris Lattner4d5542c2006-01-06 07:12:35 +00002619
Chris Lattnerf925cbd2009-08-30 18:50:58 +00002620 Value *NewShift =
2621 Builder->CreateBinOp(I.getOpcode(), Op0BO->getOperand(0), Op1);
Chris Lattner6934a042007-02-11 01:23:03 +00002622 NewShift->takeName(Op0BO);
Chris Lattner4d5542c2006-01-06 07:12:35 +00002623
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002624 return BinaryOperator::Create(Op0BO->getOpcode(), NewShift,
Chris Lattner4d5542c2006-01-06 07:12:35 +00002625 NewRHS);
2626 }
2627 }
2628 }
2629 }
2630
Chris Lattnerad0124c2006-01-06 07:52:12 +00002631 // Find out if this is a shift of a shift by a constant.
Reid Spencer832254e2007-02-02 02:16:23 +00002632 BinaryOperator *ShiftOp = dyn_cast<BinaryOperator>(Op0);
2633 if (ShiftOp && !ShiftOp->isShift())
2634 ShiftOp = 0;
Chris Lattnerad0124c2006-01-06 07:52:12 +00002635
Reid Spencerb83eb642006-10-20 07:07:24 +00002636 if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
Reid Spencerb83eb642006-10-20 07:07:24 +00002637 ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00002638 uint32_t ShiftAmt1 = ShiftAmt1C->getLimitedValue(TypeBits);
2639 uint32_t ShiftAmt2 = Op1->getLimitedValue(TypeBits);
Chris Lattnerb87056f2007-02-05 00:57:54 +00002640 assert(ShiftAmt2 != 0 && "Should have been simplified earlier");
2641 if (ShiftAmt1 == 0) return 0; // Will be simplified in the future.
2642 Value *X = ShiftOp->getOperand(0);
Chris Lattnerad0124c2006-01-06 07:52:12 +00002643
Zhou Sheng4351c642007-04-02 08:20:41 +00002644 uint32_t AmtSum = ShiftAmt1+ShiftAmt2; // Fold into one big shift.
Chris Lattnerb87056f2007-02-05 00:57:54 +00002645
2646 const IntegerType *Ty = cast<IntegerType>(I.getType());
2647
2648 // Check for (X << c1) << c2 and (X >> c1) >> c2
Chris Lattner7f3da2d2007-02-03 23:28:07 +00002649 if (I.getOpcode() == ShiftOp->getOpcode()) {
Chris Lattner344c7c52009-03-20 22:41:15 +00002650 // If this is oversized composite shift, then unsigned shifts get 0, ashr
2651 // saturates.
2652 if (AmtSum >= TypeBits) {
2653 if (I.getOpcode() != Instruction::AShr)
Owen Andersona7235ea2009-07-31 20:28:14 +00002654 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner344c7c52009-03-20 22:41:15 +00002655 AmtSum = TypeBits-1; // Saturate to 31 for i32 ashr.
2656 }
2657
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002658 return BinaryOperator::Create(I.getOpcode(), X,
Owen Andersoneed707b2009-07-24 23:12:02 +00002659 ConstantInt::get(Ty, AmtSum));
Chris Lattnerf925cbd2009-08-30 18:50:58 +00002660 }
2661
2662 if (ShiftOp->getOpcode() == Instruction::LShr &&
2663 I.getOpcode() == Instruction::AShr) {
Chris Lattner344c7c52009-03-20 22:41:15 +00002664 if (AmtSum >= TypeBits)
Owen Andersona7235ea2009-07-31 20:28:14 +00002665 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner344c7c52009-03-20 22:41:15 +00002666
Chris Lattnerb87056f2007-02-05 00:57:54 +00002667 // ((X >>u C1) >>s C2) -> (X >>u (C1+C2)) since C1 != 0.
Owen Andersoneed707b2009-07-24 23:12:02 +00002668 return BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, AmtSum));
Chris Lattnerf925cbd2009-08-30 18:50:58 +00002669 }
2670
2671 if (ShiftOp->getOpcode() == Instruction::AShr &&
2672 I.getOpcode() == Instruction::LShr) {
Chris Lattnerb87056f2007-02-05 00:57:54 +00002673 // ((X >>s C1) >>u C2) -> ((X >>s (C1+C2)) & mask) since C1 != 0.
Chris Lattner344c7c52009-03-20 22:41:15 +00002674 if (AmtSum >= TypeBits)
2675 AmtSum = TypeBits-1;
2676
Chris Lattnerf925cbd2009-08-30 18:50:58 +00002677 Value *Shift = Builder->CreateAShr(X, ConstantInt::get(Ty, AmtSum));
Chris Lattnerb87056f2007-02-05 00:57:54 +00002678
Zhou Shenge9e03f62007-03-28 15:02:20 +00002679 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Chris Lattner4de84762010-01-04 07:02:48 +00002680 return BinaryOperator::CreateAnd(Shift,
2681 ConstantInt::get(I.getContext(), Mask));
Chris Lattnerad0124c2006-01-06 07:52:12 +00002682 }
2683
Chris Lattnerb87056f2007-02-05 00:57:54 +00002684 // Okay, if we get here, one shift must be left, and the other shift must be
2685 // right. See if the amounts are equal.
2686 if (ShiftAmt1 == ShiftAmt2) {
2687 // If we have ((X >>? C) << C), turn this into X & (-1 << C).
2688 if (I.getOpcode() == Instruction::Shl) {
Reid Spencer55702aa2007-03-25 21:11:44 +00002689 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt1));
Chris Lattner4de84762010-01-04 07:02:48 +00002690 return BinaryOperator::CreateAnd(X,
2691 ConstantInt::get(I.getContext(),Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00002692 }
2693 // If we have ((X << C) >>u C), turn this into X & (-1 >>u C).
2694 if (I.getOpcode() == Instruction::LShr) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002695 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt1));
Chris Lattner4de84762010-01-04 07:02:48 +00002696 return BinaryOperator::CreateAnd(X,
2697 ConstantInt::get(I.getContext(), Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00002698 }
2699 // We can simplify ((X << C) >>s C) into a trunc + sext.
2700 // NOTE: we could do this for any C, but that would make 'unusual' integer
2701 // types. For now, just stick to ones well-supported by the code
2702 // generators.
2703 const Type *SExtType = 0;
2704 switch (Ty->getBitWidth() - ShiftAmt1) {
Zhou Shenge9e03f62007-03-28 15:02:20 +00002705 case 1 :
2706 case 8 :
2707 case 16 :
2708 case 32 :
2709 case 64 :
2710 case 128:
Chris Lattner4de84762010-01-04 07:02:48 +00002711 SExtType = IntegerType::get(I.getContext(),
2712 Ty->getBitWidth() - ShiftAmt1);
Zhou Shenge9e03f62007-03-28 15:02:20 +00002713 break;
Chris Lattnerb87056f2007-02-05 00:57:54 +00002714 default: break;
2715 }
Chris Lattnerf925cbd2009-08-30 18:50:58 +00002716 if (SExtType)
2717 return new SExtInst(Builder->CreateTrunc(X, SExtType, "sext"), Ty);
Chris Lattnerb87056f2007-02-05 00:57:54 +00002718 // Otherwise, we can't handle it yet.
2719 } else if (ShiftAmt1 < ShiftAmt2) {
Zhou Sheng4351c642007-04-02 08:20:41 +00002720 uint32_t ShiftDiff = ShiftAmt2-ShiftAmt1;
Chris Lattnerad0124c2006-01-06 07:52:12 +00002721
Chris Lattnerb0b991a2007-02-05 05:57:49 +00002722 // (X >>? C1) << C2 --> X << (C2-C1) & (-1 << C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00002723 if (I.getOpcode() == Instruction::Shl) {
2724 assert(ShiftOp->getOpcode() == Instruction::LShr ||
2725 ShiftOp->getOpcode() == Instruction::AShr);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00002726 Value *Shift = Builder->CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
Chris Lattnere8d56c52006-01-07 01:32:28 +00002727
Reid Spencer55702aa2007-03-25 21:11:44 +00002728 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersoneed707b2009-07-24 23:12:02 +00002729 return BinaryOperator::CreateAnd(Shift,
Chris Lattner4de84762010-01-04 07:02:48 +00002730 ConstantInt::get(I.getContext(),Mask));
Chris Lattnerad0124c2006-01-06 07:52:12 +00002731 }
Chris Lattnerb87056f2007-02-05 00:57:54 +00002732
Chris Lattnerb0b991a2007-02-05 05:57:49 +00002733 // (X << C1) >>u C2 --> X >>u (C2-C1) & (-1 >> C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00002734 if (I.getOpcode() == Instruction::LShr) {
2735 assert(ShiftOp->getOpcode() == Instruction::Shl);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00002736 Value *Shift = Builder->CreateLShr(X, ConstantInt::get(Ty, ShiftDiff));
Chris Lattnerad0124c2006-01-06 07:52:12 +00002737
Reid Spencerd5e30f02007-03-26 17:18:58 +00002738 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersoneed707b2009-07-24 23:12:02 +00002739 return BinaryOperator::CreateAnd(Shift,
Chris Lattner4de84762010-01-04 07:02:48 +00002740 ConstantInt::get(I.getContext(),Mask));
Chris Lattner11021cb2005-09-18 05:12:10 +00002741 }
Chris Lattnerb87056f2007-02-05 00:57:54 +00002742
2743 // We can't handle (X << C1) >>s C2, it shifts arbitrary bits in.
2744 } else {
2745 assert(ShiftAmt2 < ShiftAmt1);
Zhou Sheng4351c642007-04-02 08:20:41 +00002746 uint32_t ShiftDiff = ShiftAmt1-ShiftAmt2;
Chris Lattnerb87056f2007-02-05 00:57:54 +00002747
Chris Lattnerb0b991a2007-02-05 05:57:49 +00002748 // (X >>? C1) << C2 --> X >>? (C1-C2) & (-1 << C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00002749 if (I.getOpcode() == Instruction::Shl) {
2750 assert(ShiftOp->getOpcode() == Instruction::LShr ||
2751 ShiftOp->getOpcode() == Instruction::AShr);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00002752 Value *Shift = Builder->CreateBinOp(ShiftOp->getOpcode(), X,
2753 ConstantInt::get(Ty, ShiftDiff));
Chris Lattnerb87056f2007-02-05 00:57:54 +00002754
Reid Spencer55702aa2007-03-25 21:11:44 +00002755 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersoneed707b2009-07-24 23:12:02 +00002756 return BinaryOperator::CreateAnd(Shift,
Chris Lattner4de84762010-01-04 07:02:48 +00002757 ConstantInt::get(I.getContext(),Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00002758 }
2759
Chris Lattnerb0b991a2007-02-05 05:57:49 +00002760 // (X << C1) >>u C2 --> X << (C1-C2) & (-1 >> C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00002761 if (I.getOpcode() == Instruction::LShr) {
2762 assert(ShiftOp->getOpcode() == Instruction::Shl);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00002763 Value *Shift = Builder->CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
Chris Lattnerb87056f2007-02-05 00:57:54 +00002764
Reid Spencer68d27cf2007-03-26 23:45:51 +00002765 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersoneed707b2009-07-24 23:12:02 +00002766 return BinaryOperator::CreateAnd(Shift,
Chris Lattner4de84762010-01-04 07:02:48 +00002767 ConstantInt::get(I.getContext(),Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00002768 }
2769
2770 // We can't handle (X << C1) >>a C2, it shifts arbitrary bits in.
Chris Lattner6e7ba452005-01-01 16:22:27 +00002771 }
Chris Lattnerad0124c2006-01-06 07:52:12 +00002772 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00002773 return 0;
2774}
2775
Chris Lattnera1be5662002-05-02 17:06:02 +00002776
Reid Spencer3da59db2006-11-27 01:05:10 +00002777
Chris Lattner46cd5a12009-01-09 05:44:56 +00002778/// FindElementAtOffset - Given a type and a constant offset, determine whether
2779/// or not there is a sequence of GEP indices into the type that will land us at
Chris Lattner3914f722009-01-24 01:00:13 +00002780/// the specified offset. If so, fill them into NewIndices and return the
2781/// resultant element type, otherwise return null.
Chris Lattner80f43d32010-01-04 07:53:58 +00002782const Type *InstCombiner::FindElementAtOffset(const Type *Ty, int64_t Offset,
2783 SmallVectorImpl<Value*> &NewIndices) {
Dan Gohmance9fe9f2009-07-21 23:21:54 +00002784 if (!TD) return 0;
Chris Lattner3914f722009-01-24 01:00:13 +00002785 if (!Ty->isSized()) return 0;
Chris Lattner46cd5a12009-01-09 05:44:56 +00002786
2787 // Start with the index over the outer type. Note that the type size
2788 // might be zero (even if the offset isn't zero) if the indexed type
2789 // is something like [0 x {int, int}]
Chris Lattner4de84762010-01-04 07:02:48 +00002790 const Type *IntPtrTy = TD->getIntPtrType(Ty->getContext());
Chris Lattner46cd5a12009-01-09 05:44:56 +00002791 int64_t FirstIdx = 0;
Duncan Sands777d2302009-05-09 07:06:46 +00002792 if (int64_t TySize = TD->getTypeAllocSize(Ty)) {
Chris Lattner46cd5a12009-01-09 05:44:56 +00002793 FirstIdx = Offset/TySize;
Chris Lattner31a69cb2009-01-11 20:41:36 +00002794 Offset -= FirstIdx*TySize;
Chris Lattner46cd5a12009-01-09 05:44:56 +00002795
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00002796 // Handle hosts where % returns negative instead of values [0..TySize).
Chris Lattner46cd5a12009-01-09 05:44:56 +00002797 if (Offset < 0) {
2798 --FirstIdx;
2799 Offset += TySize;
2800 assert(Offset >= 0);
2801 }
2802 assert((uint64_t)Offset < (uint64_t)TySize && "Out of range offset");
2803 }
2804
Owen Andersoneed707b2009-07-24 23:12:02 +00002805 NewIndices.push_back(ConstantInt::get(IntPtrTy, FirstIdx));
Chris Lattner46cd5a12009-01-09 05:44:56 +00002806
2807 // Index into the types. If we fail, set OrigBase to null.
2808 while (Offset) {
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00002809 // Indexing into tail padding between struct/array elements.
2810 if (uint64_t(Offset*8) >= TD->getTypeSizeInBits(Ty))
Chris Lattner3914f722009-01-24 01:00:13 +00002811 return 0;
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00002812
Chris Lattner46cd5a12009-01-09 05:44:56 +00002813 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
2814 const StructLayout *SL = TD->getStructLayout(STy);
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00002815 assert(Offset < (int64_t)SL->getSizeInBytes() &&
2816 "Offset must stay within the indexed type");
2817
Chris Lattner46cd5a12009-01-09 05:44:56 +00002818 unsigned Elt = SL->getElementContainingOffset(Offset);
Chris Lattner4de84762010-01-04 07:02:48 +00002819 NewIndices.push_back(ConstantInt::get(Type::getInt32Ty(Ty->getContext()),
2820 Elt));
Chris Lattner46cd5a12009-01-09 05:44:56 +00002821
2822 Offset -= SL->getElementOffset(Elt);
2823 Ty = STy->getElementType(Elt);
Chris Lattner1c412d92009-01-11 20:23:52 +00002824 } else if (const ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
Duncan Sands777d2302009-05-09 07:06:46 +00002825 uint64_t EltSize = TD->getTypeAllocSize(AT->getElementType());
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00002826 assert(EltSize && "Cannot index into a zero-sized array");
Owen Andersoneed707b2009-07-24 23:12:02 +00002827 NewIndices.push_back(ConstantInt::get(IntPtrTy,Offset/EltSize));
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00002828 Offset %= EltSize;
Chris Lattner1c412d92009-01-11 20:23:52 +00002829 Ty = AT->getElementType();
Chris Lattner46cd5a12009-01-09 05:44:56 +00002830 } else {
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00002831 // Otherwise, we can't index into the middle of this atomic type, bail.
Chris Lattner3914f722009-01-24 01:00:13 +00002832 return 0;
Chris Lattner46cd5a12009-01-09 05:44:56 +00002833 }
2834 }
2835
Chris Lattner3914f722009-01-24 01:00:13 +00002836 return Ty;
Chris Lattner46cd5a12009-01-09 05:44:56 +00002837}
2838
Chris Lattner8a2a3112001-12-14 16:52:21 +00002839
Dan Gohmaneee962e2008-04-10 18:43:06 +00002840/// EnforceKnownAlignment - If the specified pointer points to an object that
2841/// we control, modify the object's alignment to PrefAlign. This isn't
2842/// often possible though. If alignment is important, a more reliable approach
2843/// is to simply align all global variables and allocation instructions to
2844/// their preferred alignment from the beginning.
2845///
2846static unsigned EnforceKnownAlignment(Value *V,
2847 unsigned Align, unsigned PrefAlign) {
Chris Lattnerf2369f22007-08-09 19:05:49 +00002848
Dan Gohmaneee962e2008-04-10 18:43:06 +00002849 User *U = dyn_cast<User>(V);
2850 if (!U) return Align;
2851
Dan Gohmanca178902009-07-17 20:47:02 +00002852 switch (Operator::getOpcode(U)) {
Dan Gohmaneee962e2008-04-10 18:43:06 +00002853 default: break;
2854 case Instruction::BitCast:
2855 return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
2856 case Instruction::GetElementPtr: {
Chris Lattner95a959d2006-03-06 20:18:44 +00002857 // If all indexes are zero, it is just the alignment of the base pointer.
2858 bool AllZeroOperands = true;
Gabor Greif52ed3632008-06-12 21:51:29 +00002859 for (User::op_iterator i = U->op_begin() + 1, e = U->op_end(); i != e; ++i)
Gabor Greif177dd3f2008-06-12 21:37:33 +00002860 if (!isa<Constant>(*i) ||
2861 !cast<Constant>(*i)->isNullValue()) {
Chris Lattner95a959d2006-03-06 20:18:44 +00002862 AllZeroOperands = false;
2863 break;
2864 }
Chris Lattnerf2369f22007-08-09 19:05:49 +00002865
2866 if (AllZeroOperands) {
2867 // Treat this like a bitcast.
Dan Gohmaneee962e2008-04-10 18:43:06 +00002868 return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
Chris Lattnerf2369f22007-08-09 19:05:49 +00002869 }
Dan Gohmaneee962e2008-04-10 18:43:06 +00002870 break;
Chris Lattner95a959d2006-03-06 20:18:44 +00002871 }
Dan Gohmaneee962e2008-04-10 18:43:06 +00002872 }
2873
2874 if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
2875 // If there is a large requested alignment and we can, bump up the alignment
2876 // of the global.
2877 if (!GV->isDeclaration()) {
Dan Gohmanecd0fb52009-02-16 23:02:21 +00002878 if (GV->getAlignment() >= PrefAlign)
2879 Align = GV->getAlignment();
2880 else {
2881 GV->setAlignment(PrefAlign);
2882 Align = PrefAlign;
2883 }
Dan Gohmaneee962e2008-04-10 18:43:06 +00002884 }
Chris Lattner42ebefa2009-09-27 21:42:46 +00002885 } else if (AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
2886 // If there is a requested alignment and if this is an alloca, round up.
2887 if (AI->getAlignment() >= PrefAlign)
2888 Align = AI->getAlignment();
2889 else {
2890 AI->setAlignment(PrefAlign);
2891 Align = PrefAlign;
Dan Gohmaneee962e2008-04-10 18:43:06 +00002892 }
2893 }
2894
2895 return Align;
2896}
2897
2898/// GetOrEnforceKnownAlignment - If the specified pointer has an alignment that
2899/// we can determine, return it, otherwise return 0. If PrefAlign is specified,
2900/// and it is more than the alignment of the ultimate object, see if we can
2901/// increase the alignment of the ultimate object, making this check succeed.
2902unsigned InstCombiner::GetOrEnforceKnownAlignment(Value *V,
2903 unsigned PrefAlign) {
2904 unsigned BitWidth = TD ? TD->getTypeSizeInBits(V->getType()) :
2905 sizeof(PrefAlign) * CHAR_BIT;
2906 APInt Mask = APInt::getAllOnesValue(BitWidth);
2907 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
2908 ComputeMaskedBits(V, Mask, KnownZero, KnownOne);
2909 unsigned TrailZ = KnownZero.countTrailingOnes();
2910 unsigned Align = 1u << std::min(BitWidth - 1, TrailZ);
2911
2912 if (PrefAlign > Align)
2913 Align = EnforceKnownAlignment(V, Align, PrefAlign);
2914
2915 // We don't need to make any adjustment.
2916 return Align;
Chris Lattner95a959d2006-03-06 20:18:44 +00002917}
2918
Chris Lattnerf497b022008-01-13 23:50:23 +00002919Instruction *InstCombiner::SimplifyMemTransfer(MemIntrinsic *MI) {
Dan Gohmaneee962e2008-04-10 18:43:06 +00002920 unsigned DstAlign = GetOrEnforceKnownAlignment(MI->getOperand(1));
Dan Gohmanbc989d42009-02-22 18:06:32 +00002921 unsigned SrcAlign = GetOrEnforceKnownAlignment(MI->getOperand(2));
Chris Lattnerf497b022008-01-13 23:50:23 +00002922 unsigned MinAlign = std::min(DstAlign, SrcAlign);
Chris Lattnerdfe964c2009-03-08 03:59:00 +00002923 unsigned CopyAlign = MI->getAlignment();
Chris Lattnerf497b022008-01-13 23:50:23 +00002924
2925 if (CopyAlign < MinAlign) {
Owen Andersoneed707b2009-07-24 23:12:02 +00002926 MI->setAlignment(ConstantInt::get(MI->getAlignmentType(),
Owen Andersona547b472009-07-09 18:36:20 +00002927 MinAlign, false));
Chris Lattnerf497b022008-01-13 23:50:23 +00002928 return MI;
2929 }
2930
2931 // If MemCpyInst length is 1/2/4/8 bytes then replace memcpy with
2932 // load/store.
2933 ConstantInt *MemOpLength = dyn_cast<ConstantInt>(MI->getOperand(3));
2934 if (MemOpLength == 0) return 0;
2935
Chris Lattner37ac6082008-01-14 00:28:35 +00002936 // Source and destination pointer types are always "i8*" for intrinsic. See
2937 // if the size is something we can handle with a single primitive load/store.
2938 // A single load+store correctly handles overlapping memory in the memmove
2939 // case.
Chris Lattnerf497b022008-01-13 23:50:23 +00002940 unsigned Size = MemOpLength->getZExtValue();
Chris Lattner69ea9d22008-04-30 06:39:11 +00002941 if (Size == 0) return MI; // Delete this mem transfer.
2942
2943 if (Size > 8 || (Size&(Size-1)))
Chris Lattner37ac6082008-01-14 00:28:35 +00002944 return 0; // If not 1/2/4/8 bytes, exit.
Chris Lattnerf497b022008-01-13 23:50:23 +00002945
Chris Lattner37ac6082008-01-14 00:28:35 +00002946 // Use an integer load+store unless we can find something better.
Owen Andersond672ecb2009-07-03 00:17:18 +00002947 Type *NewPtrTy =
Chris Lattner4de84762010-01-04 07:02:48 +00002948 PointerType::getUnqual(IntegerType::get(MI->getContext(), Size<<3));
Chris Lattner37ac6082008-01-14 00:28:35 +00002949
2950 // Memcpy forces the use of i8* for the source and destination. That means
2951 // that if you're using memcpy to move one double around, you'll get a cast
2952 // from double* to i8*. We'd much rather use a double load+store rather than
2953 // an i64 load+store, here because this improves the odds that the source or
2954 // dest address will be promotable. See if we can find a better type than the
2955 // integer datatype.
2956 if (Value *Op = getBitCastOperand(MI->getOperand(1))) {
2957 const Type *SrcETy = cast<PointerType>(Op->getType())->getElementType();
Dan Gohmance9fe9f2009-07-21 23:21:54 +00002958 if (TD && SrcETy->isSized() && TD->getTypeStoreSize(SrcETy) == Size) {
Chris Lattner37ac6082008-01-14 00:28:35 +00002959 // The SrcETy might be something like {{{double}}} or [1 x double]. Rip
2960 // down through these levels if so.
Dan Gohman8f8e2692008-05-23 01:52:21 +00002961 while (!SrcETy->isSingleValueType()) {
Chris Lattner37ac6082008-01-14 00:28:35 +00002962 if (const StructType *STy = dyn_cast<StructType>(SrcETy)) {
2963 if (STy->getNumElements() == 1)
2964 SrcETy = STy->getElementType(0);
2965 else
2966 break;
2967 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcETy)) {
2968 if (ATy->getNumElements() == 1)
2969 SrcETy = ATy->getElementType();
2970 else
2971 break;
2972 } else
2973 break;
2974 }
2975
Dan Gohman8f8e2692008-05-23 01:52:21 +00002976 if (SrcETy->isSingleValueType())
Owen Andersondebcb012009-07-29 22:17:13 +00002977 NewPtrTy = PointerType::getUnqual(SrcETy);
Chris Lattner37ac6082008-01-14 00:28:35 +00002978 }
2979 }
2980
2981
Chris Lattnerf497b022008-01-13 23:50:23 +00002982 // If the memcpy/memmove provides better alignment info than we can
2983 // infer, use it.
2984 SrcAlign = std::max(SrcAlign, CopyAlign);
2985 DstAlign = std::max(DstAlign, CopyAlign);
2986
Chris Lattner08142f22009-08-30 19:47:22 +00002987 Value *Src = Builder->CreateBitCast(MI->getOperand(2), NewPtrTy);
2988 Value *Dest = Builder->CreateBitCast(MI->getOperand(1), NewPtrTy);
Chris Lattner37ac6082008-01-14 00:28:35 +00002989 Instruction *L = new LoadInst(Src, "tmp", false, SrcAlign);
2990 InsertNewInstBefore(L, *MI);
2991 InsertNewInstBefore(new StoreInst(L, Dest, false, DstAlign), *MI);
2992
2993 // Set the size of the copy to 0, it will be deleted on the next iteration.
Owen Andersona7235ea2009-07-31 20:28:14 +00002994 MI->setOperand(3, Constant::getNullValue(MemOpLength->getType()));
Chris Lattner37ac6082008-01-14 00:28:35 +00002995 return MI;
Chris Lattnerf497b022008-01-13 23:50:23 +00002996}
Chris Lattner3d69f462004-03-12 05:52:32 +00002997
Chris Lattner69ea9d22008-04-30 06:39:11 +00002998Instruction *InstCombiner::SimplifyMemSet(MemSetInst *MI) {
2999 unsigned Alignment = GetOrEnforceKnownAlignment(MI->getDest());
Chris Lattnerdfe964c2009-03-08 03:59:00 +00003000 if (MI->getAlignment() < Alignment) {
Owen Andersoneed707b2009-07-24 23:12:02 +00003001 MI->setAlignment(ConstantInt::get(MI->getAlignmentType(),
Owen Andersona547b472009-07-09 18:36:20 +00003002 Alignment, false));
Chris Lattner69ea9d22008-04-30 06:39:11 +00003003 return MI;
3004 }
3005
3006 // Extract the length and alignment and fill if they are constant.
3007 ConstantInt *LenC = dyn_cast<ConstantInt>(MI->getLength());
3008 ConstantInt *FillC = dyn_cast<ConstantInt>(MI->getValue());
Chris Lattner4de84762010-01-04 07:02:48 +00003009 if (!LenC || !FillC || FillC->getType() != Type::getInt8Ty(MI->getContext()))
Chris Lattner69ea9d22008-04-30 06:39:11 +00003010 return 0;
3011 uint64_t Len = LenC->getZExtValue();
Chris Lattnerdfe964c2009-03-08 03:59:00 +00003012 Alignment = MI->getAlignment();
Chris Lattner69ea9d22008-04-30 06:39:11 +00003013
3014 // If the length is zero, this is a no-op
3015 if (Len == 0) return MI; // memset(d,c,0,a) -> noop
3016
3017 // memset(s,c,n) -> store s, c (for n=1,2,4,8)
3018 if (Len <= 8 && isPowerOf2_32((uint32_t)Len)) {
Chris Lattner4de84762010-01-04 07:02:48 +00003019 const Type *ITy = IntegerType::get(MI->getContext(), Len*8); // n=1 -> i8.
Chris Lattner69ea9d22008-04-30 06:39:11 +00003020
3021 Value *Dest = MI->getDest();
Chris Lattner08142f22009-08-30 19:47:22 +00003022 Dest = Builder->CreateBitCast(Dest, PointerType::getUnqual(ITy));
Chris Lattner69ea9d22008-04-30 06:39:11 +00003023
3024 // Alignment 0 is identity for alignment 1 for memset, but not store.
3025 if (Alignment == 0) Alignment = 1;
3026
3027 // Extract the fill value and store.
3028 uint64_t Fill = FillC->getZExtValue()*0x0101010101010101ULL;
Owen Andersoneed707b2009-07-24 23:12:02 +00003029 InsertNewInstBefore(new StoreInst(ConstantInt::get(ITy, Fill),
Owen Andersond672ecb2009-07-03 00:17:18 +00003030 Dest, false, Alignment), *MI);
Chris Lattner69ea9d22008-04-30 06:39:11 +00003031
3032 // Set the size of the copy to 0, it will be deleted on the next iteration.
Owen Andersona7235ea2009-07-31 20:28:14 +00003033 MI->setLength(Constant::getNullValue(LenC->getType()));
Chris Lattner69ea9d22008-04-30 06:39:11 +00003034 return MI;
3035 }
3036
3037 return 0;
3038}
3039
3040
Chris Lattner8b0ea312006-01-13 20:11:04 +00003041/// visitCallInst - CallInst simplification. This mostly only handles folding
3042/// of intrinsic instructions. For normal calls, it allows visitCallSite to do
3043/// the heavy lifting.
3044///
Chris Lattner9fe38862003-06-19 17:00:31 +00003045Instruction *InstCombiner::visitCallInst(CallInst &CI) {
Victor Hernandez66284e02009-10-24 04:23:03 +00003046 if (isFreeCall(&CI))
3047 return visitFree(CI);
3048
Chris Lattneraab6ec42009-05-13 17:39:14 +00003049 // If the caller function is nounwind, mark the call as nounwind, even if the
3050 // callee isn't.
3051 if (CI.getParent()->getParent()->doesNotThrow() &&
3052 !CI.doesNotThrow()) {
3053 CI.setDoesNotThrow();
3054 return &CI;
3055 }
3056
Chris Lattner8b0ea312006-01-13 20:11:04 +00003057 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
3058 if (!II) return visitCallSite(&CI);
3059
Chris Lattner7bcc0e72004-02-28 05:22:00 +00003060 // Intrinsics cannot occur in an invoke, so handle them here instead of in
3061 // visitCallSite.
Chris Lattner8b0ea312006-01-13 20:11:04 +00003062 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
Chris Lattner35b9e482004-10-12 04:52:52 +00003063 bool Changed = false;
3064
3065 // memmove/cpy/set of zero bytes is a noop.
3066 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
3067 if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
3068
Chris Lattner35b9e482004-10-12 04:52:52 +00003069 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
Reid Spencerb83eb642006-10-20 07:07:24 +00003070 if (CI->getZExtValue() == 1) {
Chris Lattner35b9e482004-10-12 04:52:52 +00003071 // Replace the instruction with just byte operations. We would
3072 // transform other cases to loads/stores, but we don't know if
3073 // alignment is sufficient.
3074 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +00003075 }
3076
Chris Lattner35b9e482004-10-12 04:52:52 +00003077 // If we have a memmove and the source operation is a constant global,
3078 // then the source and dest pointers can't alias, so we can change this
3079 // into a call to memcpy.
Chris Lattnerf497b022008-01-13 23:50:23 +00003080 if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI)) {
Chris Lattner35b9e482004-10-12 04:52:52 +00003081 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
3082 if (GVSrc->isConstant()) {
3083 Module *M = CI.getParent()->getParent()->getParent();
Chris Lattner824b9582008-11-21 16:42:48 +00003084 Intrinsic::ID MemCpyID = Intrinsic::memcpy;
3085 const Type *Tys[1];
3086 Tys[0] = CI.getOperand(3)->getType();
3087 CI.setOperand(0,
3088 Intrinsic::getDeclaration(M, MemCpyID, Tys, 1));
Chris Lattner35b9e482004-10-12 04:52:52 +00003089 Changed = true;
3090 }
Eli Friedman0c826d92009-12-17 21:07:31 +00003091 }
Chris Lattnera935db82008-05-28 05:30:41 +00003092
Eli Friedman0c826d92009-12-17 21:07:31 +00003093 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(MI)) {
Chris Lattnera935db82008-05-28 05:30:41 +00003094 // memmove(x,x,size) -> noop.
Eli Friedman0c826d92009-12-17 21:07:31 +00003095 if (MTI->getSource() == MTI->getDest())
Chris Lattnera935db82008-05-28 05:30:41 +00003096 return EraseInstFromFunction(CI);
Chris Lattner95a959d2006-03-06 20:18:44 +00003097 }
Chris Lattner35b9e482004-10-12 04:52:52 +00003098
Chris Lattner95a959d2006-03-06 20:18:44 +00003099 // If we can determine a pointer alignment that is bigger than currently
3100 // set, update the alignment.
Chris Lattner3ce5e882009-03-08 03:37:16 +00003101 if (isa<MemTransferInst>(MI)) {
Chris Lattnerf497b022008-01-13 23:50:23 +00003102 if (Instruction *I = SimplifyMemTransfer(MI))
3103 return I;
Chris Lattner69ea9d22008-04-30 06:39:11 +00003104 } else if (MemSetInst *MSI = dyn_cast<MemSetInst>(MI)) {
3105 if (Instruction *I = SimplifyMemSet(MSI))
3106 return I;
Chris Lattner95a959d2006-03-06 20:18:44 +00003107 }
3108
Chris Lattner8b0ea312006-01-13 20:11:04 +00003109 if (Changed) return II;
Chris Lattner0521e3c2008-06-18 04:33:20 +00003110 }
3111
3112 switch (II->getIntrinsicID()) {
3113 default: break;
3114 case Intrinsic::bswap:
3115 // bswap(bswap(x)) -> x
3116 if (IntrinsicInst *Operand = dyn_cast<IntrinsicInst>(II->getOperand(1)))
3117 if (Operand->getIntrinsicID() == Intrinsic::bswap)
3118 return ReplaceInstUsesWith(CI, Operand->getOperand(1));
Chris Lattnere33d4132010-01-01 18:34:40 +00003119
3120 // bswap(trunc(bswap(x))) -> trunc(lshr(x, c))
3121 if (TruncInst *TI = dyn_cast<TruncInst>(II->getOperand(1))) {
3122 if (IntrinsicInst *Operand = dyn_cast<IntrinsicInst>(TI->getOperand(0)))
3123 if (Operand->getIntrinsicID() == Intrinsic::bswap) {
3124 unsigned C = Operand->getType()->getPrimitiveSizeInBits() -
3125 TI->getType()->getPrimitiveSizeInBits();
3126 Value *CV = ConstantInt::get(Operand->getType(), C);
3127 Value *V = Builder->CreateLShr(Operand->getOperand(1), CV);
3128 return new TruncInst(V, TI->getType());
3129 }
3130 }
3131
Chris Lattner0521e3c2008-06-18 04:33:20 +00003132 break;
Chris Lattnerd27f9112010-01-01 01:52:15 +00003133 case Intrinsic::powi:
3134 if (ConstantInt *Power = dyn_cast<ConstantInt>(II->getOperand(2))) {
3135 // powi(x, 0) -> 1.0
3136 if (Power->isZero())
3137 return ReplaceInstUsesWith(CI, ConstantFP::get(CI.getType(), 1.0));
3138 // powi(x, 1) -> x
3139 if (Power->isOne())
3140 return ReplaceInstUsesWith(CI, II->getOperand(1));
3141 // powi(x, -1) -> 1/x
Chris Lattnerf9ead872010-01-01 01:54:08 +00003142 if (Power->isAllOnesValue())
3143 return BinaryOperator::CreateFDiv(ConstantFP::get(CI.getType(), 1.0),
3144 II->getOperand(1));
Chris Lattnerd27f9112010-01-01 01:52:15 +00003145 }
3146 break;
3147
Chris Lattner2bbac752009-11-26 21:42:47 +00003148 case Intrinsic::uadd_with_overflow: {
3149 Value *LHS = II->getOperand(1), *RHS = II->getOperand(2);
3150 const IntegerType *IT = cast<IntegerType>(II->getOperand(1)->getType());
3151 uint32_t BitWidth = IT->getBitWidth();
3152 APInt Mask = APInt::getSignBit(BitWidth);
Chris Lattner998e25a2009-11-26 22:08:06 +00003153 APInt LHSKnownZero(BitWidth, 0);
3154 APInt LHSKnownOne(BitWidth, 0);
Chris Lattner2bbac752009-11-26 21:42:47 +00003155 ComputeMaskedBits(LHS, Mask, LHSKnownZero, LHSKnownOne);
3156 bool LHSKnownNegative = LHSKnownOne[BitWidth - 1];
3157 bool LHSKnownPositive = LHSKnownZero[BitWidth - 1];
3158
3159 if (LHSKnownNegative || LHSKnownPositive) {
Chris Lattner998e25a2009-11-26 22:08:06 +00003160 APInt RHSKnownZero(BitWidth, 0);
3161 APInt RHSKnownOne(BitWidth, 0);
Chris Lattner2bbac752009-11-26 21:42:47 +00003162 ComputeMaskedBits(RHS, Mask, RHSKnownZero, RHSKnownOne);
3163 bool RHSKnownNegative = RHSKnownOne[BitWidth - 1];
3164 bool RHSKnownPositive = RHSKnownZero[BitWidth - 1];
3165 if (LHSKnownNegative && RHSKnownNegative) {
3166 // The sign bit is set in both cases: this MUST overflow.
3167 // Create a simple add instruction, and insert it into the struct.
3168 Instruction *Add = BinaryOperator::CreateAdd(LHS, RHS, "", &CI);
3169 Worklist.Add(Add);
Chris Lattnercd188e92009-11-29 02:57:29 +00003170 Constant *V[] = {
Chris Lattner4de84762010-01-04 07:02:48 +00003171 UndefValue::get(LHS->getType()),ConstantInt::getTrue(II->getContext())
Chris Lattnercd188e92009-11-29 02:57:29 +00003172 };
Chris Lattner4de84762010-01-04 07:02:48 +00003173 Constant *Struct = ConstantStruct::get(II->getContext(), V, 2, false);
Chris Lattner2bbac752009-11-26 21:42:47 +00003174 return InsertValueInst::Create(Struct, Add, 0);
3175 }
3176
3177 if (LHSKnownPositive && RHSKnownPositive) {
3178 // The sign bit is clear in both cases: this CANNOT overflow.
3179 // Create a simple add instruction, and insert it into the struct.
3180 Instruction *Add = BinaryOperator::CreateNUWAdd(LHS, RHS, "", &CI);
3181 Worklist.Add(Add);
Chris Lattnercd188e92009-11-29 02:57:29 +00003182 Constant *V[] = {
Chris Lattner4de84762010-01-04 07:02:48 +00003183 UndefValue::get(LHS->getType()),
3184 ConstantInt::getFalse(II->getContext())
Chris Lattnercd188e92009-11-29 02:57:29 +00003185 };
Chris Lattner4de84762010-01-04 07:02:48 +00003186 Constant *Struct = ConstantStruct::get(II->getContext(), V, 2, false);
Chris Lattner2bbac752009-11-26 21:42:47 +00003187 return InsertValueInst::Create(Struct, Add, 0);
3188 }
3189 }
3190 }
3191 // FALL THROUGH uadd into sadd
3192 case Intrinsic::sadd_with_overflow:
3193 // Canonicalize constants into the RHS.
3194 if (isa<Constant>(II->getOperand(1)) &&
3195 !isa<Constant>(II->getOperand(2))) {
3196 Value *LHS = II->getOperand(1);
3197 II->setOperand(1, II->getOperand(2));
3198 II->setOperand(2, LHS);
3199 return II;
3200 }
3201
3202 // X + undef -> undef
3203 if (isa<UndefValue>(II->getOperand(2)))
3204 return ReplaceInstUsesWith(CI, UndefValue::get(II->getType()));
3205
3206 if (ConstantInt *RHS = dyn_cast<ConstantInt>(II->getOperand(2))) {
3207 // X + 0 -> {X, false}
3208 if (RHS->isZero()) {
3209 Constant *V[] = {
Chris Lattnercd188e92009-11-29 02:57:29 +00003210 UndefValue::get(II->getOperand(0)->getType()),
Chris Lattner4de84762010-01-04 07:02:48 +00003211 ConstantInt::getFalse(II->getContext())
Chris Lattner2bbac752009-11-26 21:42:47 +00003212 };
Chris Lattner4de84762010-01-04 07:02:48 +00003213 Constant *Struct = ConstantStruct::get(II->getContext(), V, 2, false);
Chris Lattner2bbac752009-11-26 21:42:47 +00003214 return InsertValueInst::Create(Struct, II->getOperand(1), 0);
3215 }
3216 }
3217 break;
3218 case Intrinsic::usub_with_overflow:
3219 case Intrinsic::ssub_with_overflow:
3220 // undef - X -> undef
3221 // X - undef -> undef
3222 if (isa<UndefValue>(II->getOperand(1)) ||
3223 isa<UndefValue>(II->getOperand(2)))
3224 return ReplaceInstUsesWith(CI, UndefValue::get(II->getType()));
3225
3226 if (ConstantInt *RHS = dyn_cast<ConstantInt>(II->getOperand(2))) {
3227 // X - 0 -> {X, false}
3228 if (RHS->isZero()) {
3229 Constant *V[] = {
Chris Lattnercd188e92009-11-29 02:57:29 +00003230 UndefValue::get(II->getOperand(1)->getType()),
Chris Lattner4de84762010-01-04 07:02:48 +00003231 ConstantInt::getFalse(II->getContext())
Chris Lattner2bbac752009-11-26 21:42:47 +00003232 };
Chris Lattner4de84762010-01-04 07:02:48 +00003233 Constant *Struct = ConstantStruct::get(II->getContext(), V, 2, false);
Chris Lattner2bbac752009-11-26 21:42:47 +00003234 return InsertValueInst::Create(Struct, II->getOperand(1), 0);
3235 }
3236 }
3237 break;
3238 case Intrinsic::umul_with_overflow:
3239 case Intrinsic::smul_with_overflow:
3240 // Canonicalize constants into the RHS.
3241 if (isa<Constant>(II->getOperand(1)) &&
3242 !isa<Constant>(II->getOperand(2))) {
3243 Value *LHS = II->getOperand(1);
3244 II->setOperand(1, II->getOperand(2));
3245 II->setOperand(2, LHS);
3246 return II;
3247 }
3248
3249 // X * undef -> undef
3250 if (isa<UndefValue>(II->getOperand(2)))
3251 return ReplaceInstUsesWith(CI, UndefValue::get(II->getType()));
3252
3253 if (ConstantInt *RHSI = dyn_cast<ConstantInt>(II->getOperand(2))) {
3254 // X*0 -> {0, false}
3255 if (RHSI->isZero())
3256 return ReplaceInstUsesWith(CI, Constant::getNullValue(II->getType()));
3257
3258 // X * 1 -> {X, false}
3259 if (RHSI->equalsInt(1)) {
Chris Lattnercd188e92009-11-29 02:57:29 +00003260 Constant *V[] = {
3261 UndefValue::get(II->getOperand(1)->getType()),
Chris Lattner4de84762010-01-04 07:02:48 +00003262 ConstantInt::getFalse(II->getContext())
Chris Lattnercd188e92009-11-29 02:57:29 +00003263 };
Chris Lattner4de84762010-01-04 07:02:48 +00003264 Constant *Struct = ConstantStruct::get(II->getContext(), V, 2, false);
Chris Lattnercd188e92009-11-29 02:57:29 +00003265 return InsertValueInst::Create(Struct, II->getOperand(1), 0);
Chris Lattner2bbac752009-11-26 21:42:47 +00003266 }
3267 }
3268 break;
Chris Lattner0521e3c2008-06-18 04:33:20 +00003269 case Intrinsic::ppc_altivec_lvx:
3270 case Intrinsic::ppc_altivec_lvxl:
3271 case Intrinsic::x86_sse_loadu_ps:
3272 case Intrinsic::x86_sse2_loadu_pd:
3273 case Intrinsic::x86_sse2_loadu_dq:
3274 // Turn PPC lvx -> load if the pointer is known aligned.
3275 // Turn X86 loadups -> load if the pointer is known aligned.
3276 if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
Chris Lattner08142f22009-08-30 19:47:22 +00003277 Value *Ptr = Builder->CreateBitCast(II->getOperand(1),
3278 PointerType::getUnqual(II->getType()));
Chris Lattner0521e3c2008-06-18 04:33:20 +00003279 return new LoadInst(Ptr);
Chris Lattner867b99f2006-10-05 06:55:50 +00003280 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00003281 break;
3282 case Intrinsic::ppc_altivec_stvx:
3283 case Intrinsic::ppc_altivec_stvxl:
3284 // Turn stvx -> store if the pointer is known aligned.
3285 if (GetOrEnforceKnownAlignment(II->getOperand(2), 16) >= 16) {
3286 const Type *OpPtrTy =
Owen Andersondebcb012009-07-29 22:17:13 +00003287 PointerType::getUnqual(II->getOperand(1)->getType());
Chris Lattner08142f22009-08-30 19:47:22 +00003288 Value *Ptr = Builder->CreateBitCast(II->getOperand(2), OpPtrTy);
Chris Lattner0521e3c2008-06-18 04:33:20 +00003289 return new StoreInst(II->getOperand(1), Ptr);
3290 }
3291 break;
3292 case Intrinsic::x86_sse_storeu_ps:
3293 case Intrinsic::x86_sse2_storeu_pd:
3294 case Intrinsic::x86_sse2_storeu_dq:
Chris Lattner0521e3c2008-06-18 04:33:20 +00003295 // Turn X86 storeu -> store if the pointer is known aligned.
3296 if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
3297 const Type *OpPtrTy =
Owen Andersondebcb012009-07-29 22:17:13 +00003298 PointerType::getUnqual(II->getOperand(2)->getType());
Chris Lattner08142f22009-08-30 19:47:22 +00003299 Value *Ptr = Builder->CreateBitCast(II->getOperand(1), OpPtrTy);
Chris Lattner0521e3c2008-06-18 04:33:20 +00003300 return new StoreInst(II->getOperand(2), Ptr);
3301 }
3302 break;
3303
3304 case Intrinsic::x86_sse_cvttss2si: {
3305 // These intrinsics only demands the 0th element of its input vector. If
3306 // we can simplify the input based on that, do so now.
Evan Cheng388df622009-02-03 10:05:09 +00003307 unsigned VWidth =
3308 cast<VectorType>(II->getOperand(1)->getType())->getNumElements();
3309 APInt DemandedElts(VWidth, 1);
3310 APInt UndefElts(VWidth, 0);
3311 if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
Chris Lattner0521e3c2008-06-18 04:33:20 +00003312 UndefElts)) {
3313 II->setOperand(1, V);
3314 return II;
3315 }
3316 break;
3317 }
3318
3319 case Intrinsic::ppc_altivec_vperm:
3320 // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
3321 if (ConstantVector *Mask = dyn_cast<ConstantVector>(II->getOperand(3))) {
3322 assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
Chris Lattner867b99f2006-10-05 06:55:50 +00003323
Chris Lattner0521e3c2008-06-18 04:33:20 +00003324 // Check that all of the elements are integer constants or undefs.
3325 bool AllEltsOk = true;
3326 for (unsigned i = 0; i != 16; ++i) {
3327 if (!isa<ConstantInt>(Mask->getOperand(i)) &&
3328 !isa<UndefValue>(Mask->getOperand(i))) {
3329 AllEltsOk = false;
3330 break;
3331 }
3332 }
3333
3334 if (AllEltsOk) {
3335 // Cast the input vectors to byte vectors.
Chris Lattner08142f22009-08-30 19:47:22 +00003336 Value *Op0 = Builder->CreateBitCast(II->getOperand(1), Mask->getType());
3337 Value *Op1 = Builder->CreateBitCast(II->getOperand(2), Mask->getType());
Owen Anderson9e9a0d52009-07-30 23:03:37 +00003338 Value *Result = UndefValue::get(Op0->getType());
Chris Lattnere2ed0572006-04-06 19:19:17 +00003339
Chris Lattner0521e3c2008-06-18 04:33:20 +00003340 // Only extract each element once.
3341 Value *ExtractedElts[32];
3342 memset(ExtractedElts, 0, sizeof(ExtractedElts));
3343
Chris Lattnere2ed0572006-04-06 19:19:17 +00003344 for (unsigned i = 0; i != 16; ++i) {
Chris Lattner0521e3c2008-06-18 04:33:20 +00003345 if (isa<UndefValue>(Mask->getOperand(i)))
3346 continue;
3347 unsigned Idx=cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
3348 Idx &= 31; // Match the hardware behavior.
3349
3350 if (ExtractedElts[Idx] == 0) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +00003351 ExtractedElts[Idx] =
3352 Builder->CreateExtractElement(Idx < 16 ? Op0 : Op1,
Chris Lattner4de84762010-01-04 07:02:48 +00003353 ConstantInt::get(Type::getInt32Ty(II->getContext()),
3354 Idx&15, false), "tmp");
Chris Lattnere2ed0572006-04-06 19:19:17 +00003355 }
Chris Lattnere2ed0572006-04-06 19:19:17 +00003356
Chris Lattner0521e3c2008-06-18 04:33:20 +00003357 // Insert this value into the result vector.
Chris Lattnerf925cbd2009-08-30 18:50:58 +00003358 Result = Builder->CreateInsertElement(Result, ExtractedElts[Idx],
Chris Lattner4de84762010-01-04 07:02:48 +00003359 ConstantInt::get(Type::getInt32Ty(II->getContext()),
3360 i, false), "tmp");
Chris Lattnere2ed0572006-04-06 19:19:17 +00003361 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00003362 return CastInst::Create(Instruction::BitCast, Result, CI.getType());
Chris Lattnere2ed0572006-04-06 19:19:17 +00003363 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00003364 }
3365 break;
Chris Lattnere2ed0572006-04-06 19:19:17 +00003366
Chris Lattner0521e3c2008-06-18 04:33:20 +00003367 case Intrinsic::stackrestore: {
3368 // If the save is right next to the restore, remove the restore. This can
3369 // happen when variable allocas are DCE'd.
3370 if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
3371 if (SS->getIntrinsicID() == Intrinsic::stacksave) {
3372 BasicBlock::iterator BI = SS;
3373 if (&*++BI == II)
3374 return EraseInstFromFunction(CI);
Chris Lattnera728ddc2006-01-13 21:28:09 +00003375 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00003376 }
3377
3378 // Scan down this block to see if there is another stack restore in the
3379 // same block without an intervening call/alloca.
3380 BasicBlock::iterator BI = II;
3381 TerminatorInst *TI = II->getParent()->getTerminator();
3382 bool CannotRemove = false;
3383 for (++BI; &*BI != TI; ++BI) {
Victor Hernandez83d63912009-09-18 22:35:49 +00003384 if (isa<AllocaInst>(BI) || isMalloc(BI)) {
Chris Lattner0521e3c2008-06-18 04:33:20 +00003385 CannotRemove = true;
3386 break;
3387 }
Chris Lattneraa0bf522008-06-25 05:59:28 +00003388 if (CallInst *BCI = dyn_cast<CallInst>(BI)) {
3389 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(BCI)) {
3390 // If there is a stackrestore below this one, remove this one.
3391 if (II->getIntrinsicID() == Intrinsic::stackrestore)
3392 return EraseInstFromFunction(CI);
3393 // Otherwise, ignore the intrinsic.
3394 } else {
3395 // If we found a non-intrinsic call, we can't remove the stack
3396 // restore.
Chris Lattnerbf1d8a72008-02-18 06:12:38 +00003397 CannotRemove = true;
3398 break;
3399 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00003400 }
Chris Lattnera728ddc2006-01-13 21:28:09 +00003401 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00003402
3403 // If the stack restore is in a return/unwind block and if there are no
3404 // allocas or calls between the restore and the return, nuke the restore.
3405 if (!CannotRemove && (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)))
3406 return EraseInstFromFunction(CI);
3407 break;
3408 }
Chris Lattner35b9e482004-10-12 04:52:52 +00003409 }
3410
Chris Lattner8b0ea312006-01-13 20:11:04 +00003411 return visitCallSite(II);
Chris Lattner9fe38862003-06-19 17:00:31 +00003412}
3413
3414// InvokeInst simplification
3415//
3416Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
Chris Lattnera44d8a22003-10-07 22:32:43 +00003417 return visitCallSite(&II);
Chris Lattner9fe38862003-06-19 17:00:31 +00003418}
3419
Dale Johannesenda30ccb2008-04-25 21:16:07 +00003420/// isSafeToEliminateVarargsCast - If this cast does not affect the value
3421/// passed through the varargs area, we can eliminate the use of the cast.
Dale Johannesen1f530a52008-04-23 18:34:37 +00003422static bool isSafeToEliminateVarargsCast(const CallSite CS,
3423 const CastInst * const CI,
3424 const TargetData * const TD,
3425 const int ix) {
3426 if (!CI->isLosslessCast())
3427 return false;
3428
3429 // The size of ByVal arguments is derived from the type, so we
3430 // can't change to a type with a different size. If the size were
3431 // passed explicitly we could avoid this check.
Devang Patel05988662008-09-25 21:00:45 +00003432 if (!CS.paramHasAttr(ix, Attribute::ByVal))
Dale Johannesen1f530a52008-04-23 18:34:37 +00003433 return true;
3434
3435 const Type* SrcTy =
3436 cast<PointerType>(CI->getOperand(0)->getType())->getElementType();
3437 const Type* DstTy = cast<PointerType>(CI->getType())->getElementType();
3438 if (!SrcTy->isSized() || !DstTy->isSized())
3439 return false;
Dan Gohmance9fe9f2009-07-21 23:21:54 +00003440 if (!TD || TD->getTypeAllocSize(SrcTy) != TD->getTypeAllocSize(DstTy))
Dale Johannesen1f530a52008-04-23 18:34:37 +00003441 return false;
3442 return true;
3443}
3444
Chris Lattnera44d8a22003-10-07 22:32:43 +00003445// visitCallSite - Improvements for call and invoke instructions.
3446//
3447Instruction *InstCombiner::visitCallSite(CallSite CS) {
Chris Lattner6c266db2003-10-07 22:54:13 +00003448 bool Changed = false;
3449
3450 // If the callee is a constexpr cast of a function, attempt to move the cast
3451 // to the arguments of the call/invoke.
Chris Lattnera44d8a22003-10-07 22:32:43 +00003452 if (transformConstExprCastCall(CS)) return 0;
3453
Chris Lattner6c266db2003-10-07 22:54:13 +00003454 Value *Callee = CS.getCalledValue();
Chris Lattnere87597f2004-10-16 18:11:37 +00003455
Chris Lattner08b22ec2005-05-13 07:09:09 +00003456 if (Function *CalleeF = dyn_cast<Function>(Callee))
3457 if (CalleeF->getCallingConv() != CS.getCallingConv()) {
3458 Instruction *OldCall = CS.getInstruction();
3459 // If the call and callee calling conventions don't match, this call must
3460 // be unreachable, as the call is undefined.
Chris Lattner4de84762010-01-04 07:02:48 +00003461 new StoreInst(ConstantInt::getTrue(Callee->getContext()),
3462 UndefValue::get(Type::getInt1PtrTy(Callee->getContext())),
Owen Andersond672ecb2009-07-03 00:17:18 +00003463 OldCall);
Devang Patel228ebd02009-10-13 22:56:32 +00003464 // If OldCall dues not return void then replaceAllUsesWith undef.
3465 // This allows ValueHandlers and custom metadata to adjust itself.
Devang Patel9674d152009-10-14 17:29:00 +00003466 if (!OldCall->getType()->isVoidTy())
Devang Patel228ebd02009-10-13 22:56:32 +00003467 OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
Chris Lattner08b22ec2005-05-13 07:09:09 +00003468 if (isa<CallInst>(OldCall)) // Not worth removing an invoke here.
3469 return EraseInstFromFunction(*OldCall);
3470 return 0;
3471 }
3472
Chris Lattner17be6352004-10-18 02:59:09 +00003473 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
3474 // This instruction is not reachable, just remove it. We insert a store to
3475 // undef so that we know that this code is not reachable, despite the fact
3476 // that we can't modify the CFG here.
Chris Lattner4de84762010-01-04 07:02:48 +00003477 new StoreInst(ConstantInt::getTrue(Callee->getContext()),
3478 UndefValue::get(Type::getInt1PtrTy(Callee->getContext())),
Chris Lattner17be6352004-10-18 02:59:09 +00003479 CS.getInstruction());
3480
Devang Patel228ebd02009-10-13 22:56:32 +00003481 // If CS dues not return void then replaceAllUsesWith undef.
3482 // This allows ValueHandlers and custom metadata to adjust itself.
Devang Patel9674d152009-10-14 17:29:00 +00003483 if (!CS.getInstruction()->getType()->isVoidTy())
Devang Patel228ebd02009-10-13 22:56:32 +00003484 CS.getInstruction()->
3485 replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
Chris Lattner17be6352004-10-18 02:59:09 +00003486
3487 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
3488 // Don't break the CFG, insert a dummy cond branch.
Gabor Greif051a9502008-04-06 20:25:17 +00003489 BranchInst::Create(II->getNormalDest(), II->getUnwindDest(),
Chris Lattner4de84762010-01-04 07:02:48 +00003490 ConstantInt::getTrue(Callee->getContext()), II);
Chris Lattnere87597f2004-10-16 18:11:37 +00003491 }
Chris Lattner17be6352004-10-18 02:59:09 +00003492 return EraseInstFromFunction(*CS.getInstruction());
3493 }
Chris Lattnere87597f2004-10-16 18:11:37 +00003494
Duncan Sandscdb6d922007-09-17 10:26:40 +00003495 if (BitCastInst *BC = dyn_cast<BitCastInst>(Callee))
3496 if (IntrinsicInst *In = dyn_cast<IntrinsicInst>(BC->getOperand(0)))
3497 if (In->getIntrinsicID() == Intrinsic::init_trampoline)
3498 return transformCallThroughTrampoline(CS);
3499
Chris Lattner6c266db2003-10-07 22:54:13 +00003500 const PointerType *PTy = cast<PointerType>(Callee->getType());
3501 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
3502 if (FTy->isVarArg()) {
Dale Johannesen63e7eb42008-04-23 01:03:05 +00003503 int ix = FTy->getNumParams() + (isa<InvokeInst>(Callee) ? 3 : 1);
Chris Lattner6c266db2003-10-07 22:54:13 +00003504 // See if we can optimize any arguments passed through the varargs area of
3505 // the call.
3506 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
Dale Johannesen1f530a52008-04-23 18:34:37 +00003507 E = CS.arg_end(); I != E; ++I, ++ix) {
3508 CastInst *CI = dyn_cast<CastInst>(*I);
3509 if (CI && isSafeToEliminateVarargsCast(CS, CI, TD, ix)) {
3510 *I = CI->getOperand(0);
3511 Changed = true;
Chris Lattner6c266db2003-10-07 22:54:13 +00003512 }
Dale Johannesen1f530a52008-04-23 18:34:37 +00003513 }
Chris Lattner6c266db2003-10-07 22:54:13 +00003514 }
Misha Brukmanfd939082005-04-21 23:48:37 +00003515
Duncan Sandsf0c33542007-12-19 21:13:37 +00003516 if (isa<InlineAsm>(Callee) && !CS.doesNotThrow()) {
Duncan Sandsece2c042007-12-16 15:51:49 +00003517 // Inline asm calls cannot throw - mark them 'nounwind'.
Duncan Sandsf0c33542007-12-19 21:13:37 +00003518 CS.setDoesNotThrow();
Duncan Sandsece2c042007-12-16 15:51:49 +00003519 Changed = true;
3520 }
3521
Chris Lattner6c266db2003-10-07 22:54:13 +00003522 return Changed ? CS.getInstruction() : 0;
Chris Lattnera44d8a22003-10-07 22:32:43 +00003523}
3524
Chris Lattner9fe38862003-06-19 17:00:31 +00003525// transformConstExprCastCall - If the callee is a constexpr cast of a function,
3526// attempt to move the cast to the arguments of the call/invoke.
3527//
3528bool InstCombiner::transformConstExprCastCall(CallSite CS) {
3529 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
3530 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
Reid Spencer3da59db2006-11-27 01:05:10 +00003531 if (CE->getOpcode() != Instruction::BitCast ||
3532 !isa<Function>(CE->getOperand(0)))
Chris Lattner9fe38862003-06-19 17:00:31 +00003533 return false;
Reid Spencer8863f182004-07-18 00:38:32 +00003534 Function *Callee = cast<Function>(CE->getOperand(0));
Chris Lattner9fe38862003-06-19 17:00:31 +00003535 Instruction *Caller = CS.getInstruction();
Devang Patel05988662008-09-25 21:00:45 +00003536 const AttrListPtr &CallerPAL = CS.getAttributes();
Chris Lattner9fe38862003-06-19 17:00:31 +00003537
3538 // Okay, this is a cast from a function to a different type. Unless doing so
3539 // would cause a type conversion of one of our arguments, change this call to
3540 // be a direct call with arguments casted to the appropriate types.
3541 //
3542 const FunctionType *FT = Callee->getFunctionType();
3543 const Type *OldRetTy = Caller->getType();
Duncan Sandsf413cdf2008-06-01 07:38:42 +00003544 const Type *NewRetTy = FT->getReturnType();
Chris Lattner9fe38862003-06-19 17:00:31 +00003545
Duncan Sandsf413cdf2008-06-01 07:38:42 +00003546 if (isa<StructType>(NewRetTy))
Devang Patel75e6f022008-03-11 18:04:06 +00003547 return false; // TODO: Handle multiple return values.
3548
Chris Lattnerf78616b2004-01-14 06:06:08 +00003549 // Check to see if we are changing the return type...
Duncan Sandsf413cdf2008-06-01 07:38:42 +00003550 if (OldRetTy != NewRetTy) {
Bill Wendlinga6c31122008-05-14 22:45:20 +00003551 if (Callee->isDeclaration() &&
Duncan Sandsf413cdf2008-06-01 07:38:42 +00003552 // Conversion is ok if changing from one pointer type to another or from
3553 // a pointer to an integer of the same size.
Dan Gohmance9fe9f2009-07-21 23:21:54 +00003554 !((isa<PointerType>(OldRetTy) || !TD ||
Owen Anderson1d0be152009-08-13 21:58:54 +00003555 OldRetTy == TD->getIntPtrType(Caller->getContext())) &&
Dan Gohmance9fe9f2009-07-21 23:21:54 +00003556 (isa<PointerType>(NewRetTy) || !TD ||
Owen Anderson1d0be152009-08-13 21:58:54 +00003557 NewRetTy == TD->getIntPtrType(Caller->getContext()))))
Chris Lattnerec479922007-01-06 02:09:32 +00003558 return false; // Cannot transform this return value.
Chris Lattnerf78616b2004-01-14 06:06:08 +00003559
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00003560 if (!Caller->use_empty() &&
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00003561 // void -> non-void is handled specially
Devang Patel9674d152009-10-14 17:29:00 +00003562 !NewRetTy->isVoidTy() && !CastInst::isCastable(NewRetTy, OldRetTy))
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00003563 return false; // Cannot transform this return value.
3564
Chris Lattner58d74912008-03-12 17:45:29 +00003565 if (!CallerPAL.isEmpty() && !Caller->use_empty()) {
Devang Patel19c87462008-09-26 22:53:05 +00003566 Attributes RAttrs = CallerPAL.getRetAttributes();
Devang Patel05988662008-09-25 21:00:45 +00003567 if (RAttrs & Attribute::typeIncompatible(NewRetTy))
Duncan Sands6c3470e2008-01-07 17:16:06 +00003568 return false; // Attribute not compatible with transformed value.
3569 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +00003570
Chris Lattnerf78616b2004-01-14 06:06:08 +00003571 // If the callsite is an invoke instruction, and the return value is used by
3572 // a PHI node in a successor, we cannot change the return type of the call
3573 // because there is no place to put the cast instruction (without breaking
3574 // the critical edge). Bail out in this case.
3575 if (!Caller->use_empty())
3576 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
3577 for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
3578 UI != E; ++UI)
3579 if (PHINode *PN = dyn_cast<PHINode>(*UI))
3580 if (PN->getParent() == II->getNormalDest() ||
Chris Lattneraeb2a1d2004-02-08 21:44:31 +00003581 PN->getParent() == II->getUnwindDest())
Chris Lattnerf78616b2004-01-14 06:06:08 +00003582 return false;
3583 }
Chris Lattner9fe38862003-06-19 17:00:31 +00003584
3585 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
3586 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
Misha Brukmanfd939082005-04-21 23:48:37 +00003587
Chris Lattner9fe38862003-06-19 17:00:31 +00003588 CallSite::arg_iterator AI = CS.arg_begin();
3589 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
3590 const Type *ParamTy = FT->getParamType(i);
Andrew Lenharthb8e604c2006-06-28 01:01:52 +00003591 const Type *ActTy = (*AI)->getType();
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00003592
3593 if (!CastInst::isCastable(ActTy, ParamTy))
Duncan Sandsad9a9e12008-01-06 18:27:01 +00003594 return false; // Cannot transform this parameter value.
3595
Devang Patel19c87462008-09-26 22:53:05 +00003596 if (CallerPAL.getParamAttributes(i + 1)
3597 & Attribute::typeIncompatible(ParamTy))
Chris Lattner58d74912008-03-12 17:45:29 +00003598 return false; // Attribute not compatible with transformed value.
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00003599
Duncan Sandsf413cdf2008-06-01 07:38:42 +00003600 // Converting from one pointer type to another or between a pointer and an
3601 // integer of the same size is safe even if we do not have a body.
Chris Lattnerec479922007-01-06 02:09:32 +00003602 bool isConvertible = ActTy == ParamTy ||
Owen Anderson1d0be152009-08-13 21:58:54 +00003603 (TD && ((isa<PointerType>(ParamTy) ||
3604 ParamTy == TD->getIntPtrType(Caller->getContext())) &&
3605 (isa<PointerType>(ActTy) ||
3606 ActTy == TD->getIntPtrType(Caller->getContext()))));
Reid Spencer5cbf9852007-01-30 20:08:39 +00003607 if (Callee->isDeclaration() && !isConvertible) return false;
Chris Lattner9fe38862003-06-19 17:00:31 +00003608 }
3609
3610 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
Reid Spencer5cbf9852007-01-30 20:08:39 +00003611 Callee->isDeclaration())
Chris Lattner58d74912008-03-12 17:45:29 +00003612 return false; // Do not delete arguments unless we have a function body.
Chris Lattner9fe38862003-06-19 17:00:31 +00003613
Chris Lattner58d74912008-03-12 17:45:29 +00003614 if (FT->getNumParams() < NumActualArgs && FT->isVarArg() &&
3615 !CallerPAL.isEmpty())
Duncan Sandsad9a9e12008-01-06 18:27:01 +00003616 // In this case we have more arguments than the new function type, but we
Duncan Sandse1e520f2008-01-13 08:02:44 +00003617 // won't be dropping them. Check that these extra arguments have attributes
3618 // that are compatible with being a vararg call argument.
Chris Lattner58d74912008-03-12 17:45:29 +00003619 for (unsigned i = CallerPAL.getNumSlots(); i; --i) {
3620 if (CallerPAL.getSlot(i - 1).Index <= FT->getNumParams())
Duncan Sandse1e520f2008-01-13 08:02:44 +00003621 break;
Devang Pateleaf42ab2008-09-23 23:03:40 +00003622 Attributes PAttrs = CallerPAL.getSlot(i - 1).Attrs;
Devang Patel05988662008-09-25 21:00:45 +00003623 if (PAttrs & Attribute::VarArgsIncompatible)
Duncan Sandse1e520f2008-01-13 08:02:44 +00003624 return false;
3625 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +00003626
Chris Lattner9fe38862003-06-19 17:00:31 +00003627 // Okay, we decided that this is a safe thing to do: go ahead and start
3628 // inserting cast instructions as necessary...
3629 std::vector<Value*> Args;
3630 Args.reserve(NumActualArgs);
Devang Patel05988662008-09-25 21:00:45 +00003631 SmallVector<AttributeWithIndex, 8> attrVec;
Duncan Sandsad9a9e12008-01-06 18:27:01 +00003632 attrVec.reserve(NumCommonArgs);
3633
3634 // Get any return attributes.
Devang Patel19c87462008-09-26 22:53:05 +00003635 Attributes RAttrs = CallerPAL.getRetAttributes();
Duncan Sandsad9a9e12008-01-06 18:27:01 +00003636
3637 // If the return value is not being used, the type may not be compatible
3638 // with the existing attributes. Wipe out any problematic attributes.
Devang Patel05988662008-09-25 21:00:45 +00003639 RAttrs &= ~Attribute::typeIncompatible(NewRetTy);
Duncan Sandsad9a9e12008-01-06 18:27:01 +00003640
3641 // Add the new return attributes.
3642 if (RAttrs)
Devang Patel05988662008-09-25 21:00:45 +00003643 attrVec.push_back(AttributeWithIndex::get(0, RAttrs));
Chris Lattner9fe38862003-06-19 17:00:31 +00003644
3645 AI = CS.arg_begin();
3646 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
3647 const Type *ParamTy = FT->getParamType(i);
3648 if ((*AI)->getType() == ParamTy) {
3649 Args.push_back(*AI);
3650 } else {
Reid Spencer8a903db2006-12-18 08:47:13 +00003651 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
Reid Spencerc5b206b2006-12-31 05:48:39 +00003652 false, ParamTy, false);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00003653 Args.push_back(Builder->CreateCast(opcode, *AI, ParamTy, "tmp"));
Chris Lattner9fe38862003-06-19 17:00:31 +00003654 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +00003655
3656 // Add any parameter attributes.
Devang Patel19c87462008-09-26 22:53:05 +00003657 if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
Devang Patel05988662008-09-25 21:00:45 +00003658 attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
Chris Lattner9fe38862003-06-19 17:00:31 +00003659 }
3660
3661 // If the function takes more arguments than the call was taking, add them
Chris Lattnerf925cbd2009-08-30 18:50:58 +00003662 // now.
Chris Lattner9fe38862003-06-19 17:00:31 +00003663 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
Owen Andersona7235ea2009-07-31 20:28:14 +00003664 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
Chris Lattner9fe38862003-06-19 17:00:31 +00003665
Chris Lattnerf925cbd2009-08-30 18:50:58 +00003666 // If we are removing arguments to the function, emit an obnoxious warning.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00003667 if (FT->getNumParams() < NumActualArgs) {
Chris Lattner9fe38862003-06-19 17:00:31 +00003668 if (!FT->isVarArg()) {
Daniel Dunbarce63ffb2009-07-25 00:23:56 +00003669 errs() << "WARNING: While resolving call to function '"
3670 << Callee->getName() << "' arguments were dropped!\n";
Chris Lattner9fe38862003-06-19 17:00:31 +00003671 } else {
Chris Lattnerf925cbd2009-08-30 18:50:58 +00003672 // Add all of the arguments in their promoted form to the arg list.
Chris Lattner9fe38862003-06-19 17:00:31 +00003673 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
3674 const Type *PTy = getPromotedType((*AI)->getType());
3675 if (PTy != (*AI)->getType()) {
3676 // Must promote to pass through va_arg area!
Chris Lattnerf925cbd2009-08-30 18:50:58 +00003677 Instruction::CastOps opcode =
3678 CastInst::getCastOpcode(*AI, false, PTy, false);
3679 Args.push_back(Builder->CreateCast(opcode, *AI, PTy, "tmp"));
Chris Lattner9fe38862003-06-19 17:00:31 +00003680 } else {
3681 Args.push_back(*AI);
3682 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +00003683
Duncan Sandse1e520f2008-01-13 08:02:44 +00003684 // Add any parameter attributes.
Devang Patel19c87462008-09-26 22:53:05 +00003685 if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
Devang Patel05988662008-09-25 21:00:45 +00003686 attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
Duncan Sandse1e520f2008-01-13 08:02:44 +00003687 }
Chris Lattner9fe38862003-06-19 17:00:31 +00003688 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00003689 }
Chris Lattner9fe38862003-06-19 17:00:31 +00003690
Devang Patel19c87462008-09-26 22:53:05 +00003691 if (Attributes FnAttrs = CallerPAL.getFnAttributes())
3692 attrVec.push_back(AttributeWithIndex::get(~0, FnAttrs));
3693
Devang Patel9674d152009-10-14 17:29:00 +00003694 if (NewRetTy->isVoidTy())
Chris Lattner6934a042007-02-11 01:23:03 +00003695 Caller->setName(""); // Void type should not have a name.
Chris Lattner9fe38862003-06-19 17:00:31 +00003696
Eric Christophera66297a2009-07-25 02:45:27 +00003697 const AttrListPtr &NewCallerPAL = AttrListPtr::get(attrVec.begin(),
3698 attrVec.end());
Duncan Sandsad9a9e12008-01-06 18:27:01 +00003699
Chris Lattner9fe38862003-06-19 17:00:31 +00003700 Instruction *NC;
3701 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Gabor Greif051a9502008-04-06 20:25:17 +00003702 NC = InvokeInst::Create(Callee, II->getNormalDest(), II->getUnwindDest(),
Gabor Greifb1dbcd82008-05-15 10:04:30 +00003703 Args.begin(), Args.end(),
3704 Caller->getName(), Caller);
Reid Spencered3fa852007-07-30 19:53:57 +00003705 cast<InvokeInst>(NC)->setCallingConv(II->getCallingConv());
Devang Patel05988662008-09-25 21:00:45 +00003706 cast<InvokeInst>(NC)->setAttributes(NewCallerPAL);
Chris Lattner9fe38862003-06-19 17:00:31 +00003707 } else {
Gabor Greif051a9502008-04-06 20:25:17 +00003708 NC = CallInst::Create(Callee, Args.begin(), Args.end(),
3709 Caller->getName(), Caller);
Duncan Sandsdc024672007-11-27 13:23:08 +00003710 CallInst *CI = cast<CallInst>(Caller);
3711 if (CI->isTailCall())
Chris Lattnera9e92112005-05-06 06:48:21 +00003712 cast<CallInst>(NC)->setTailCall();
Duncan Sandsdc024672007-11-27 13:23:08 +00003713 cast<CallInst>(NC)->setCallingConv(CI->getCallingConv());
Devang Patel05988662008-09-25 21:00:45 +00003714 cast<CallInst>(NC)->setAttributes(NewCallerPAL);
Chris Lattner9fe38862003-06-19 17:00:31 +00003715 }
3716
Chris Lattner6934a042007-02-11 01:23:03 +00003717 // Insert a cast of the return type as necessary.
Chris Lattner9fe38862003-06-19 17:00:31 +00003718 Value *NV = NC;
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00003719 if (OldRetTy != NV->getType() && !Caller->use_empty()) {
Devang Patel9674d152009-10-14 17:29:00 +00003720 if (!NV->getType()->isVoidTy()) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00003721 Instruction::CastOps opcode = CastInst::getCastOpcode(NC, false,
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00003722 OldRetTy, false);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003723 NV = NC = CastInst::Create(opcode, NC, OldRetTy, "tmp");
Chris Lattnerbb609042003-10-30 00:46:41 +00003724
3725 // If this is an invoke instruction, we should insert it after the first
3726 // non-phi, instruction in the normal successor block.
3727 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Dan Gohman02dea8b2008-05-23 21:05:58 +00003728 BasicBlock::iterator I = II->getNormalDest()->getFirstNonPHI();
Chris Lattnerbb609042003-10-30 00:46:41 +00003729 InsertNewInstBefore(NC, *I);
3730 } else {
3731 // Otherwise, it's a call, just insert cast right after the call instr
3732 InsertNewInstBefore(NC, *Caller);
3733 }
Chris Lattnere5ecdb52009-08-30 06:22:51 +00003734 Worklist.AddUsersToWorkList(*Caller);
Chris Lattner9fe38862003-06-19 17:00:31 +00003735 } else {
Owen Anderson9e9a0d52009-07-30 23:03:37 +00003736 NV = UndefValue::get(Caller->getType());
Chris Lattner9fe38862003-06-19 17:00:31 +00003737 }
3738 }
3739
Devang Patel1bf5ebc2009-10-13 21:41:20 +00003740
Chris Lattner931f8f32009-08-31 05:17:58 +00003741 if (!Caller->use_empty())
Chris Lattner9fe38862003-06-19 17:00:31 +00003742 Caller->replaceAllUsesWith(NV);
Chris Lattner931f8f32009-08-31 05:17:58 +00003743
3744 EraseInstFromFunction(*Caller);
Chris Lattner9fe38862003-06-19 17:00:31 +00003745 return true;
3746}
3747
Duncan Sandscdb6d922007-09-17 10:26:40 +00003748// transformCallThroughTrampoline - Turn a call to a function created by the
3749// init_trampoline intrinsic into a direct call to the underlying function.
3750//
3751Instruction *InstCombiner::transformCallThroughTrampoline(CallSite CS) {
3752 Value *Callee = CS.getCalledValue();
3753 const PointerType *PTy = cast<PointerType>(Callee->getType());
3754 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
Devang Patel05988662008-09-25 21:00:45 +00003755 const AttrListPtr &Attrs = CS.getAttributes();
Duncan Sandsb0c9b932008-01-14 19:52:09 +00003756
3757 // If the call already has the 'nest' attribute somewhere then give up -
3758 // otherwise 'nest' would occur twice after splicing in the chain.
Devang Patel05988662008-09-25 21:00:45 +00003759 if (Attrs.hasAttrSomewhere(Attribute::Nest))
Duncan Sandsb0c9b932008-01-14 19:52:09 +00003760 return 0;
Duncan Sandscdb6d922007-09-17 10:26:40 +00003761
3762 IntrinsicInst *Tramp =
3763 cast<IntrinsicInst>(cast<BitCastInst>(Callee)->getOperand(0));
3764
Anton Korobeynikov0b12ecf2008-05-07 22:54:15 +00003765 Function *NestF = cast<Function>(Tramp->getOperand(2)->stripPointerCasts());
Duncan Sandscdb6d922007-09-17 10:26:40 +00003766 const PointerType *NestFPTy = cast<PointerType>(NestF->getType());
3767 const FunctionType *NestFTy = cast<FunctionType>(NestFPTy->getElementType());
3768
Devang Patel05988662008-09-25 21:00:45 +00003769 const AttrListPtr &NestAttrs = NestF->getAttributes();
Chris Lattner58d74912008-03-12 17:45:29 +00003770 if (!NestAttrs.isEmpty()) {
Duncan Sandscdb6d922007-09-17 10:26:40 +00003771 unsigned NestIdx = 1;
3772 const Type *NestTy = 0;
Devang Patel05988662008-09-25 21:00:45 +00003773 Attributes NestAttr = Attribute::None;
Duncan Sandscdb6d922007-09-17 10:26:40 +00003774
3775 // Look for a parameter marked with the 'nest' attribute.
3776 for (FunctionType::param_iterator I = NestFTy->param_begin(),
3777 E = NestFTy->param_end(); I != E; ++NestIdx, ++I)
Devang Patel05988662008-09-25 21:00:45 +00003778 if (NestAttrs.paramHasAttr(NestIdx, Attribute::Nest)) {
Duncan Sandscdb6d922007-09-17 10:26:40 +00003779 // Record the parameter type and any other attributes.
3780 NestTy = *I;
Devang Patel19c87462008-09-26 22:53:05 +00003781 NestAttr = NestAttrs.getParamAttributes(NestIdx);
Duncan Sandscdb6d922007-09-17 10:26:40 +00003782 break;
3783 }
3784
3785 if (NestTy) {
3786 Instruction *Caller = CS.getInstruction();
3787 std::vector<Value*> NewArgs;
3788 NewArgs.reserve(unsigned(CS.arg_end()-CS.arg_begin())+1);
3789
Devang Patel05988662008-09-25 21:00:45 +00003790 SmallVector<AttributeWithIndex, 8> NewAttrs;
Chris Lattner58d74912008-03-12 17:45:29 +00003791 NewAttrs.reserve(Attrs.getNumSlots() + 1);
Duncan Sandsb0c9b932008-01-14 19:52:09 +00003792
Duncan Sandscdb6d922007-09-17 10:26:40 +00003793 // Insert the nest argument into the call argument list, which may
Duncan Sandsb0c9b932008-01-14 19:52:09 +00003794 // mean appending it. Likewise for attributes.
3795
Devang Patel19c87462008-09-26 22:53:05 +00003796 // Add any result attributes.
3797 if (Attributes Attr = Attrs.getRetAttributes())
Devang Patel05988662008-09-25 21:00:45 +00003798 NewAttrs.push_back(AttributeWithIndex::get(0, Attr));
Duncan Sandsb0c9b932008-01-14 19:52:09 +00003799
Duncan Sandscdb6d922007-09-17 10:26:40 +00003800 {
3801 unsigned Idx = 1;
3802 CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
3803 do {
3804 if (Idx == NestIdx) {
Duncan Sandsb0c9b932008-01-14 19:52:09 +00003805 // Add the chain argument and attributes.
Duncan Sandscdb6d922007-09-17 10:26:40 +00003806 Value *NestVal = Tramp->getOperand(3);
3807 if (NestVal->getType() != NestTy)
3808 NestVal = new BitCastInst(NestVal, NestTy, "nest", Caller);
3809 NewArgs.push_back(NestVal);
Devang Patel05988662008-09-25 21:00:45 +00003810 NewAttrs.push_back(AttributeWithIndex::get(NestIdx, NestAttr));
Duncan Sandscdb6d922007-09-17 10:26:40 +00003811 }
3812
3813 if (I == E)
3814 break;
3815
Duncan Sandsb0c9b932008-01-14 19:52:09 +00003816 // Add the original argument and attributes.
Duncan Sandscdb6d922007-09-17 10:26:40 +00003817 NewArgs.push_back(*I);
Devang Patel19c87462008-09-26 22:53:05 +00003818 if (Attributes Attr = Attrs.getParamAttributes(Idx))
Duncan Sandsb0c9b932008-01-14 19:52:09 +00003819 NewAttrs.push_back
Devang Patel05988662008-09-25 21:00:45 +00003820 (AttributeWithIndex::get(Idx + (Idx >= NestIdx), Attr));
Duncan Sandscdb6d922007-09-17 10:26:40 +00003821
3822 ++Idx, ++I;
3823 } while (1);
3824 }
3825
Devang Patel19c87462008-09-26 22:53:05 +00003826 // Add any function attributes.
3827 if (Attributes Attr = Attrs.getFnAttributes())
3828 NewAttrs.push_back(AttributeWithIndex::get(~0, Attr));
3829
Duncan Sandscdb6d922007-09-17 10:26:40 +00003830 // The trampoline may have been bitcast to a bogus type (FTy).
3831 // Handle this by synthesizing a new function type, equal to FTy
Duncan Sandsb0c9b932008-01-14 19:52:09 +00003832 // with the chain parameter inserted.
Duncan Sandscdb6d922007-09-17 10:26:40 +00003833
Duncan Sandscdb6d922007-09-17 10:26:40 +00003834 std::vector<const Type*> NewTypes;
Duncan Sandscdb6d922007-09-17 10:26:40 +00003835 NewTypes.reserve(FTy->getNumParams()+1);
3836
Duncan Sandscdb6d922007-09-17 10:26:40 +00003837 // Insert the chain's type into the list of parameter types, which may
Duncan Sandsb0c9b932008-01-14 19:52:09 +00003838 // mean appending it.
Duncan Sandscdb6d922007-09-17 10:26:40 +00003839 {
3840 unsigned Idx = 1;
3841 FunctionType::param_iterator I = FTy->param_begin(),
3842 E = FTy->param_end();
3843
3844 do {
Duncan Sandsb0c9b932008-01-14 19:52:09 +00003845 if (Idx == NestIdx)
3846 // Add the chain's type.
Duncan Sandscdb6d922007-09-17 10:26:40 +00003847 NewTypes.push_back(NestTy);
Duncan Sandscdb6d922007-09-17 10:26:40 +00003848
3849 if (I == E)
3850 break;
3851
Duncan Sandsb0c9b932008-01-14 19:52:09 +00003852 // Add the original type.
Duncan Sandscdb6d922007-09-17 10:26:40 +00003853 NewTypes.push_back(*I);
Duncan Sandscdb6d922007-09-17 10:26:40 +00003854
3855 ++Idx, ++I;
3856 } while (1);
3857 }
3858
3859 // Replace the trampoline call with a direct call. Let the generic
3860 // code sort out any function type mismatches.
Owen Andersondebcb012009-07-29 22:17:13 +00003861 FunctionType *NewFTy = FunctionType::get(FTy->getReturnType(), NewTypes,
Owen Andersond672ecb2009-07-03 00:17:18 +00003862 FTy->isVarArg());
3863 Constant *NewCallee =
Owen Andersondebcb012009-07-29 22:17:13 +00003864 NestF->getType() == PointerType::getUnqual(NewFTy) ?
Owen Andersonbaf3c402009-07-29 18:55:55 +00003865 NestF : ConstantExpr::getBitCast(NestF,
Owen Andersondebcb012009-07-29 22:17:13 +00003866 PointerType::getUnqual(NewFTy));
Eric Christophera66297a2009-07-25 02:45:27 +00003867 const AttrListPtr &NewPAL = AttrListPtr::get(NewAttrs.begin(),
3868 NewAttrs.end());
Duncan Sandscdb6d922007-09-17 10:26:40 +00003869
3870 Instruction *NewCaller;
3871 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Gabor Greif051a9502008-04-06 20:25:17 +00003872 NewCaller = InvokeInst::Create(NewCallee,
3873 II->getNormalDest(), II->getUnwindDest(),
3874 NewArgs.begin(), NewArgs.end(),
3875 Caller->getName(), Caller);
Duncan Sandscdb6d922007-09-17 10:26:40 +00003876 cast<InvokeInst>(NewCaller)->setCallingConv(II->getCallingConv());
Devang Patel05988662008-09-25 21:00:45 +00003877 cast<InvokeInst>(NewCaller)->setAttributes(NewPAL);
Duncan Sandscdb6d922007-09-17 10:26:40 +00003878 } else {
Gabor Greif051a9502008-04-06 20:25:17 +00003879 NewCaller = CallInst::Create(NewCallee, NewArgs.begin(), NewArgs.end(),
3880 Caller->getName(), Caller);
Duncan Sandscdb6d922007-09-17 10:26:40 +00003881 if (cast<CallInst>(Caller)->isTailCall())
3882 cast<CallInst>(NewCaller)->setTailCall();
3883 cast<CallInst>(NewCaller)->
3884 setCallingConv(cast<CallInst>(Caller)->getCallingConv());
Devang Patel05988662008-09-25 21:00:45 +00003885 cast<CallInst>(NewCaller)->setAttributes(NewPAL);
Duncan Sandscdb6d922007-09-17 10:26:40 +00003886 }
Devang Patel9674d152009-10-14 17:29:00 +00003887 if (!Caller->getType()->isVoidTy())
Duncan Sandscdb6d922007-09-17 10:26:40 +00003888 Caller->replaceAllUsesWith(NewCaller);
3889 Caller->eraseFromParent();
Chris Lattner7a1e9242009-08-30 06:13:40 +00003890 Worklist.Remove(Caller);
Duncan Sandscdb6d922007-09-17 10:26:40 +00003891 return 0;
3892 }
3893 }
3894
3895 // Replace the trampoline call with a direct call. Since there is no 'nest'
3896 // parameter, there is no need to adjust the argument list. Let the generic
3897 // code sort out any function type mismatches.
3898 Constant *NewCallee =
Owen Andersond672ecb2009-07-03 00:17:18 +00003899 NestF->getType() == PTy ? NestF :
Owen Andersonbaf3c402009-07-29 18:55:55 +00003900 ConstantExpr::getBitCast(NestF, PTy);
Duncan Sandscdb6d922007-09-17 10:26:40 +00003901 CS.setCalledFunction(NewCallee);
3902 return CS.getInstruction();
3903}
3904
Reid Spencere4d87aa2006-12-23 06:05:41 +00003905
Chris Lattner473945d2002-05-06 18:06:38 +00003906
Chris Lattner7e708292002-06-25 16:13:24 +00003907Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
Chris Lattnerc514c1f2009-11-27 00:29:05 +00003908 SmallVector<Value*, 8> Ops(GEP.op_begin(), GEP.op_end());
3909
3910 if (Value *V = SimplifyGEPInst(&Ops[0], Ops.size(), TD))
3911 return ReplaceInstUsesWith(GEP, V);
3912
Chris Lattner620ce142004-05-07 22:09:22 +00003913 Value *PtrOp = GEP.getOperand(0);
Chris Lattnerc6bd1952004-02-22 05:25:17 +00003914
Chris Lattnere87597f2004-10-16 18:11:37 +00003915 if (isa<UndefValue>(GEP.getOperand(0)))
Owen Anderson9e9a0d52009-07-30 23:03:37 +00003916 return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00003917
Chris Lattner28977af2004-04-05 01:30:19 +00003918 // Eliminate unneeded casts for indices.
Chris Lattnerccf4b342009-08-30 04:49:01 +00003919 if (TD) {
3920 bool MadeChange = false;
3921 unsigned PtrSize = TD->getPointerSizeInBits();
3922
3923 gep_type_iterator GTI = gep_type_begin(GEP);
3924 for (User::op_iterator I = GEP.op_begin() + 1, E = GEP.op_end();
3925 I != E; ++I, ++GTI) {
3926 if (!isa<SequentialType>(*GTI)) continue;
3927
Chris Lattnercb69a4e2004-04-07 18:38:20 +00003928 // If we are using a wider index than needed for this platform, shrink it
Chris Lattnerccf4b342009-08-30 04:49:01 +00003929 // to what we need. If narrower, sign-extend it to what we need. This
3930 // explicit cast can make subsequent optimizations more obvious.
3931 unsigned OpBits = cast<IntegerType>((*I)->getType())->getBitWidth();
Chris Lattnerccf4b342009-08-30 04:49:01 +00003932 if (OpBits == PtrSize)
3933 continue;
3934
Chris Lattner2345d1d2009-08-30 20:01:10 +00003935 *I = Builder->CreateIntCast(*I, TD->getIntPtrType(GEP.getContext()),true);
Chris Lattnerccf4b342009-08-30 04:49:01 +00003936 MadeChange = true;
Chris Lattner28977af2004-04-05 01:30:19 +00003937 }
Chris Lattnerccf4b342009-08-30 04:49:01 +00003938 if (MadeChange) return &GEP;
Chris Lattnerdb9654e2007-03-25 20:43:09 +00003939 }
Chris Lattner28977af2004-04-05 01:30:19 +00003940
Chris Lattner90ac28c2002-08-02 19:29:35 +00003941 // Combine Indices - If the source pointer to this getelementptr instruction
3942 // is a getelementptr instruction, combine the indices of the two
3943 // getelementptr instructions into a single instruction.
3944 //
Dan Gohmand6aa02d2009-07-28 01:40:03 +00003945 if (GEPOperator *Src = dyn_cast<GEPOperator>(PtrOp)) {
Chris Lattner620ce142004-05-07 22:09:22 +00003946 // Note that if our source is a gep chain itself that we wait for that
3947 // chain to be resolved before we perform this transformation. This
3948 // avoids us creating a TON of code in some cases.
3949 //
Chris Lattnerf9b91bb2009-08-30 05:08:50 +00003950 if (GetElementPtrInst *SrcGEP =
3951 dyn_cast<GetElementPtrInst>(Src->getOperand(0)))
3952 if (SrcGEP->getNumOperands() == 2)
3953 return 0; // Wait until our source is folded to completion.
Chris Lattner620ce142004-05-07 22:09:22 +00003954
Chris Lattner72588fc2007-02-15 22:48:32 +00003955 SmallVector<Value*, 8> Indices;
Chris Lattner620ce142004-05-07 22:09:22 +00003956
3957 // Find out whether the last index in the source GEP is a sequential idx.
3958 bool EndsWithSequential = false;
Chris Lattnerab984842009-08-30 05:30:55 +00003959 for (gep_type_iterator I = gep_type_begin(*Src), E = gep_type_end(*Src);
3960 I != E; ++I)
Chris Lattnerbe97b4e2004-05-08 22:41:42 +00003961 EndsWithSequential = !isa<StructType>(*I);
Misha Brukmanfd939082005-04-21 23:48:37 +00003962
Chris Lattner90ac28c2002-08-02 19:29:35 +00003963 // Can we combine the two pointer arithmetics offsets?
Chris Lattner620ce142004-05-07 22:09:22 +00003964 if (EndsWithSequential) {
Chris Lattnerdecd0812003-03-05 22:33:14 +00003965 // Replace: gep (gep %P, long B), long A, ...
3966 // With: T = long A+B; gep %P, T, ...
3967 //
Chris Lattnerf9b91bb2009-08-30 05:08:50 +00003968 Value *Sum;
3969 Value *SO1 = Src->getOperand(Src->getNumOperands()-1);
3970 Value *GO1 = GEP.getOperand(1);
Owen Andersona7235ea2009-07-31 20:28:14 +00003971 if (SO1 == Constant::getNullValue(SO1->getType())) {
Chris Lattner28977af2004-04-05 01:30:19 +00003972 Sum = GO1;
Owen Andersona7235ea2009-07-31 20:28:14 +00003973 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
Chris Lattner28977af2004-04-05 01:30:19 +00003974 Sum = SO1;
3975 } else {
Chris Lattnerab984842009-08-30 05:30:55 +00003976 // If they aren't the same type, then the input hasn't been processed
3977 // by the loop above yet (which canonicalizes sequential index types to
3978 // intptr_t). Just avoid transforming this until the input has been
3979 // normalized.
3980 if (SO1->getType() != GO1->getType())
3981 return 0;
Chris Lattnerf925cbd2009-08-30 18:50:58 +00003982 Sum = Builder->CreateAdd(SO1, GO1, PtrOp->getName()+".sum");
Chris Lattner28977af2004-04-05 01:30:19 +00003983 }
Chris Lattner620ce142004-05-07 22:09:22 +00003984
Chris Lattnerab984842009-08-30 05:30:55 +00003985 // Update the GEP in place if possible.
Chris Lattnerf9b91bb2009-08-30 05:08:50 +00003986 if (Src->getNumOperands() == 2) {
3987 GEP.setOperand(0, Src->getOperand(0));
Chris Lattner620ce142004-05-07 22:09:22 +00003988 GEP.setOperand(1, Sum);
3989 return &GEP;
Chris Lattner620ce142004-05-07 22:09:22 +00003990 }
Chris Lattnerab984842009-08-30 05:30:55 +00003991 Indices.append(Src->op_begin()+1, Src->op_end()-1);
Chris Lattnerccf4b342009-08-30 04:49:01 +00003992 Indices.push_back(Sum);
Chris Lattnerab984842009-08-30 05:30:55 +00003993 Indices.append(GEP.op_begin()+2, GEP.op_end());
Misha Brukmanfd939082005-04-21 23:48:37 +00003994 } else if (isa<Constant>(*GEP.idx_begin()) &&
Chris Lattner28977af2004-04-05 01:30:19 +00003995 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
Chris Lattnerf9b91bb2009-08-30 05:08:50 +00003996 Src->getNumOperands() != 1) {
Chris Lattner90ac28c2002-08-02 19:29:35 +00003997 // Otherwise we can do the fold if the first index of the GEP is a zero
Chris Lattnerab984842009-08-30 05:30:55 +00003998 Indices.append(Src->op_begin()+1, Src->op_end());
3999 Indices.append(GEP.idx_begin()+1, GEP.idx_end());
Chris Lattner90ac28c2002-08-02 19:29:35 +00004000 }
4001
Dan Gohmanf8dbee72009-09-07 23:54:19 +00004002 if (!Indices.empty())
4003 return (cast<GEPOperator>(&GEP)->isInBounds() &&
4004 Src->isInBounds()) ?
4005 GetElementPtrInst::CreateInBounds(Src->getOperand(0), Indices.begin(),
4006 Indices.end(), GEP.getName()) :
Chris Lattnerf9b91bb2009-08-30 05:08:50 +00004007 GetElementPtrInst::Create(Src->getOperand(0), Indices.begin(),
Chris Lattnerccf4b342009-08-30 04:49:01 +00004008 Indices.end(), GEP.getName());
Chris Lattner6e24d832009-08-30 05:00:50 +00004009 }
4010
Chris Lattnerf9b91bb2009-08-30 05:08:50 +00004011 // Handle gep(bitcast x) and gep(gep x, 0, 0, 0).
4012 if (Value *X = getBitCastOperand(PtrOp)) {
Chris Lattner6e24d832009-08-30 05:00:50 +00004013 assert(isa<PointerType>(X->getType()) && "Must be cast from pointer");
Chris Lattner963f4ba2009-08-30 20:36:46 +00004014
Chris Lattner2de23192009-08-30 20:38:21 +00004015 // If the input bitcast is actually "bitcast(bitcast(x))", then we don't
4016 // want to change the gep until the bitcasts are eliminated.
4017 if (getBitCastOperand(X)) {
4018 Worklist.AddValue(PtrOp);
4019 return 0;
4020 }
4021
Chris Lattnerc514c1f2009-11-27 00:29:05 +00004022 bool HasZeroPointerIndex = false;
4023 if (ConstantInt *C = dyn_cast<ConstantInt>(GEP.getOperand(1)))
4024 HasZeroPointerIndex = C->isZero();
4025
Chris Lattner963f4ba2009-08-30 20:36:46 +00004026 // Transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ...
4027 // into : GEP [10 x i8]* X, i32 0, ...
4028 //
4029 // Likewise, transform: GEP (bitcast i8* X to [0 x i8]*), i32 0, ...
4030 // into : GEP i8* X, ...
4031 //
4032 // This occurs when the program declares an array extern like "int X[];"
Chris Lattner6e24d832009-08-30 05:00:50 +00004033 if (HasZeroPointerIndex) {
Chris Lattnereed48272005-09-13 00:40:14 +00004034 const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
4035 const PointerType *XTy = cast<PointerType>(X->getType());
Duncan Sands5b7cfb02009-03-02 09:18:21 +00004036 if (const ArrayType *CATy =
4037 dyn_cast<ArrayType>(CPTy->getElementType())) {
4038 // GEP (bitcast i8* X to [0 x i8]*), i32 0, ... ?
4039 if (CATy->getElementType() == XTy->getElementType()) {
4040 // -> GEP i8* X, ...
4041 SmallVector<Value*, 8> Indices(GEP.idx_begin()+1, GEP.idx_end());
Dan Gohmanf8dbee72009-09-07 23:54:19 +00004042 return cast<GEPOperator>(&GEP)->isInBounds() ?
4043 GetElementPtrInst::CreateInBounds(X, Indices.begin(), Indices.end(),
4044 GEP.getName()) :
Dan Gohmand6aa02d2009-07-28 01:40:03 +00004045 GetElementPtrInst::Create(X, Indices.begin(), Indices.end(),
4046 GEP.getName());
Chris Lattner963f4ba2009-08-30 20:36:46 +00004047 }
4048
4049 if (const ArrayType *XATy = dyn_cast<ArrayType>(XTy->getElementType())){
Duncan Sands5b7cfb02009-03-02 09:18:21 +00004050 // GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ... ?
Chris Lattnereed48272005-09-13 00:40:14 +00004051 if (CATy->getElementType() == XATy->getElementType()) {
Duncan Sands5b7cfb02009-03-02 09:18:21 +00004052 // -> GEP [10 x i8]* X, i32 0, ...
Chris Lattnereed48272005-09-13 00:40:14 +00004053 // At this point, we know that the cast source type is a pointer
4054 // to an array of the same type as the destination pointer
4055 // array. Because the array type is never stepped over (there
4056 // is a leading zero) we can fold the cast into this GEP.
4057 GEP.setOperand(0, X);
4058 return &GEP;
4059 }
Duncan Sands5b7cfb02009-03-02 09:18:21 +00004060 }
4061 }
Chris Lattnereed48272005-09-13 00:40:14 +00004062 } else if (GEP.getNumOperands() == 2) {
4063 // Transform things like:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +00004064 // %t = getelementptr i32* bitcast ([2 x i32]* %str to i32*), i32 %V
4065 // into: %t1 = getelementptr [2 x i32]* %str, i32 0, i32 %V; bitcast
Chris Lattnereed48272005-09-13 00:40:14 +00004066 const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
4067 const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
Dan Gohmance9fe9f2009-07-21 23:21:54 +00004068 if (TD && isa<ArrayType>(SrcElTy) &&
Duncan Sands777d2302009-05-09 07:06:46 +00004069 TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
4070 TD->getTypeAllocSize(ResElTy)) {
David Greeneb8f74792007-09-04 15:46:09 +00004071 Value *Idx[2];
Chris Lattner4de84762010-01-04 07:02:48 +00004072 Idx[0] = Constant::getNullValue(Type::getInt32Ty(GEP.getContext()));
David Greeneb8f74792007-09-04 15:46:09 +00004073 Idx[1] = GEP.getOperand(1);
Dan Gohmanf8dbee72009-09-07 23:54:19 +00004074 Value *NewGEP = cast<GEPOperator>(&GEP)->isInBounds() ?
4075 Builder->CreateInBoundsGEP(X, Idx, Idx + 2, GEP.getName()) :
Chris Lattnerf925cbd2009-08-30 18:50:58 +00004076 Builder->CreateGEP(X, Idx, Idx + 2, GEP.getName());
Reid Spencer3da59db2006-11-27 01:05:10 +00004077 // V and GEP are both pointer types --> BitCast
Chris Lattnerf925cbd2009-08-30 18:50:58 +00004078 return new BitCastInst(NewGEP, GEP.getType());
Chris Lattnerc6bd1952004-02-22 05:25:17 +00004079 }
Chris Lattner7835cdd2005-09-13 18:36:04 +00004080
4081 // Transform things like:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +00004082 // getelementptr i8* bitcast ([100 x double]* X to i8*), i32 %tmp
Chris Lattner7835cdd2005-09-13 18:36:04 +00004083 // (where tmp = 8*tmp2) into:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +00004084 // getelementptr [100 x double]* %arr, i32 0, i32 %tmp2; bitcast
Chris Lattner7835cdd2005-09-13 18:36:04 +00004085
Chris Lattner4de84762010-01-04 07:02:48 +00004086 if (TD && isa<ArrayType>(SrcElTy) &&
4087 ResElTy == Type::getInt8Ty(GEP.getContext())) {
Chris Lattner7835cdd2005-09-13 18:36:04 +00004088 uint64_t ArrayEltSize =
Duncan Sands777d2302009-05-09 07:06:46 +00004089 TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType());
Chris Lattner7835cdd2005-09-13 18:36:04 +00004090
4091 // Check to see if "tmp" is a scale by a multiple of ArrayEltSize. We
4092 // allow either a mul, shift, or constant here.
4093 Value *NewIdx = 0;
4094 ConstantInt *Scale = 0;
4095 if (ArrayEltSize == 1) {
4096 NewIdx = GEP.getOperand(1);
Chris Lattnerab984842009-08-30 05:30:55 +00004097 Scale = ConstantInt::get(cast<IntegerType>(NewIdx->getType()), 1);
Chris Lattner7835cdd2005-09-13 18:36:04 +00004098 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
Owen Andersoneed707b2009-07-24 23:12:02 +00004099 NewIdx = ConstantInt::get(CI->getType(), 1);
Chris Lattner7835cdd2005-09-13 18:36:04 +00004100 Scale = CI;
4101 } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
4102 if (Inst->getOpcode() == Instruction::Shl &&
4103 isa<ConstantInt>(Inst->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00004104 ConstantInt *ShAmt = cast<ConstantInt>(Inst->getOperand(1));
4105 uint32_t ShAmtVal = ShAmt->getLimitedValue(64);
Owen Andersoneed707b2009-07-24 23:12:02 +00004106 Scale = ConstantInt::get(cast<IntegerType>(Inst->getType()),
Dan Gohman6de29f82009-06-15 22:12:54 +00004107 1ULL << ShAmtVal);
Chris Lattner7835cdd2005-09-13 18:36:04 +00004108 NewIdx = Inst->getOperand(0);
4109 } else if (Inst->getOpcode() == Instruction::Mul &&
4110 isa<ConstantInt>(Inst->getOperand(1))) {
4111 Scale = cast<ConstantInt>(Inst->getOperand(1));
4112 NewIdx = Inst->getOperand(0);
4113 }
4114 }
Wojciech Matyjewiczed223252007-12-12 15:21:32 +00004115
Chris Lattner7835cdd2005-09-13 18:36:04 +00004116 // If the index will be to exactly the right offset with the scale taken
Wojciech Matyjewiczed223252007-12-12 15:21:32 +00004117 // out, perform the transformation. Note, we don't know whether Scale is
4118 // signed or not. We'll use unsigned version of division/modulo
4119 // operation after making sure Scale doesn't have the sign bit set.
Chris Lattner58b1ac72009-02-25 18:20:01 +00004120 if (ArrayEltSize && Scale && Scale->getSExtValue() >= 0LL &&
Wojciech Matyjewiczed223252007-12-12 15:21:32 +00004121 Scale->getZExtValue() % ArrayEltSize == 0) {
Owen Andersoneed707b2009-07-24 23:12:02 +00004122 Scale = ConstantInt::get(Scale->getType(),
Wojciech Matyjewiczed223252007-12-12 15:21:32 +00004123 Scale->getZExtValue() / ArrayEltSize);
Reid Spencerb83eb642006-10-20 07:07:24 +00004124 if (Scale->getZExtValue() != 1) {
Chris Lattner878daed2009-08-30 05:56:44 +00004125 Constant *C = ConstantExpr::getIntegerCast(Scale, NewIdx->getType(),
4126 false /*ZExt*/);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00004127 NewIdx = Builder->CreateMul(NewIdx, C, "idxscale");
Chris Lattner7835cdd2005-09-13 18:36:04 +00004128 }
4129
4130 // Insert the new GEP instruction.
David Greeneb8f74792007-09-04 15:46:09 +00004131 Value *Idx[2];
Chris Lattner4de84762010-01-04 07:02:48 +00004132 Idx[0] = Constant::getNullValue(Type::getInt32Ty(GEP.getContext()));
David Greeneb8f74792007-09-04 15:46:09 +00004133 Idx[1] = NewIdx;
Dan Gohmanf8dbee72009-09-07 23:54:19 +00004134 Value *NewGEP = cast<GEPOperator>(&GEP)->isInBounds() ?
4135 Builder->CreateInBoundsGEP(X, Idx, Idx + 2, GEP.getName()) :
4136 Builder->CreateGEP(X, Idx, Idx + 2, GEP.getName());
Reid Spencer3da59db2006-11-27 01:05:10 +00004137 // The NewGEP must be pointer typed, so must the old one -> BitCast
4138 return new BitCastInst(NewGEP, GEP.getType());
Chris Lattner7835cdd2005-09-13 18:36:04 +00004139 }
4140 }
Chris Lattnerc6bd1952004-02-22 05:25:17 +00004141 }
Chris Lattner8a2a3112001-12-14 16:52:21 +00004142 }
Chris Lattner58407792009-01-09 04:53:57 +00004143
Chris Lattner46cd5a12009-01-09 05:44:56 +00004144 /// See if we can simplify:
Chris Lattner873ff012009-08-30 05:55:36 +00004145 /// X = bitcast A* to B*
Chris Lattner46cd5a12009-01-09 05:44:56 +00004146 /// Y = gep X, <...constant indices...>
4147 /// into a gep of the original struct. This is important for SROA and alias
4148 /// analysis of unions. If "A" is also a bitcast, wait for A/X to be merged.
Chris Lattner58407792009-01-09 04:53:57 +00004149 if (BitCastInst *BCI = dyn_cast<BitCastInst>(PtrOp)) {
Dan Gohmance9fe9f2009-07-21 23:21:54 +00004150 if (TD &&
4151 !isa<BitCastInst>(BCI->getOperand(0)) && GEP.hasAllConstantIndices()) {
Chris Lattner46cd5a12009-01-09 05:44:56 +00004152 // Determine how much the GEP moves the pointer. We are guaranteed to get
4153 // a constant back from EmitGEPOffset.
Chris Lattner02446fc2010-01-04 07:37:31 +00004154 ConstantInt *OffsetV = cast<ConstantInt>(EmitGEPOffset(&GEP));
Chris Lattner46cd5a12009-01-09 05:44:56 +00004155 int64_t Offset = OffsetV->getSExtValue();
4156
4157 // If this GEP instruction doesn't move the pointer, just replace the GEP
4158 // with a bitcast of the real input to the dest type.
4159 if (Offset == 0) {
4160 // If the bitcast is of an allocation, and the allocation will be
4161 // converted to match the type of the cast, don't touch this.
Victor Hernandez7b929da2009-10-23 21:09:37 +00004162 if (isa<AllocaInst>(BCI->getOperand(0)) ||
Victor Hernandez83d63912009-09-18 22:35:49 +00004163 isMalloc(BCI->getOperand(0))) {
Chris Lattner46cd5a12009-01-09 05:44:56 +00004164 // See if the bitcast simplifies, if so, don't nuke this GEP yet.
4165 if (Instruction *I = visitBitCast(*BCI)) {
4166 if (I != BCI) {
4167 I->takeName(BCI);
4168 BCI->getParent()->getInstList().insert(BCI, I);
4169 ReplaceInstUsesWith(*BCI, I);
4170 }
4171 return &GEP;
Chris Lattner58407792009-01-09 04:53:57 +00004172 }
Chris Lattner58407792009-01-09 04:53:57 +00004173 }
Chris Lattner46cd5a12009-01-09 05:44:56 +00004174 return new BitCastInst(BCI->getOperand(0), GEP.getType());
Chris Lattner58407792009-01-09 04:53:57 +00004175 }
Chris Lattner46cd5a12009-01-09 05:44:56 +00004176
4177 // Otherwise, if the offset is non-zero, we need to find out if there is a
4178 // field at Offset in 'A's type. If so, we can pull the cast through the
4179 // GEP.
4180 SmallVector<Value*, 8> NewIndices;
4181 const Type *InTy =
4182 cast<PointerType>(BCI->getOperand(0)->getType())->getElementType();
Chris Lattner80f43d32010-01-04 07:53:58 +00004183 if (FindElementAtOffset(InTy, Offset, NewIndices)) {
Dan Gohmanf8dbee72009-09-07 23:54:19 +00004184 Value *NGEP = cast<GEPOperator>(&GEP)->isInBounds() ?
4185 Builder->CreateInBoundsGEP(BCI->getOperand(0), NewIndices.begin(),
4186 NewIndices.end()) :
4187 Builder->CreateGEP(BCI->getOperand(0), NewIndices.begin(),
4188 NewIndices.end());
Chris Lattnerf925cbd2009-08-30 18:50:58 +00004189
4190 if (NGEP->getType() == GEP.getType())
4191 return ReplaceInstUsesWith(GEP, NGEP);
Chris Lattner46cd5a12009-01-09 05:44:56 +00004192 NGEP->takeName(&GEP);
4193 return new BitCastInst(NGEP, GEP.getType());
4194 }
Chris Lattner58407792009-01-09 04:53:57 +00004195 }
4196 }
4197
Chris Lattner8a2a3112001-12-14 16:52:21 +00004198 return 0;
4199}
4200
Victor Hernandez66284e02009-10-24 04:23:03 +00004201Instruction *InstCombiner::visitFree(Instruction &FI) {
4202 Value *Op = FI.getOperand(1);
4203
4204 // free undef -> unreachable.
4205 if (isa<UndefValue>(Op)) {
4206 // Insert a new store to null because we cannot modify the CFG here.
Chris Lattner4de84762010-01-04 07:02:48 +00004207 new StoreInst(ConstantInt::getTrue(FI.getContext()),
4208 UndefValue::get(Type::getInt1PtrTy(FI.getContext())), &FI);
Victor Hernandez66284e02009-10-24 04:23:03 +00004209 return EraseInstFromFunction(FI);
4210 }
4211
4212 // If we have 'free null' delete the instruction. This can happen in stl code
4213 // when lots of inlining happens.
4214 if (isa<ConstantPointerNull>(Op))
4215 return EraseInstFromFunction(FI);
4216
Victor Hernandez046e78c2009-10-26 23:43:48 +00004217 // If we have a malloc call whose only use is a free call, delete both.
Dan Gohman7f712a12009-10-27 00:11:02 +00004218 if (isMalloc(Op)) {
Victor Hernandez66284e02009-10-24 04:23:03 +00004219 if (CallInst* CI = extractMallocCallFromBitCast(Op)) {
4220 if (Op->hasOneUse() && CI->hasOneUse()) {
4221 EraseInstFromFunction(FI);
4222 EraseInstFromFunction(*CI);
4223 return EraseInstFromFunction(*cast<Instruction>(Op));
4224 }
4225 } else {
4226 // Op is a call to malloc
4227 if (Op->hasOneUse()) {
4228 EraseInstFromFunction(FI);
4229 return EraseInstFromFunction(*cast<Instruction>(Op));
4230 }
4231 }
Dan Gohman7f712a12009-10-27 00:11:02 +00004232 }
Victor Hernandez66284e02009-10-24 04:23:03 +00004233
4234 return 0;
4235}
Chris Lattner67b1e1b2003-12-07 01:24:23 +00004236
Chris Lattner3284d1f2007-04-15 00:07:55 +00004237
Chris Lattner2f503e62005-01-31 05:36:43 +00004238
Chris Lattnerc4d10eb2003-06-04 04:46:00 +00004239Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
4240 // Change br (not X), label True, label False to: br X, label False, True
Reid Spencer4b828e62005-06-18 17:37:34 +00004241 Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004242 BasicBlock *TrueDest;
4243 BasicBlock *FalseDest;
Dan Gohman4ae51262009-08-12 16:23:25 +00004244 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004245 !isa<Constant>(X)) {
4246 // Swap Destinations and condition...
4247 BI.setCondition(X);
4248 BI.setSuccessor(0, FalseDest);
4249 BI.setSuccessor(1, TrueDest);
4250 return &BI;
4251 }
4252
Reid Spencere4d87aa2006-12-23 06:05:41 +00004253 // Cannonicalize fcmp_one -> fcmp_oeq
4254 FCmpInst::Predicate FPred; Value *Y;
4255 if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)),
Chris Lattner7a1e9242009-08-30 06:13:40 +00004256 TrueDest, FalseDest)) &&
4257 BI.getCondition()->hasOneUse())
4258 if (FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
4259 FPred == FCmpInst::FCMP_OGE) {
4260 FCmpInst *Cond = cast<FCmpInst>(BI.getCondition());
4261 Cond->setPredicate(FCmpInst::getInversePredicate(FPred));
4262
4263 // Swap Destinations and condition.
Reid Spencere4d87aa2006-12-23 06:05:41 +00004264 BI.setSuccessor(0, FalseDest);
4265 BI.setSuccessor(1, TrueDest);
Chris Lattner7a1e9242009-08-30 06:13:40 +00004266 Worklist.Add(Cond);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004267 return &BI;
4268 }
4269
4270 // Cannonicalize icmp_ne -> icmp_eq
4271 ICmpInst::Predicate IPred;
4272 if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
Chris Lattner7a1e9242009-08-30 06:13:40 +00004273 TrueDest, FalseDest)) &&
4274 BI.getCondition()->hasOneUse())
4275 if (IPred == ICmpInst::ICMP_NE || IPred == ICmpInst::ICMP_ULE ||
4276 IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
4277 IPred == ICmpInst::ICMP_SGE) {
4278 ICmpInst *Cond = cast<ICmpInst>(BI.getCondition());
4279 Cond->setPredicate(ICmpInst::getInversePredicate(IPred));
4280 // Swap Destinations and condition.
Chris Lattner40f5d702003-06-04 05:10:11 +00004281 BI.setSuccessor(0, FalseDest);
4282 BI.setSuccessor(1, TrueDest);
Chris Lattner7a1e9242009-08-30 06:13:40 +00004283 Worklist.Add(Cond);
Chris Lattner40f5d702003-06-04 05:10:11 +00004284 return &BI;
4285 }
Misha Brukmanfd939082005-04-21 23:48:37 +00004286
Chris Lattnerc4d10eb2003-06-04 04:46:00 +00004287 return 0;
4288}
Chris Lattner0864acf2002-11-04 16:18:53 +00004289
Chris Lattner46238a62004-07-03 00:26:11 +00004290Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
4291 Value *Cond = SI.getCondition();
4292 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
4293 if (I->getOpcode() == Instruction::Add)
4294 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
4295 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
4296 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
Owen Andersond672ecb2009-07-03 00:17:18 +00004297 SI.setOperand(i,
Owen Andersonbaf3c402009-07-29 18:55:55 +00004298 ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
Chris Lattner46238a62004-07-03 00:26:11 +00004299 AddRHS));
4300 SI.setOperand(0, I->getOperand(0));
Chris Lattner7a1e9242009-08-30 06:13:40 +00004301 Worklist.Add(I);
Chris Lattner46238a62004-07-03 00:26:11 +00004302 return &SI;
4303 }
4304 }
4305 return 0;
4306}
4307
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +00004308Instruction *InstCombiner::visitExtractValueInst(ExtractValueInst &EV) {
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +00004309 Value *Agg = EV.getAggregateOperand();
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +00004310
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +00004311 if (!EV.hasIndices())
4312 return ReplaceInstUsesWith(EV, Agg);
4313
4314 if (Constant *C = dyn_cast<Constant>(Agg)) {
4315 if (isa<UndefValue>(C))
Owen Anderson9e9a0d52009-07-30 23:03:37 +00004316 return ReplaceInstUsesWith(EV, UndefValue::get(EV.getType()));
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +00004317
4318 if (isa<ConstantAggregateZero>(C))
Owen Andersona7235ea2009-07-31 20:28:14 +00004319 return ReplaceInstUsesWith(EV, Constant::getNullValue(EV.getType()));
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +00004320
4321 if (isa<ConstantArray>(C) || isa<ConstantStruct>(C)) {
4322 // Extract the element indexed by the first index out of the constant
4323 Value *V = C->getOperand(*EV.idx_begin());
4324 if (EV.getNumIndices() > 1)
4325 // Extract the remaining indices out of the constant indexed by the
4326 // first index
4327 return ExtractValueInst::Create(V, EV.idx_begin() + 1, EV.idx_end());
4328 else
4329 return ReplaceInstUsesWith(EV, V);
4330 }
4331 return 0; // Can't handle other constants
4332 }
4333 if (InsertValueInst *IV = dyn_cast<InsertValueInst>(Agg)) {
4334 // We're extracting from an insertvalue instruction, compare the indices
4335 const unsigned *exti, *exte, *insi, *inse;
4336 for (exti = EV.idx_begin(), insi = IV->idx_begin(),
4337 exte = EV.idx_end(), inse = IV->idx_end();
4338 exti != exte && insi != inse;
4339 ++exti, ++insi) {
4340 if (*insi != *exti)
4341 // The insert and extract both reference distinctly different elements.
4342 // This means the extract is not influenced by the insert, and we can
4343 // replace the aggregate operand of the extract with the aggregate
4344 // operand of the insert. i.e., replace
4345 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
4346 // %E = extractvalue { i32, { i32 } } %I, 0
4347 // with
4348 // %E = extractvalue { i32, { i32 } } %A, 0
4349 return ExtractValueInst::Create(IV->getAggregateOperand(),
4350 EV.idx_begin(), EV.idx_end());
4351 }
4352 if (exti == exte && insi == inse)
4353 // Both iterators are at the end: Index lists are identical. Replace
4354 // %B = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
4355 // %C = extractvalue { i32, { i32 } } %B, 1, 0
4356 // with "i32 42"
4357 return ReplaceInstUsesWith(EV, IV->getInsertedValueOperand());
4358 if (exti == exte) {
4359 // The extract list is a prefix of the insert list. i.e. replace
4360 // %I = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
4361 // %E = extractvalue { i32, { i32 } } %I, 1
4362 // with
4363 // %X = extractvalue { i32, { i32 } } %A, 1
4364 // %E = insertvalue { i32 } %X, i32 42, 0
4365 // by switching the order of the insert and extract (though the
4366 // insertvalue should be left in, since it may have other uses).
Chris Lattnerf925cbd2009-08-30 18:50:58 +00004367 Value *NewEV = Builder->CreateExtractValue(IV->getAggregateOperand(),
4368 EV.idx_begin(), EV.idx_end());
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +00004369 return InsertValueInst::Create(NewEV, IV->getInsertedValueOperand(),
4370 insi, inse);
4371 }
4372 if (insi == inse)
4373 // The insert list is a prefix of the extract list
4374 // We can simply remove the common indices from the extract and make it
4375 // operate on the inserted value instead of the insertvalue result.
4376 // i.e., replace
4377 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
4378 // %E = extractvalue { i32, { i32 } } %I, 1, 0
4379 // with
4380 // %E extractvalue { i32 } { i32 42 }, 0
4381 return ExtractValueInst::Create(IV->getInsertedValueOperand(),
4382 exti, exte);
4383 }
Chris Lattner7e606e22009-11-09 07:07:56 +00004384 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Agg)) {
4385 // We're extracting from an intrinsic, see if we're the only user, which
4386 // allows us to simplify multiple result intrinsics to simpler things that
4387 // just get one value..
4388 if (II->hasOneUse()) {
4389 // Check if we're grabbing the overflow bit or the result of a 'with
4390 // overflow' intrinsic. If it's the latter we can remove the intrinsic
4391 // and replace it with a traditional binary instruction.
4392 switch (II->getIntrinsicID()) {
4393 case Intrinsic::uadd_with_overflow:
4394 case Intrinsic::sadd_with_overflow:
4395 if (*EV.idx_begin() == 0) { // Normal result.
4396 Value *LHS = II->getOperand(1), *RHS = II->getOperand(2);
4397 II->replaceAllUsesWith(UndefValue::get(II->getType()));
4398 EraseInstFromFunction(*II);
4399 return BinaryOperator::CreateAdd(LHS, RHS);
4400 }
4401 break;
4402 case Intrinsic::usub_with_overflow:
4403 case Intrinsic::ssub_with_overflow:
4404 if (*EV.idx_begin() == 0) { // Normal result.
4405 Value *LHS = II->getOperand(1), *RHS = II->getOperand(2);
4406 II->replaceAllUsesWith(UndefValue::get(II->getType()));
4407 EraseInstFromFunction(*II);
4408 return BinaryOperator::CreateSub(LHS, RHS);
4409 }
4410 break;
4411 case Intrinsic::umul_with_overflow:
4412 case Intrinsic::smul_with_overflow:
4413 if (*EV.idx_begin() == 0) { // Normal result.
4414 Value *LHS = II->getOperand(1), *RHS = II->getOperand(2);
4415 II->replaceAllUsesWith(UndefValue::get(II->getType()));
4416 EraseInstFromFunction(*II);
4417 return BinaryOperator::CreateMul(LHS, RHS);
4418 }
4419 break;
4420 default:
4421 break;
4422 }
4423 }
4424 }
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +00004425 // Can't simplify extracts from other values. Note that nested extracts are
4426 // already simplified implicitely by the above (extract ( extract (insert) )
4427 // will be translated into extract ( insert ( extract ) ) first and then just
4428 // the value inserted, if appropriate).
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +00004429 return 0;
4430}
4431
Chris Lattnera844fc4c2006-04-10 22:45:52 +00004432
Robert Bocchino1d7456d2006-01-13 22:48:06 +00004433
Chris Lattnerea1c4542004-12-08 23:43:58 +00004434
4435/// TryToSinkInstruction - Try to move the specified instruction from its
4436/// current block into the beginning of DestBlock, which can only happen if it's
4437/// safe to move the instruction past all of the instructions between it and the
4438/// end of its block.
4439static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
4440 assert(I->hasOneUse() && "Invariants didn't hold!");
4441
Chris Lattner108e9022005-10-27 17:13:11 +00004442 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
Duncan Sands7af1c782009-05-06 06:49:50 +00004443 if (isa<PHINode>(I) || I->mayHaveSideEffects() || isa<TerminatorInst>(I))
Chris Lattnerbfc538c2008-05-09 15:07:33 +00004444 return false;
Misha Brukmanfd939082005-04-21 23:48:37 +00004445
Chris Lattnerea1c4542004-12-08 23:43:58 +00004446 // Do not sink alloca instructions out of the entry block.
Dan Gohmanecb7a772007-03-22 16:38:57 +00004447 if (isa<AllocaInst>(I) && I->getParent() ==
4448 &DestBlock->getParent()->getEntryBlock())
Chris Lattnerea1c4542004-12-08 23:43:58 +00004449 return false;
4450
Chris Lattner96a52a62004-12-09 07:14:34 +00004451 // We can only sink load instructions if there is nothing between the load and
4452 // the end of block that could change the value.
Chris Lattner2539e332008-05-08 17:37:37 +00004453 if (I->mayReadFromMemory()) {
4454 for (BasicBlock::iterator Scan = I, E = I->getParent()->end();
Chris Lattner96a52a62004-12-09 07:14:34 +00004455 Scan != E; ++Scan)
4456 if (Scan->mayWriteToMemory())
4457 return false;
Chris Lattner96a52a62004-12-09 07:14:34 +00004458 }
Chris Lattnerea1c4542004-12-08 23:43:58 +00004459
Dan Gohman02dea8b2008-05-23 21:05:58 +00004460 BasicBlock::iterator InsertPos = DestBlock->getFirstNonPHI();
Chris Lattnerea1c4542004-12-08 23:43:58 +00004461
Chris Lattner4bc5f802005-08-08 19:11:57 +00004462 I->moveBefore(InsertPos);
Chris Lattnerea1c4542004-12-08 23:43:58 +00004463 ++NumSunkInst;
4464 return true;
4465}
4466
Chris Lattnerf4f5a772006-05-10 19:00:36 +00004467
4468/// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
4469/// all reachable code to the worklist.
4470///
4471/// This has a couple of tricks to make the code faster and more powerful. In
4472/// particular, we constant fold and DCE instructions as we go, to avoid adding
4473/// them to the worklist (this significantly speeds up instcombine on code where
4474/// many instructions are dead or constant). Additionally, if we find a branch
4475/// whose condition is a known constant, we only visit the reachable successors.
4476///
Chris Lattner2ee743b2009-10-15 04:59:28 +00004477static bool AddReachableCodeToWorklist(BasicBlock *BB,
Chris Lattner1f87a582007-02-15 19:41:52 +00004478 SmallPtrSet<BasicBlock*, 64> &Visited,
Chris Lattnerdbab3862007-03-02 21:28:56 +00004479 InstCombiner &IC,
Chris Lattner8c8c66a2006-05-11 17:11:52 +00004480 const TargetData *TD) {
Chris Lattner2ee743b2009-10-15 04:59:28 +00004481 bool MadeIRChange = false;
Chris Lattner2806dff2008-08-15 04:03:01 +00004482 SmallVector<BasicBlock*, 256> Worklist;
Chris Lattner2c7718a2007-03-23 19:17:18 +00004483 Worklist.push_back(BB);
Chris Lattner67f7d542009-10-12 03:58:40 +00004484
4485 std::vector<Instruction*> InstrsForInstCombineWorklist;
4486 InstrsForInstCombineWorklist.reserve(128);
Chris Lattnerf4f5a772006-05-10 19:00:36 +00004487
Chris Lattner2ee743b2009-10-15 04:59:28 +00004488 SmallPtrSet<ConstantExpr*, 64> FoldedConstants;
4489
Chris Lattner2c7718a2007-03-23 19:17:18 +00004490 while (!Worklist.empty()) {
4491 BB = Worklist.back();
4492 Worklist.pop_back();
4493
4494 // We have now visited this block! If we've already been here, ignore it.
4495 if (!Visited.insert(BB)) continue;
Devang Patel7fe1dec2008-11-19 18:56:50 +00004496
Chris Lattner2c7718a2007-03-23 19:17:18 +00004497 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
4498 Instruction *Inst = BBI++;
Chris Lattnerf4f5a772006-05-10 19:00:36 +00004499
Chris Lattner2c7718a2007-03-23 19:17:18 +00004500 // DCE instruction if trivially dead.
4501 if (isInstructionTriviallyDead(Inst)) {
4502 ++NumDeadInst;
Chris Lattnerbdff5482009-08-23 04:37:46 +00004503 DEBUG(errs() << "IC: DCE: " << *Inst << '\n');
Chris Lattner2c7718a2007-03-23 19:17:18 +00004504 Inst->eraseFromParent();
4505 continue;
4506 }
4507
4508 // ConstantProp instruction if trivially constant.
Chris Lattnere2cc1ad2009-10-15 04:13:44 +00004509 if (!Inst->use_empty() && isa<Constant>(Inst->getOperand(0)))
Chris Lattner7b550cc2009-11-06 04:27:31 +00004510 if (Constant *C = ConstantFoldInstruction(Inst, TD)) {
Chris Lattnere2cc1ad2009-10-15 04:13:44 +00004511 DEBUG(errs() << "IC: ConstFold to: " << *C << " from: "
4512 << *Inst << '\n');
4513 Inst->replaceAllUsesWith(C);
4514 ++NumConstProp;
4515 Inst->eraseFromParent();
4516 continue;
4517 }
Chris Lattner2ee743b2009-10-15 04:59:28 +00004518
4519
4520
4521 if (TD) {
4522 // See if we can constant fold its operands.
4523 for (User::op_iterator i = Inst->op_begin(), e = Inst->op_end();
4524 i != e; ++i) {
4525 ConstantExpr *CE = dyn_cast<ConstantExpr>(i);
4526 if (CE == 0) continue;
4527
4528 // If we already folded this constant, don't try again.
4529 if (!FoldedConstants.insert(CE))
4530 continue;
4531
Chris Lattner7b550cc2009-11-06 04:27:31 +00004532 Constant *NewC = ConstantFoldConstantExpression(CE, TD);
Chris Lattner2ee743b2009-10-15 04:59:28 +00004533 if (NewC && NewC != CE) {
4534 *i = NewC;
4535 MadeIRChange = true;
4536 }
4537 }
4538 }
4539
Devang Patel7fe1dec2008-11-19 18:56:50 +00004540
Chris Lattner67f7d542009-10-12 03:58:40 +00004541 InstrsForInstCombineWorklist.push_back(Inst);
Chris Lattnerf4f5a772006-05-10 19:00:36 +00004542 }
Chris Lattner2c7718a2007-03-23 19:17:18 +00004543
4544 // Recursively visit successors. If this is a branch or switch on a
4545 // constant, only visit the reachable successor.
4546 TerminatorInst *TI = BB->getTerminator();
4547 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
4548 if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
4549 bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
Nick Lewycky91436992008-03-09 08:50:23 +00004550 BasicBlock *ReachableBB = BI->getSuccessor(!CondVal);
Nick Lewycky280a6e62008-04-25 16:53:59 +00004551 Worklist.push_back(ReachableBB);
Chris Lattner2c7718a2007-03-23 19:17:18 +00004552 continue;
4553 }
4554 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
4555 if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
4556 // See if this is an explicit destination.
4557 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
4558 if (SI->getCaseValue(i) == Cond) {
Nick Lewycky91436992008-03-09 08:50:23 +00004559 BasicBlock *ReachableBB = SI->getSuccessor(i);
Nick Lewycky280a6e62008-04-25 16:53:59 +00004560 Worklist.push_back(ReachableBB);
Chris Lattner2c7718a2007-03-23 19:17:18 +00004561 continue;
4562 }
4563
4564 // Otherwise it is the default destination.
4565 Worklist.push_back(SI->getSuccessor(0));
4566 continue;
4567 }
4568 }
4569
4570 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
4571 Worklist.push_back(TI->getSuccessor(i));
Chris Lattnerf4f5a772006-05-10 19:00:36 +00004572 }
Chris Lattner67f7d542009-10-12 03:58:40 +00004573
4574 // Once we've found all of the instructions to add to instcombine's worklist,
4575 // add them in reverse order. This way instcombine will visit from the top
4576 // of the function down. This jives well with the way that it adds all uses
4577 // of instructions to the worklist after doing a transformation, thus avoiding
4578 // some N^2 behavior in pathological cases.
4579 IC.Worklist.AddInitialGroup(&InstrsForInstCombineWorklist[0],
4580 InstrsForInstCombineWorklist.size());
Chris Lattner2ee743b2009-10-15 04:59:28 +00004581
4582 return MadeIRChange;
Chris Lattnerf4f5a772006-05-10 19:00:36 +00004583}
4584
Chris Lattnerec9c3582007-03-03 02:04:50 +00004585bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) {
Chris Lattnerb0b822c2009-08-31 06:57:37 +00004586 MadeIRChange = false;
Chris Lattnerec9c3582007-03-03 02:04:50 +00004587
Daniel Dunbarce63ffb2009-07-25 00:23:56 +00004588 DEBUG(errs() << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
4589 << F.getNameStr() << "\n");
Chris Lattner8a2a3112001-12-14 16:52:21 +00004590
Chris Lattnerb3d59702005-07-07 20:40:38 +00004591 {
Chris Lattnerf4f5a772006-05-10 19:00:36 +00004592 // Do a depth-first traversal of the function, populate the worklist with
4593 // the reachable instructions. Ignore blocks that are not reachable. Keep
4594 // track of which blocks we visit.
Chris Lattner1f87a582007-02-15 19:41:52 +00004595 SmallPtrSet<BasicBlock*, 64> Visited;
Chris Lattner2ee743b2009-10-15 04:59:28 +00004596 MadeIRChange |= AddReachableCodeToWorklist(F.begin(), Visited, *this, TD);
Jeff Cohen00b168892005-07-27 06:12:32 +00004597
Chris Lattnerb3d59702005-07-07 20:40:38 +00004598 // Do a quick scan over the function. If we find any blocks that are
4599 // unreachable, remove any instructions inside of them. This prevents
4600 // the instcombine code from having to deal with some bad special cases.
4601 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
4602 if (!Visited.count(BB)) {
4603 Instruction *Term = BB->getTerminator();
4604 while (Term != BB->begin()) { // Remove instrs bottom-up
4605 BasicBlock::iterator I = Term; --I;
Chris Lattner6ffe5512004-04-27 15:13:33 +00004606
Chris Lattnerbdff5482009-08-23 04:37:46 +00004607 DEBUG(errs() << "IC: DCE: " << *I << '\n');
Dale Johannesenff278b12009-03-10 21:19:49 +00004608 // A debug intrinsic shouldn't force another iteration if we weren't
4609 // going to do one without it.
4610 if (!isa<DbgInfoIntrinsic>(I)) {
4611 ++NumDeadInst;
Chris Lattnerb0b822c2009-08-31 06:57:37 +00004612 MadeIRChange = true;
Dale Johannesenff278b12009-03-10 21:19:49 +00004613 }
Devang Patel228ebd02009-10-13 22:56:32 +00004614
Devang Patel228ebd02009-10-13 22:56:32 +00004615 // If I is not void type then replaceAllUsesWith undef.
4616 // This allows ValueHandlers and custom metadata to adjust itself.
Devang Patel9674d152009-10-14 17:29:00 +00004617 if (!I->getType()->isVoidTy())
Devang Patel228ebd02009-10-13 22:56:32 +00004618 I->replaceAllUsesWith(UndefValue::get(I->getType()));
Chris Lattnerb3d59702005-07-07 20:40:38 +00004619 I->eraseFromParent();
4620 }
4621 }
4622 }
Chris Lattner8a2a3112001-12-14 16:52:21 +00004623
Chris Lattner873ff012009-08-30 05:55:36 +00004624 while (!Worklist.isEmpty()) {
4625 Instruction *I = Worklist.RemoveOne();
Chris Lattnerdbab3862007-03-02 21:28:56 +00004626 if (I == 0) continue; // skip null values.
Chris Lattner8a2a3112001-12-14 16:52:21 +00004627
Chris Lattner8c8c66a2006-05-11 17:11:52 +00004628 // Check to see if we can DCE the instruction.
Chris Lattner62b14df2002-09-02 04:59:56 +00004629 if (isInstructionTriviallyDead(I)) {
Chris Lattnerbdff5482009-08-23 04:37:46 +00004630 DEBUG(errs() << "IC: DCE: " << *I << '\n');
Chris Lattner7a1e9242009-08-30 06:13:40 +00004631 EraseInstFromFunction(*I);
4632 ++NumDeadInst;
Chris Lattnerb0b822c2009-08-31 06:57:37 +00004633 MadeIRChange = true;
Chris Lattner4bb7c022003-10-06 17:11:01 +00004634 continue;
4635 }
Chris Lattner62b14df2002-09-02 04:59:56 +00004636
Chris Lattner8c8c66a2006-05-11 17:11:52 +00004637 // Instruction isn't dead, see if we can constant propagate it.
Chris Lattnere2cc1ad2009-10-15 04:13:44 +00004638 if (!I->use_empty() && isa<Constant>(I->getOperand(0)))
Chris Lattner7b550cc2009-11-06 04:27:31 +00004639 if (Constant *C = ConstantFoldInstruction(I, TD)) {
Chris Lattnere2cc1ad2009-10-15 04:13:44 +00004640 DEBUG(errs() << "IC: ConstFold to: " << *C << " from: " << *I << '\n');
Chris Lattnerad5fec12005-01-28 19:32:01 +00004641
Chris Lattnere2cc1ad2009-10-15 04:13:44 +00004642 // Add operands to the worklist.
4643 ReplaceInstUsesWith(*I, C);
4644 ++NumConstProp;
4645 EraseInstFromFunction(*I);
4646 MadeIRChange = true;
4647 continue;
4648 }
Chris Lattner4bb7c022003-10-06 17:11:01 +00004649
Chris Lattnerea1c4542004-12-08 23:43:58 +00004650 // See if we can trivially sink this instruction to a successor basic block.
Dan Gohmanfc74abf2008-07-23 00:34:11 +00004651 if (I->hasOneUse()) {
Chris Lattnerea1c4542004-12-08 23:43:58 +00004652 BasicBlock *BB = I->getParent();
Chris Lattner8db2cd12009-10-14 15:21:58 +00004653 Instruction *UserInst = cast<Instruction>(I->use_back());
4654 BasicBlock *UserParent;
4655
4656 // Get the block the use occurs in.
4657 if (PHINode *PN = dyn_cast<PHINode>(UserInst))
4658 UserParent = PN->getIncomingBlock(I->use_begin().getUse());
4659 else
4660 UserParent = UserInst->getParent();
4661
Chris Lattnerea1c4542004-12-08 23:43:58 +00004662 if (UserParent != BB) {
4663 bool UserIsSuccessor = false;
4664 // See if the user is one of our successors.
4665 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
4666 if (*SI == UserParent) {
4667 UserIsSuccessor = true;
4668 break;
4669 }
4670
4671 // If the user is one of our immediate successors, and if that successor
4672 // only has us as a predecessors (we'd have to split the critical edge
4673 // otherwise), we can keep going.
Chris Lattner8db2cd12009-10-14 15:21:58 +00004674 if (UserIsSuccessor && UserParent->getSinglePredecessor())
Chris Lattnerea1c4542004-12-08 23:43:58 +00004675 // Okay, the CFG is simple enough, try to sink this instruction.
Chris Lattnerb0b822c2009-08-31 06:57:37 +00004676 MadeIRChange |= TryToSinkInstruction(I, UserParent);
Chris Lattnerea1c4542004-12-08 23:43:58 +00004677 }
4678 }
4679
Chris Lattner74381062009-08-30 07:44:24 +00004680 // Now that we have an instruction, try combining it to simplify it.
4681 Builder->SetInsertPoint(I->getParent(), I);
4682
Reid Spencera9b81012007-03-26 17:44:01 +00004683#ifndef NDEBUG
4684 std::string OrigI;
4685#endif
Chris Lattnerbdff5482009-08-23 04:37:46 +00004686 DEBUG(raw_string_ostream SS(OrigI); I->print(SS); OrigI = SS.str(););
Jeffrey Yasskin43069632009-10-08 00:12:24 +00004687 DEBUG(errs() << "IC: Visiting: " << OrigI << '\n');
4688
Chris Lattner90ac28c2002-08-02 19:29:35 +00004689 if (Instruction *Result = visit(*I)) {
Chris Lattner3dec1f22002-05-10 15:38:35 +00004690 ++NumCombined;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00004691 // Should we replace the old instruction with a new one?
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +00004692 if (Result != I) {
Chris Lattnerbdff5482009-08-23 04:37:46 +00004693 DEBUG(errs() << "IC: Old = " << *I << '\n'
4694 << " New = " << *Result << '\n');
Chris Lattner0cea42a2004-03-13 23:54:27 +00004695
Chris Lattnerf523d062004-06-09 05:08:07 +00004696 // Everything uses the new instruction now.
4697 I->replaceAllUsesWith(Result);
4698
4699 // Push the new instruction and any users onto the worklist.
Chris Lattner7a1e9242009-08-30 06:13:40 +00004700 Worklist.Add(Result);
Chris Lattnere5ecdb52009-08-30 06:22:51 +00004701 Worklist.AddUsersToWorkList(*Result);
Chris Lattner4bb7c022003-10-06 17:11:01 +00004702
Chris Lattner6934a042007-02-11 01:23:03 +00004703 // Move the name to the new instruction first.
4704 Result->takeName(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +00004705
4706 // Insert the new instruction into the basic block...
4707 BasicBlock *InstParent = I->getParent();
Chris Lattnerbac32862004-11-14 19:13:23 +00004708 BasicBlock::iterator InsertPos = I;
4709
4710 if (!isa<PHINode>(Result)) // If combining a PHI, don't insert
4711 while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
4712 ++InsertPos;
4713
4714 InstParent->getInstList().insert(InsertPos, Result);
Chris Lattner4bb7c022003-10-06 17:11:01 +00004715
Chris Lattner7a1e9242009-08-30 06:13:40 +00004716 EraseInstFromFunction(*I);
Chris Lattner7e708292002-06-25 16:13:24 +00004717 } else {
Evan Chengc7baf682007-03-27 16:44:48 +00004718#ifndef NDEBUG
Chris Lattnerbdff5482009-08-23 04:37:46 +00004719 DEBUG(errs() << "IC: Mod = " << OrigI << '\n'
4720 << " New = " << *I << '\n');
Evan Chengc7baf682007-03-27 16:44:48 +00004721#endif
Chris Lattner0cea42a2004-03-13 23:54:27 +00004722
Chris Lattner90ac28c2002-08-02 19:29:35 +00004723 // If the instruction was modified, it's possible that it is now dead.
4724 // if so, remove it.
Chris Lattner00d51312004-05-01 23:27:23 +00004725 if (isInstructionTriviallyDead(I)) {
Chris Lattner7a1e9242009-08-30 06:13:40 +00004726 EraseInstFromFunction(*I);
Chris Lattnerf523d062004-06-09 05:08:07 +00004727 } else {
Chris Lattner7a1e9242009-08-30 06:13:40 +00004728 Worklist.Add(I);
Chris Lattnere5ecdb52009-08-30 06:22:51 +00004729 Worklist.AddUsersToWorkList(*I);
Chris Lattner90ac28c2002-08-02 19:29:35 +00004730 }
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +00004731 }
Chris Lattnerb0b822c2009-08-31 06:57:37 +00004732 MadeIRChange = true;
Chris Lattner8a2a3112001-12-14 16:52:21 +00004733 }
4734 }
4735
Chris Lattner873ff012009-08-30 05:55:36 +00004736 Worklist.Zap();
Chris Lattnerb0b822c2009-08-31 06:57:37 +00004737 return MadeIRChange;
Chris Lattnerbd0ef772002-02-26 21:46:54 +00004738}
4739
Chris Lattnerec9c3582007-03-03 02:04:50 +00004740
4741bool InstCombiner::runOnFunction(Function &F) {
Chris Lattnerf964f322007-03-04 04:27:24 +00004742 MustPreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
Chris Lattnere2cc1ad2009-10-15 04:13:44 +00004743 TD = getAnalysisIfAvailable<TargetData>();
4744
Chris Lattner74381062009-08-30 07:44:24 +00004745
4746 /// Builder - This is an IRBuilder that automatically inserts new
4747 /// instructions into the worklist when they are created.
Chris Lattnere2cc1ad2009-10-15 04:13:44 +00004748 IRBuilder<true, TargetFolder, InstCombineIRInserter>
Chris Lattnerf55eeb92009-11-06 05:59:53 +00004749 TheBuilder(F.getContext(), TargetFolder(TD),
Chris Lattner74381062009-08-30 07:44:24 +00004750 InstCombineIRInserter(Worklist));
4751 Builder = &TheBuilder;
4752
Chris Lattnerec9c3582007-03-03 02:04:50 +00004753 bool EverMadeChange = false;
4754
4755 // Iterate while there is work to do.
4756 unsigned Iteration = 0;
Bill Wendlinga6c31122008-05-14 22:45:20 +00004757 while (DoOneIteration(F, Iteration++))
Chris Lattnerec9c3582007-03-03 02:04:50 +00004758 EverMadeChange = true;
Chris Lattner74381062009-08-30 07:44:24 +00004759
4760 Builder = 0;
Chris Lattnerec9c3582007-03-03 02:04:50 +00004761 return EverMadeChange;
4762}
4763
Brian Gaeke96d4bf72004-07-27 17:43:21 +00004764FunctionPass *llvm::createInstructionCombiningPass() {
Chris Lattnerdd841ae2002-04-18 17:39:14 +00004765 return new InstCombiner();
Chris Lattnerbd0ef772002-02-26 21:46:54 +00004766}