blob: 81640f36a8eff582f39302b6fc46b8afb90be80a [file] [log] [blame]
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001//===- InstructionCombining.cpp - Combine multiple instructions -----------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner081ce942007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007//
8//===----------------------------------------------------------------------===//
9//
10// InstructionCombining - Combine instructions to form fewer, simple
Dan Gohman089efff2008-05-13 00:00:25 +000011// instructions. This pass does not modify the CFG. This pass is where
12// algebraic simplification happens.
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013//
14// This pass combines things like:
15// %Y = add i32 %X, 1
16// %Z = add i32 %Y, 1
17// into:
18// %Z = add i32 %X, 2
19//
20// This is a simple worklist driven algorithm.
21//
22// This pass guarantees that the following canonicalizations are performed on
23// the program:
24// 1. If a binary operator has a constant operand, it is moved to the RHS
25// 2. Bitwise operators with constant operands are always grouped so that
26// shifts are performed first, then or's, then and's, then xor's.
27// 3. Compare instructions are converted from <,>,<=,>= to ==,!= if possible
28// 4. All cmp instructions on boolean values are replaced with logical ops
29// 5. add X, X is represented as (X*2) => (X << 1)
30// 6. Multiplies with a power-of-two constant argument are transformed into
31// shifts.
32// ... etc.
33//
34//===----------------------------------------------------------------------===//
35
36#define DEBUG_TYPE "instcombine"
37#include "llvm/Transforms/Scalar.h"
Chris Lattner530dd162010-01-04 07:12:23 +000038#include "InstCombine.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000039#include "llvm/IntrinsicInst.h"
Owen Anderson24be4c12009-07-03 00:17:18 +000040#include "llvm/LLVMContext.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000041#include "llvm/DerivedTypes.h"
42#include "llvm/GlobalVariable.h"
Dan Gohman9545fb02009-07-17 20:47:02 +000043#include "llvm/Operator.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000044#include "llvm/Analysis/ConstantFolding.h"
Chris Lattnera9333562009-11-09 23:28:39 +000045#include "llvm/Analysis/InstructionSimplify.h"
Victor Hernandez28f4d2f2009-10-27 20:05:49 +000046#include "llvm/Analysis/MemoryBuiltins.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000047#include "llvm/Target/TargetData.h"
48#include "llvm/Transforms/Utils/BasicBlockUtils.h"
49#include "llvm/Transforms/Utils/Local.h"
50#include "llvm/Support/CallSite.h"
51#include "llvm/Support/Debug.h"
Edwin Törökced9ff82009-07-11 13:10:19 +000052#include "llvm/Support/ErrorHandling.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000053#include "llvm/Support/GetElementPtrTypeIterator.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000054#include "llvm/Support/MathExtras.h"
55#include "llvm/Support/PatternMatch.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000056#include "llvm/ADT/SmallPtrSet.h"
57#include "llvm/ADT/Statistic.h"
58#include "llvm/ADT/STLExtras.h"
59#include <algorithm>
Edwin Töröka0e6fce2008-04-20 08:33:11 +000060#include <climits>
Dan Gohmanf17a25c2007-07-18 16:29:46 +000061using namespace llvm;
62using namespace llvm::PatternMatch;
63
64STATISTIC(NumCombined , "Number of insts combined");
65STATISTIC(NumConstProp, "Number of constant folds");
66STATISTIC(NumDeadInst , "Number of dead inst eliminated");
Dan Gohmanf17a25c2007-07-18 16:29:46 +000067STATISTIC(NumSunkInst , "Number of instructions sunk");
68
Dan Gohmanf17a25c2007-07-18 16:29:46 +000069
Dan Gohman089efff2008-05-13 00:00:25 +000070char InstCombiner::ID = 0;
71static RegisterPass<InstCombiner>
72X("instcombine", "Combine redundant instructions");
73
Chris Lattnerc1cea3f2010-01-04 07:17:19 +000074void InstCombiner::getAnalysisUsage(AnalysisUsage &AU) const {
75 AU.addPreservedID(LCSSAID);
76 AU.setPreservesCFG();
77}
78
79
Dan Gohmanf17a25c2007-07-18 16:29:46 +000080// getPromotedType - Return the specified type promoted as it would be to pass
Chris Lattner1e680352010-01-05 07:04:23 +000081// though a va_arg area.
Dan Gohmanf17a25c2007-07-18 16:29:46 +000082static const Type *getPromotedType(const Type *Ty) {
83 if (const IntegerType* ITy = dyn_cast<IntegerType>(Ty)) {
84 if (ITy->getBitWidth() < 32)
Owen Anderson35b47072009-08-13 21:58:54 +000085 return Type::getInt32Ty(Ty->getContext());
Dan Gohmanf17a25c2007-07-18 16:29:46 +000086 }
87 return Ty;
88}
89
Chris Lattnerd0011092009-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 Lattner54826cd2010-01-04 07:53:58 +000093bool InstCombiner::ShouldChangeType(const Type *From, const Type *To) const {
Chris Lattnerd0011092009-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 Kooijman5e2a3182008-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.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000120static Value *getBitCastOperand(Value *V) {
Dan Gohmanae402b02009-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 Kooijman5e2a3182008-10-13 15:17:01 +0000127 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000128 return 0;
129}
130
Dan Gohmana80e2712009-07-21 23:21:54 +0000131
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000132
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000133// SimplifyCommutative - This performs a few simplifications for commutative
134// operators:
135//
136// 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//
140// 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))
142//
143bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
144 bool Changed = false;
Dan Gohman5d138f92009-08-29 23:39:38 +0000145 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000146 Changed = !I.swapOperands();
147
148 if (!I.isAssociative()) return Changed;
Chris Lattner1e680352010-01-05 07:04:23 +0000149
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000150 Instruction::BinaryOps Opcode = I.getOpcode();
151 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 Anderson02b48c32009-07-29 18:55:55 +0000154 Constant *Folded = ConstantExpr::get(I.getOpcode(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000155 cast<Constant>(I.getOperand(1)),
156 cast<Constant>(Op->getOperand(1)));
157 I.setOperand(0, Op->getOperand(0));
158 I.setOperand(1, Folded);
159 return true;
Chris Lattner1e680352010-01-05 07:04:23 +0000160 }
161
162 if (BinaryOperator *Op1 = dyn_cast<BinaryOperator>(I.getOperand(1)))
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000163 if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
Chris Lattner1e680352010-01-05 07:04:23 +0000164 Op->hasOneUse() && Op1->hasOneUse()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +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 Anderson02b48c32009-07-29 18:55:55 +0000169 Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
Gabor Greifa645dd32008-05-16 19:29:10 +0000170 Instruction *New = BinaryOperator::Create(Opcode, Op->getOperand(0),
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000171 Op1->getOperand(0),
172 Op1->getName(), &I);
Chris Lattner3183fb62009-08-30 06:13:40 +0000173 Worklist.Add(New);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000174 I.setOperand(0, New);
175 I.setOperand(1, Folded);
176 return true;
177 }
178 }
179 return Changed;
180}
181
Dan Gohmanf17a25c2007-07-18 16:29:46 +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).
184//
Chris Lattner63ac8422010-01-04 07:37:31 +0000185Value *InstCombiner::dyn_castNegVal(Value *V) const {
Owen Anderson76f49252009-07-13 22:18:28 +0000186 if (BinaryOperator::isNeg(V))
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000187 return BinaryOperator::getNegArgument(V);
188
189 // Constants can be considered to be negated values if they can be folded.
190 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
Owen Anderson02b48c32009-07-29 18:55:55 +0000191 return ConstantExpr::getNeg(C);
Nick Lewycky58867bc2008-05-23 04:54:45 +0000192
193 if (ConstantVector *C = dyn_cast<ConstantVector>(V))
194 if (C->getType()->getElementType()->isInteger())
Owen Anderson02b48c32009-07-29 18:55:55 +0000195 return ConstantExpr::getNeg(C);
Nick Lewycky58867bc2008-05-23 04:54:45 +0000196
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000197 return 0;
198}
199
Dan Gohman7ce405e2009-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 Lattner978364f2010-01-05 06:09:35 +0000204Value *InstCombiner::dyn_castFNegVal(Value *V) const {
Owen Anderson76f49252009-07-13 22:18:28 +0000205 if (BinaryOperator::isFNeg(V))
Dan Gohman7ce405e2009-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 Anderson02b48c32009-07-29 18:55:55 +0000210 return ConstantExpr::getFNeg(C);
Dan Gohman7ce405e2009-06-04 22:49:04 +0000211
212 if (ConstantVector *C = dyn_cast<ConstantVector>(V))
213 if (C->getType()->getElementType()->isFloatingPoint())
Owen Anderson02b48c32009-07-29 18:55:55 +0000214 return ConstantExpr::getFNeg(C);
Dan Gohman7ce405e2009-06-04 22:49:04 +0000215
216 return 0;
217}
218
Chris Lattner6e060db2009-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 Cheng5d4a07e2009-10-26 03:51:32 +0000223 if (BinaryOperator::isNot(V))
Chris Lattner6e060db2009-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 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000245
246 // Constants can be considered to be not'ed values...
247 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
Dan Gohmanfe91cd62009-08-12 16:04:34 +0000248 return ConstantInt::get(C->getType(), ~C->getValue());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000249 return 0;
250}
251
Chris Lattner6e060db2009-10-26 15:40:07 +0000252
253
Chris Lattner978364f2010-01-05 06:09:35 +0000254/// AddOne - Add one to a ConstantInt.
Dan Gohmanfe91cd62009-08-12 16:04:34 +0000255static Constant *AddOne(Constant *C) {
Chris Lattner63ac8422010-01-04 07:37:31 +0000256 return ConstantExpr::getAdd(C, ConstantInt::get(C->getType(), 1));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000257}
Chris Lattner978364f2010-01-05 06:09:35 +0000258/// SubOne - Subtract one from a ConstantInt.
Dan Gohmanfe91cd62009-08-12 16:04:34 +0000259static Constant *SubOne(ConstantInt *C) {
Chris Lattner978364f2010-01-05 06:09:35 +0000260 return ConstantInt::get(C->getContext(), C->getValue()-1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000261}
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000262
Dan Gohman5d56fd42008-05-19 22:14:15 +0000263
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000264static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
265 InstCombiner *IC) {
Chris Lattner78628292009-08-30 19:47:22 +0000266 if (CastInst *CI = dyn_cast<CastInst>(&I))
Chris Lattnerd6164c22009-08-30 20:01:10 +0000267 return IC->Builder->CreateCast(CI->getOpcode(), SO, I.getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000268
269 // Figure out if the constant is the left or the right argument.
270 bool ConstIsRHS = isa<Constant>(I.getOperand(1));
271 Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
272
273 if (Constant *SOC = dyn_cast<Constant>(SO)) {
274 if (ConstIsRHS)
Owen Anderson02b48c32009-07-29 18:55:55 +0000275 return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
276 return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000277 }
278
279 Value *Op0 = SO, *Op1 = ConstOperand;
280 if (!ConstIsRHS)
281 std::swap(Op0, Op1);
Chris Lattnerc7694852009-08-30 07:44:24 +0000282
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000283 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
Chris Lattnerc7694852009-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!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +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 Lattner54826cd2010-01-04 07:53:58 +0000299Instruction *InstCombiner::FoldOpIntoSelect(Instruction &Op, SelectInst *SI) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +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)) {
306 // Bool selects with constant operands can be folded to logical ops.
Chris Lattner03a27b42010-01-04 07:02:48 +0000307 if (SI->getType() == Type::getInt1Ty(SI->getContext())) return 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000308
Chris Lattner54826cd2010-01-04 07:53:58 +0000309 Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, this);
310 Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, this);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000311
Gabor Greifd6da1d02008-04-06 20:25:17 +0000312 return SelectInst::Create(SI->getCondition(), SelectTrueVal,
313 SelectFalseVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000314 }
315 return 0;
316}
317
318
Chris Lattnerf7843b72009-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 Lattner9b61abd2009-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;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000329 PHINode *PN = cast<PHINode>(I.getOperand(0));
330 unsigned NumPHIValues = PN->getNumIncomingValues();
Chris Lattner9b61abd2009-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 Lattnerf7843b72009-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 Lattnerff5cd9d2009-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.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000343 BasicBlock *NonConstBB = 0;
344 for (unsigned i = 0; i != NumPHIValues; ++i)
Chris Lattnerf7843b72009-09-27 19:57:57 +0000345 if (!isa<Constant>(PN->getIncomingValue(i)) ||
346 isa<ConstantExpr>(PN->getIncomingValue(i))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000347 if (NonConstBB) return 0; // More than one non-const value.
348 if (isa<PHINode>(PN->getIncomingValue(i))) return 0; // Itself a phi.
349 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 Lattner9b61abd2009-09-27 20:46:36 +0000361 if (NonConstBB != 0 && !AllowAggressive) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000362 BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
363 if (!BI || !BI->isUnconditional()) return 0;
364 }
365
366 // Okay, we can do the transformation: create the new PHI node.
Gabor Greifd6da1d02008-04-06 20:25:17 +0000367 PHINode *NewPN = PHINode::Create(I.getType(), "");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000368 NewPN->reserveOperandSpace(PN->getNumOperands()/2);
Chris Lattner3980f9b2009-10-21 23:41:58 +0000369 InsertNewInstBefore(NewPN, *PN);
370 NewPN->takeName(PN);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000371
372 // Next, add all of the operands to the PHI.
Chris Lattnerf7843b72009-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 Lattnerff5cd9d2009-09-27 20:18:49 +0000376 Value *TrueV = SI->getTrueValue();
377 Value *FalseV = SI->getFalseValue();
Chris Lattnerda3ee9c2009-09-28 06:49:44 +0000378 BasicBlock *PhiTransBB = PN->getParent();
Chris Lattnerf7843b72009-09-27 19:57:57 +0000379 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattnerff5cd9d2009-09-27 20:18:49 +0000380 BasicBlock *ThisBB = PN->getIncomingBlock(i);
Chris Lattnerda3ee9c2009-09-28 06:49:44 +0000381 Value *TrueVInPred = TrueV->DoPHITranslation(PhiTransBB, ThisBB);
382 Value *FalseVInPred = FalseV->DoPHITranslation(PhiTransBB, ThisBB);
Chris Lattnerf7843b72009-09-27 19:57:57 +0000383 Value *InV = 0;
384 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Chris Lattnerff5cd9d2009-09-27 20:18:49 +0000385 InV = InC->isNullValue() ? FalseVInPred : TrueVInPred;
Chris Lattnerf7843b72009-09-27 19:57:57 +0000386 } else {
387 assert(PN->getIncomingBlock(i) == NonConstBB);
Chris Lattnerff5cd9d2009-09-27 20:18:49 +0000388 InV = SelectInst::Create(PN->getIncomingValue(i), TrueVInPred,
389 FalseVInPred,
Chris Lattnerf7843b72009-09-27 19:57:57 +0000390 "phitmp", NonConstBB->getTerminator());
Chris Lattner3980f9b2009-10-21 23:41:58 +0000391 Worklist.Add(cast<Instruction>(InV));
Chris Lattnerf7843b72009-09-27 19:57:57 +0000392 }
Chris Lattnerff5cd9d2009-09-27 20:18:49 +0000393 NewPN->addIncoming(InV, ThisBB);
Chris Lattnerf7843b72009-09-27 19:57:57 +0000394 }
395 } else if (I.getNumOperands() == 2) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000396 Constant *C = cast<Constant>(I.getOperand(1));
397 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattnerb933ea62007-08-05 08:47:58 +0000398 Value *InV = 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000399 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
400 if (CmpInst *CI = dyn_cast<CmpInst>(&I))
Owen Anderson02b48c32009-07-29 18:55:55 +0000401 InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000402 else
Owen Anderson02b48c32009-07-29 18:55:55 +0000403 InV = ConstantExpr::get(I.getOpcode(), InC, C);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000404 } else {
405 assert(PN->getIncomingBlock(i) == NonConstBB);
406 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
Gabor Greifa645dd32008-05-16 19:29:10 +0000407 InV = BinaryOperator::Create(BO->getOpcode(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000408 PN->getIncomingValue(i), C, "phitmp",
409 NonConstBB->getTerminator());
410 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
Dan Gohmane6803b82009-08-25 23:17:54 +0000411 InV = CmpInst::Create(CI->getOpcode(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000412 CI->getPredicate(),
413 PN->getIncomingValue(i), C, "phitmp",
414 NonConstBB->getTerminator());
415 else
Edwin Törökbd448e32009-07-14 16:55:14 +0000416 llvm_unreachable("Unknown binop!");
Chris Lattner3980f9b2009-10-21 23:41:58 +0000417
418 Worklist.Add(cast<Instruction>(InV));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000419 }
420 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
421 }
422 } else {
423 CastInst *CI = cast<CastInst>(&I);
424 const Type *RetTy = CI->getType();
425 for (unsigned i = 0; i != NumPHIValues; ++i) {
426 Value *InV;
427 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Owen Anderson02b48c32009-07-29 18:55:55 +0000428 InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000429 } else {
430 assert(PN->getIncomingBlock(i) == NonConstBB);
Gabor Greifa645dd32008-05-16 19:29:10 +0000431 InV = CastInst::Create(CI->getOpcode(), PN->getIncomingValue(i),
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000432 I.getType(), "phitmp",
433 NonConstBB->getTerminator());
Chris Lattner3980f9b2009-10-21 23:41:58 +0000434 Worklist.Add(cast<Instruction>(InV));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000435 }
436 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
437 }
438 }
439 return ReplaceInstUsesWith(I, NewPN);
440}
441
Chris Lattner55476162008-01-29 06:52:45 +0000442
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000443/// getICmpCode - Encode a icmp predicate into a three bit mask. These bits
444/// are carefully arranged to allow folding of expressions such as:
445///
446/// (A < B) | (A > B) --> (A != B)
447///
448/// 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)
450///
451/// 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()) {
468 // False -> 0
469 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
479 // True -> 7
480 default:
Edwin Törökbd448e32009-07-14 16:55:14 +0000481 llvm_unreachable("Invalid ICmp predicate!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000482 return 0;
483 }
484}
485
Evan Cheng0ac3a4d2008-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 Chengf1f2cea2008-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 Cheng0ac3a4d2008-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 Chengf1f2cea2008-10-14 18:13:38 +0000502 case FCmpInst::FCMP_ONE: isOrdered = true; return 5; // 101
503 case FCmpInst::FCMP_UNE: return 5; // 101
Evan Cheng0ac3a4d2008-10-14 17:15:11 +0000504 case FCmpInst::FCMP_OLE: isOrdered = true; return 6; // 110
505 case FCmpInst::FCMP_ULE: return 6; // 110
Evan Cheng72988052008-10-14 18:44:08 +0000506 // True -> 7
Evan Cheng0ac3a4d2008-10-14 17:15:11 +0000507 default:
508 // Not expecting FCMP_FALSE and FCMP_TRUE;
Edwin Törökbd448e32009-07-14 16:55:14 +0000509 llvm_unreachable("Unexpected FCmp predicate!");
Evan Cheng0ac3a4d2008-10-14 17:15:11 +0000510 return 0;
511 }
512}
513
Dan Gohmanf17a25c2007-07-18 16:29:46 +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 Gohmanda338742007-09-17 17:31:57 +0000516/// new ICmp instruction. The sign is passed in to determine which kind
Evan Cheng0ac3a4d2008-10-14 17:15:11 +0000517/// of predicate to use in the new icmp instruction.
Chris Lattner41cabbe2010-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 Gohmane6803b82009-08-25 23:17:54 +0000525 return new ICmpInst(ICmpInst::ICMP_SGT, LHS, RHS);
Chris Lattner41cabbe2010-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 Gohmane6803b82009-08-25 23:17:54 +0000531 return new ICmpInst(ICmpInst::ICMP_SGE, LHS, RHS);
Chris Lattner41cabbe2010-01-05 06:59:49 +0000532 return new ICmpInst(ICmpInst::ICMP_UGE, LHS, RHS);
533 case 4:
534 if (Sign)
Dan Gohmane6803b82009-08-25 23:17:54 +0000535 return new ICmpInst(ICmpInst::ICMP_SLT, LHS, RHS);
Chris Lattner41cabbe2010-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 Gohmane6803b82009-08-25 23:17:54 +0000541 return new ICmpInst(ICmpInst::ICMP_SLE, LHS, RHS);
Chris Lattner41cabbe2010-01-05 06:59:49 +0000542 return new ICmpInst(ICmpInst::ICMP_ULE, LHS, RHS);
543 case 7:
544 return ConstantInt::getTrue(LHS->getContext());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000545 }
546}
547
Evan Cheng0ac3a4d2008-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 Lattner03a27b42010-01-04 07:02:48 +0000552 Value *LHS, Value *RHS) {
Evan Cheng0ac3a4d2008-10-14 17:15:11 +0000553 switch (code) {
Edwin Törökbd448e32009-07-14 16:55:14 +0000554 default: llvm_unreachable("Illegal FCmp code!");
Evan Cheng0ac3a4d2008-10-14 17:15:11 +0000555 case 0:
556 if (isordered)
Dan Gohmane6803b82009-08-25 23:17:54 +0000557 return new FCmpInst(FCmpInst::FCMP_ORD, LHS, RHS);
Evan Cheng0ac3a4d2008-10-14 17:15:11 +0000558 else
Dan Gohmane6803b82009-08-25 23:17:54 +0000559 return new FCmpInst(FCmpInst::FCMP_UNO, LHS, RHS);
Evan Cheng0ac3a4d2008-10-14 17:15:11 +0000560 case 1:
561 if (isordered)
Dan Gohmane6803b82009-08-25 23:17:54 +0000562 return new FCmpInst(FCmpInst::FCMP_OGT, LHS, RHS);
Evan Cheng0ac3a4d2008-10-14 17:15:11 +0000563 else
Dan Gohmane6803b82009-08-25 23:17:54 +0000564 return new FCmpInst(FCmpInst::FCMP_UGT, LHS, RHS);
Evan Chengf1f2cea2008-10-14 18:13:38 +0000565 case 2:
566 if (isordered)
Dan Gohmane6803b82009-08-25 23:17:54 +0000567 return new FCmpInst(FCmpInst::FCMP_OEQ, LHS, RHS);
Evan Chengf1f2cea2008-10-14 18:13:38 +0000568 else
Dan Gohmane6803b82009-08-25 23:17:54 +0000569 return new FCmpInst(FCmpInst::FCMP_UEQ, LHS, RHS);
Evan Cheng0ac3a4d2008-10-14 17:15:11 +0000570 case 3:
571 if (isordered)
Dan Gohmane6803b82009-08-25 23:17:54 +0000572 return new FCmpInst(FCmpInst::FCMP_OGE, LHS, RHS);
Evan Cheng0ac3a4d2008-10-14 17:15:11 +0000573 else
Dan Gohmane6803b82009-08-25 23:17:54 +0000574 return new FCmpInst(FCmpInst::FCMP_UGE, LHS, RHS);
Evan Cheng0ac3a4d2008-10-14 17:15:11 +0000575 case 4:
576 if (isordered)
Dan Gohmane6803b82009-08-25 23:17:54 +0000577 return new FCmpInst(FCmpInst::FCMP_OLT, LHS, RHS);
Evan Cheng0ac3a4d2008-10-14 17:15:11 +0000578 else
Dan Gohmane6803b82009-08-25 23:17:54 +0000579 return new FCmpInst(FCmpInst::FCMP_ULT, LHS, RHS);
Evan Cheng0ac3a4d2008-10-14 17:15:11 +0000580 case 5:
581 if (isordered)
Dan Gohmane6803b82009-08-25 23:17:54 +0000582 return new FCmpInst(FCmpInst::FCMP_ONE, LHS, RHS);
Evan Chengf1f2cea2008-10-14 18:13:38 +0000583 else
Dan Gohmane6803b82009-08-25 23:17:54 +0000584 return new FCmpInst(FCmpInst::FCMP_UNE, LHS, RHS);
Evan Chengf1f2cea2008-10-14 18:13:38 +0000585 case 6:
586 if (isordered)
Dan Gohmane6803b82009-08-25 23:17:54 +0000587 return new FCmpInst(FCmpInst::FCMP_OLE, LHS, RHS);
Evan Cheng0ac3a4d2008-10-14 17:15:11 +0000588 else
Dan Gohmane6803b82009-08-25 23:17:54 +0000589 return new FCmpInst(FCmpInst::FCMP_ULE, LHS, RHS);
Chris Lattner03a27b42010-01-04 07:02:48 +0000590 case 7: return ConstantInt::getTrue(LHS->getContext());
Evan Cheng0ac3a4d2008-10-14 17:15:11 +0000591 }
592}
593
Chris Lattner2972b822008-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).
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000596static bool PredicatesFoldable(ICmpInst::Predicate p1, ICmpInst::Predicate p2) {
Nick Lewyckyb0796c62009-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));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000600}
601
Dan Gohmanf17a25c2007-07-18 16:29:46 +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
604// guaranteed to be a binary operator.
605Instruction *InstCombiner::OptAndOp(Instruction *Op,
606 ConstantInt *OpRHS,
607 ConstantInt *AndRHS,
608 BinaryOperator &TheAnd) {
609 Value *X = Op->getOperand(0);
610 Constant *Together = 0;
611 if (!Op->isShift())
Owen Anderson02b48c32009-07-29 18:55:55 +0000612 Together = ConstantExpr::getAnd(AndRHS, OpRHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000613
614 switch (Op->getOpcode()) {
615 case Instruction::Xor:
616 if (Op->hasOneUse()) {
617 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
Chris Lattnerc7694852009-08-30 07:44:24 +0000618 Value *And = Builder->CreateAnd(X, AndRHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000619 And->takeName(Op);
Gabor Greifa645dd32008-05-16 19:29:10 +0000620 return BinaryOperator::CreateXor(And, Together);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000621 }
622 break;
623 case Instruction::Or:
624 if (Together == AndRHS) // (X | C) & C --> C
625 return ReplaceInstUsesWith(TheAnd, AndRHS);
626
627 if (Op->hasOneUse() && Together != OpRHS) {
628 // (X | C1) & C2 --> (X | (C1&C2)) & C2
Chris Lattnerc7694852009-08-30 07:44:24 +0000629 Value *Or = Builder->CreateOr(X, Together);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000630 Or->takeName(Op);
Gabor Greifa645dd32008-05-16 19:29:10 +0000631 return BinaryOperator::CreateAnd(Or, AndRHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000632 }
633 break;
634 case Instruction::Add:
635 if (Op->hasOneUse()) {
636 // 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 Lattner77fe28f2010-01-05 06:03:12 +0000639 const APInt &AndRHSV = cast<ConstantInt>(AndRHS)->getValue();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000640
Chris Lattner77fe28f2010-01-05 06:03:12 +0000641 // If there is only one bit set.
642 if (AndRHSV.isPowerOf2()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +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.
646 const APInt& AddRHS = cast<ConstantInt>(OpRHS)->getValue();
647
648 // 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 {
658 // Pull the XOR out of the AND.
Chris Lattnerc7694852009-08-30 07:44:24 +0000659 Value *NewAnd = Builder->CreateAnd(X, AndRHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000660 NewAnd->takeName(Op);
Gabor Greifa645dd32008-05-16 19:29:10 +0000661 return BinaryOperator::CreateXor(NewAnd, AndRHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000662 }
663 }
664 }
665 }
666 break;
667
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 //
672 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
673 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
674 APInt ShlMask(APInt::getHighBitsSet(BitWidth, BitWidth-OpRHSVal));
Chris Lattner03a27b42010-01-04 07:02:48 +0000675 ConstantInt *CI = ConstantInt::get(AndRHS->getContext(),
676 AndRHS->getValue() & ShlMask);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000677
678 if (CI->getValue() == ShlMask) {
679 // Masking out bits that the shift already masks
680 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
681 } else if (CI != AndRHS) { // Reducing bits set in and.
682 TheAnd.setOperand(1, CI);
683 return &TheAnd;
684 }
685 break;
686 }
Chris Lattner03a27b42010-01-04 07:02:48 +0000687 case Instruction::LShr: {
Dan Gohmanf17a25c2007-07-18 16:29:46 +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 //
692 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
693 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
694 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
Chris Lattner03a27b42010-01-04 07:02:48 +0000695 ConstantInt *CI = ConstantInt::get(Op->getContext(),
696 AndRHS->getValue() & ShrMask);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000697
698 if (CI->getValue() == ShrMask) {
699 // Masking out bits that the shift already masks.
700 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()) {
712 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
713 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
714 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
Chris Lattner03a27b42010-01-04 07:02:48 +0000715 Constant *C = ConstantInt::get(Op->getContext(),
716 AndRHS->getValue() & ShrMask);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000717 if (C == AndRHS) { // Masking out bits shifted in.
718 // (Val ashr C1) & C2 -> (Val lshr C1) & C2
719 // Make the argument unsigned.
720 Value *ShVal = Op->getOperand(0);
Chris Lattnerc7694852009-08-30 07:44:24 +0000721 ShVal = Builder->CreateLShr(ShVal, OpRHS, Op->getName());
Gabor Greifa645dd32008-05-16 19:29:10 +0000722 return BinaryOperator::CreateAnd(ShVal, AndRHS, TheAnd.getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000723 }
724 }
725 break;
726 }
727 return 0;
728}
729
730
731/// 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
733/// (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
735/// insert new instructions.
736Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
737 bool isSigned, bool Inside,
738 Instruction &IB) {
Owen Anderson02b48c32009-07-29 18:55:55 +0000739 assert(cast<ConstantInt>(ConstantExpr::getICmp((isSigned ?
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000740 ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
741 "Lo is not <= Hi in range emission code!");
742
743 if (Inside) {
744 if (Lo == Hi) // Trivially false.
Dan Gohmane6803b82009-08-25 23:17:54 +0000745 return new ICmpInst(ICmpInst::ICMP_NE, V, V);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000746
747 // V >= Min && V < Hi --> V < Hi
748 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
749 ICmpInst::Predicate pred = (isSigned ?
750 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
Dan Gohmane6803b82009-08-25 23:17:54 +0000751 return new ICmpInst(pred, V, Hi);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000752 }
753
754 // Emit V-Lo <u Hi-Lo
Owen Anderson02b48c32009-07-29 18:55:55 +0000755 Constant *NegLo = ConstantExpr::getNeg(Lo);
Chris Lattnerc7694852009-08-30 07:44:24 +0000756 Value *Add = Builder->CreateAdd(V, NegLo, V->getName()+".off");
Owen Anderson02b48c32009-07-29 18:55:55 +0000757 Constant *UpperBound = ConstantExpr::getAdd(NegLo, Hi);
Dan Gohmane6803b82009-08-25 23:17:54 +0000758 return new ICmpInst(ICmpInst::ICMP_ULT, Add, UpperBound);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000759 }
760
761 if (Lo == Hi) // Trivially true.
Dan Gohmane6803b82009-08-25 23:17:54 +0000762 return new ICmpInst(ICmpInst::ICMP_EQ, V, V);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000763
764 // V < Min || V >= Hi -> V > Hi-1
Dan Gohmanfe91cd62009-08-12 16:04:34 +0000765 Hi = SubOne(cast<ConstantInt>(Hi));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000766 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
767 ICmpInst::Predicate pred = (isSigned ?
768 ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
Dan Gohmane6803b82009-08-25 23:17:54 +0000769 return new ICmpInst(pred, V, Hi);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000770 }
771
772 // Emit V-Lo >u Hi-1-Lo
773 // Note that Hi has already had one subtracted from it, above.
Owen Anderson02b48c32009-07-29 18:55:55 +0000774 ConstantInt *NegLo = cast<ConstantInt>(ConstantExpr::getNeg(Lo));
Chris Lattnerc7694852009-08-30 07:44:24 +0000775 Value *Add = Builder->CreateAdd(V, NegLo, V->getName()+".off");
Owen Anderson02b48c32009-07-29 18:55:55 +0000776 Constant *LowerBound = ConstantExpr::getAdd(NegLo, Hi);
Dan Gohmane6803b82009-08-25 23:17:54 +0000777 return new ICmpInst(ICmpInst::ICMP_UGT, Add, LowerBound);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000778}
779
780// 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.
784static bool isRunOfOnes(ConstantInt *Val, uint32_t &MB, uint32_t &ME) {
785 const APInt& V = Val->getValue();
786 uint32_t BitWidth = Val->getType()->getBitWidth();
787 if (!APIntOps::isShiftedMask(BitWidth, V)) return false;
788
789 // look for the first zero bit after the run of ones
790 MB = BitWidth - ((V - 1) ^ V).countLeadingZeros();
791 // look for the first non-zero bit
792 ME = V.getActiveBits();
793 return true;
794}
795
796/// 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:
799///
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,
807 ConstantInt *Mask, bool isSub,
808 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 Anderson02b48c32009-07-29 18:55:55 +0000818 if (ConstantExpr::getAnd(N, Mask) == Mask) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000819 // If the AndRHS is a power of two minus one (0+1+), this is simple.
820 if ((Mask->getValue().countLeadingZeros() +
821 Mask->getValue().countPopulation()) ==
822 Mask->getValue().getBitWidth())
823 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.
828 uint32_t MB = 0, ME = 0;
829 if (isRunOfOnes(Mask, MB, ME)) { // begin/end bit of run, inclusive
830 uint32_t BitWidth = cast<IntegerType>(RHS->getType())->getBitWidth();
831 APInt Mask(APInt::getLowBitsSet(BitWidth, MB-1));
832 if (MaskedValueIsZero(RHS, Mask))
833 break;
834 }
835 }
836 return 0;
837 case Instruction::Or:
838 case Instruction::Xor:
839 // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
840 if ((Mask->getValue().countLeadingZeros() +
841 Mask->getValue().countPopulation()) == Mask->getValue().getBitWidth()
Owen Anderson02b48c32009-07-29 18:55:55 +0000842 && ConstantExpr::getAnd(N, Mask)->isNullValue())
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000843 break;
844 return 0;
845 }
846
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000847 if (isSub)
Chris Lattnerc7694852009-08-30 07:44:24 +0000848 return Builder->CreateSub(LHSI->getOperand(0), RHS, "fold");
849 return Builder->CreateAdd(LHSI->getOperand(0), RHS, "fold");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000850}
851
Chris Lattner0631ea72008-11-16 05:06:21 +0000852/// FoldAndOfICmps - Fold (icmp)&(icmp) if possible.
853Instruction *InstCombiner::FoldAndOfICmps(Instruction &I,
854 ICmpInst *LHS, ICmpInst *RHS) {
Chris Lattner41cabbe2010-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 Lattner0631ea72008-11-16 05:06:21 +0000874
Chris Lattnerf3803482008-11-16 05:10:52 +0000875 // This only handles icmp of constants: (icmp1 A, C1) & (icmp2 B, C2).
Chris Lattner41cabbe2010-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 Lattnerf3803482008-11-16 05:10:52 +0000880
Chris Lattner163e6ab2009-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 Lattnerf3803482008-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 Lattner0631ea72008-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 Lattner665298f2008-11-16 05:14:43 +0000913 bool ShouldSwap;
Nick Lewyckyb0796c62009-10-25 05:20:17 +0000914 if (CmpInst::isSigned(LHSCC) ||
Chris Lattner0631ea72008-11-16 05:06:21 +0000915 (ICmpInst::isEquality(LHSCC) &&
Nick Lewyckyb0796c62009-10-25 05:20:17 +0000916 CmpInst::isSigned(RHSCC)))
Chris Lattner665298f2008-11-16 05:14:43 +0000917 ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
Chris Lattner0631ea72008-11-16 05:06:21 +0000918 else
Chris Lattner665298f2008-11-16 05:14:43 +0000919 ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
920
921 if (ShouldSwap) {
Chris Lattner0631ea72008-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 Lattner41cabbe2010-01-05 06:59:49 +0000931 // (from the icmp folding check above), that the two constants
Chris Lattner0631ea72008-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) {
Edwin Törökbd448e32009-07-14 16:55:14 +0000936 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner0631ea72008-11-16 05:06:21 +0000937 case ICmpInst::ICMP_EQ:
938 switch (RHSCC) {
Edwin Törökbd448e32009-07-14 16:55:14 +0000939 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner0631ea72008-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 Lattner03a27b42010-01-04 07:02:48 +0000943 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getContext()));
Chris Lattner0631ea72008-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) {
Edwin Törökbd448e32009-07-14 16:55:14 +0000951 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner0631ea72008-11-16 05:06:21 +0000952 case ICmpInst::ICMP_ULT:
Dan Gohmanfe91cd62009-08-12 16:04:34 +0000953 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X u< 14) -> X < 13
Dan Gohmane6803b82009-08-25 23:17:54 +0000954 return new ICmpInst(ICmpInst::ICMP_ULT, Val, LHSCst);
Chris Lattner0631ea72008-11-16 05:06:21 +0000955 break; // (X != 13 & X u< 15) -> no change
956 case ICmpInst::ICMP_SLT:
Dan Gohmanfe91cd62009-08-12 16:04:34 +0000957 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X s< 14) -> X < 13
Dan Gohmane6803b82009-08-25 23:17:54 +0000958 return new ICmpInst(ICmpInst::ICMP_SLT, Val, LHSCst);
Chris Lattner0631ea72008-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 Gohmanfe91cd62009-08-12 16:04:34 +0000965 if (LHSCst == SubOne(RHSCst)){// (X != 13 & X != 14) -> X-13 >u 1
Owen Anderson02b48c32009-07-29 18:55:55 +0000966 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
Chris Lattnerc7694852009-08-30 07:44:24 +0000967 Value *Add = Builder->CreateAdd(Val, AddCST, Val->getName()+".off");
Dan Gohmane6803b82009-08-25 23:17:54 +0000968 return new ICmpInst(ICmpInst::ICMP_UGT, Add,
Owen Andersoneacb44d2009-07-24 23:12:02 +0000969 ConstantInt::get(Add->getType(), 1));
Chris Lattner0631ea72008-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) {
Edwin Törökbd448e32009-07-14 16:55:14 +0000976 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner0631ea72008-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 Lattner03a27b42010-01-04 07:02:48 +0000979 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getContext()));
Chris Lattner0631ea72008-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) {
Edwin Törökbd448e32009-07-14 16:55:14 +0000991 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner0631ea72008-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 Lattner03a27b42010-01-04 07:02:48 +0000994 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getContext()));
Chris Lattner0631ea72008-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) {
Edwin Törökbd448e32009-07-14 16:55:14 +00001006 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner0631ea72008-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 Gohmanfe91cd62009-08-12 16:04:34 +00001013 if (RHSCst == AddOne(LHSCst)) // (X u> 13 & X != 14) -> X u> 14
Dan Gohmane6803b82009-08-25 23:17:54 +00001014 return new ICmpInst(LHSCC, Val, RHSCst);
Chris Lattner0631ea72008-11-16 05:06:21 +00001015 break; // (X u> 13 & X != 15) -> no change
Chris Lattner0c678e52008-11-16 05:20:07 +00001016 case ICmpInst::ICMP_ULT: // (X u> 13 & X u< 15) -> (X-14) <u 1
Dan Gohmanfe91cd62009-08-12 16:04:34 +00001017 return InsertRangeTest(Val, AddOne(LHSCst),
Owen Anderson24be4c12009-07-03 00:17:18 +00001018 RHSCst, false, true, I);
Chris Lattner0631ea72008-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) {
Edwin Törökbd448e32009-07-14 16:55:14 +00001025 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner0631ea72008-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 Gohmanfe91cd62009-08-12 16:04:34 +00001032 if (RHSCst == AddOne(LHSCst)) // (X s> 13 & X != 14) -> X s> 14
Dan Gohmane6803b82009-08-25 23:17:54 +00001033 return new ICmpInst(LHSCC, Val, RHSCst);
Chris Lattner0631ea72008-11-16 05:06:21 +00001034 break; // (X s> 13 & X != 15) -> no change
Chris Lattner0c678e52008-11-16 05:20:07 +00001035 case ICmpInst::ICMP_SLT: // (X s> 13 & X s< 15) -> (X-14) s< 1
Dan Gohmanfe91cd62009-08-12 16:04:34 +00001036 return InsertRangeTest(Val, AddOne(LHSCst),
Owen Anderson24be4c12009-07-03 00:17:18 +00001037 RHSCst, true, true, I);
Chris Lattner0631ea72008-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 Lattner0631ea72008-11-16 05:06:21 +00001043
1044 return 0;
1045}
1046
Chris Lattner93a359a2009-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 Lattner03a27b42010-01-04 07:02:48 +00001058 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getContext()));
Dan Gohmane6803b82009-08-25 23:17:54 +00001059 return new FCmpInst(FCmpInst::FCMP_ORD,
Chris Lattner93a359a2009-07-23 05:14:02 +00001060 LHS->getOperand(0), RHS->getOperand(0));
1061 }
Chris Lattnercf373552009-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 Gohmane6803b82009-08-25 23:17:54 +00001067 return new FCmpInst(FCmpInst::FCMP_ORD,
Chris Lattnercf373552009-07-23 05:32:17 +00001068 LHS->getOperand(0), RHS->getOperand(0));
Chris Lattner93a359a2009-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 Gohmane6803b82009-08-25 23:17:54 +00001086 return new FCmpInst((FCmpInst::Predicate)Op0CC, Op0LHS, Op0RHS);
Chris Lattner93a359a2009-07-23 05:14:02 +00001087
1088 if (Op0CC == FCmpInst::FCMP_FALSE || Op1CC == FCmpInst::FCMP_FALSE)
Chris Lattner03a27b42010-01-04 07:02:48 +00001089 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getContext()));
Chris Lattner93a359a2009-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 Lattner03a27b42010-01-04 07:02:48 +00001113 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getContext()));
Chris Lattner93a359a2009-07-23 05:14:02 +00001114 // ord && ueq -> ord && (uno || eq) -> oeq
Chris Lattner03a27b42010-01-04 07:02:48 +00001115 return cast<Instruction>(getFCmpValue(true, Op1Pred, Op0LHS, Op0RHS));
Chris Lattner93a359a2009-07-23 05:14:02 +00001116 }
1117 }
1118
1119 return 0;
1120}
1121
Chris Lattner0631ea72008-11-16 05:06:21 +00001122
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001123Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
1124 bool Changed = SimplifyCommutative(I);
1125 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1126
Chris Lattnera3e46f62009-11-10 00:55:12 +00001127 if (Value *V = SimplifyAndInst(Op0, Op1, TD))
1128 return ReplaceInstUsesWith(I, V);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001129
1130 // See if we can simplify any instructions used by the instruction whose sole
1131 // purpose is to compute bits we don't care about.
Dan Gohman8fd520a2009-06-15 22:12:54 +00001132 if (SimplifyDemandedInstructionBits(I))
Nick Lewycky72c812c2010-01-02 15:25:44 +00001133 return &I;
Dan Gohman8fd520a2009-06-15 22:12:54 +00001134
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001135 if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner4580d452009-10-11 22:00:32 +00001136 const APInt &AndRHSMask = AndRHS->getValue();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001137 APInt NotAndRHS(~AndRHSMask);
1138
1139 // Optimize a variety of ((val OP C1) & C2) combinations...
Chris Lattner4580d452009-10-11 22:00:32 +00001140 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001141 Value *Op0LHS = Op0I->getOperand(0);
1142 Value *Op0RHS = Op0I->getOperand(1);
1143 switch (Op0I->getOpcode()) {
Chris Lattner4580d452009-10-11 22:00:32 +00001144 default: break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001145 case Instruction::Xor:
1146 case Instruction::Or:
1147 // If the mask is only needed on one incoming arm, push it up.
Chris Lattner4580d452009-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);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001162 }
1163
1164 break;
1165 case Instruction::Add:
1166 // ((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 Greifa645dd32008-05-16 19:29:10 +00001170 return BinaryOperator::CreateAnd(V, AndRHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001171 if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
Gabor Greifa645dd32008-05-16 19:29:10 +00001172 return BinaryOperator::CreateAnd(V, AndRHS); // Add commutes
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001173 break;
1174
1175 case Instruction::Sub:
1176 // ((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 Greifa645dd32008-05-16 19:29:10 +00001180 return BinaryOperator::CreateAnd(V, AndRHS);
Nick Lewyckyffed71b2008-07-09 04:32:37 +00001181
Nick Lewyckya349ba42008-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 Lewyckyffed71b2008-07-09 04:32:37 +00001189 ConstantInt *A = dyn_cast<ConstantInt>(Op0LHS);
Nick Lewyckya349ba42008-07-10 05:51:40 +00001190 if (!(A && A->isZero()) && // avoid infinite recursion.
1191 MaskedValueIsZero(Op0LHS, Mask)) {
Chris Lattnerc7694852009-08-30 07:44:24 +00001192 Value *NewNeg = Builder->CreateNeg(Op0RHS);
Nick Lewyckyffed71b2008-07-09 04:32:37 +00001193 return BinaryOperator::CreateAnd(NewNeg, AndRHS);
1194 }
1195 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001196 break;
Nick Lewycky659ed4d2008-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 Lewyckyf1b12222008-07-09 07:35:26 +00001202 if (AndRHSMask == 1 && Op0LHS == AndRHS) {
Chris Lattnerc7694852009-08-30 07:44:24 +00001203 Value *NewICmp =
1204 Builder->CreateICmpEQ(Op0RHS, Constant::getNullValue(I.getType()));
Nick Lewycky659ed4d2008-07-09 05:20:13 +00001205 return new ZExtInst(NewICmp, I.getType());
1206 }
1207 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001208 }
1209
1210 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
1211 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
1212 return Res;
1213 } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
1214 // 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))) {
1218 if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
1219 CastOp->getNumOperands() == 2)
Chris Lattner6e060db2009-10-26 15:40:07 +00001220 if (ConstantInt *AndCI =dyn_cast<ConstantInt>(CastOp->getOperand(1))){
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001221 if (CastOp->getOpcode() == Instruction::And) {
1222 // Change: and (cast (and X, C1) to T), C2
1223 // 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 Lattnerc7694852009-08-30 07:44:24 +00001226 Value *NewCast = Builder->CreateTruncOrBitCast(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001227 CastOp->getOperand(0), I.getType(),
1228 CastOp->getName()+".shrunk");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001229 // trunc_or_bitcast(C1)&C2
Chris Lattnerc7694852009-08-30 07:44:24 +00001230 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
Owen Anderson02b48c32009-07-29 18:55:55 +00001231 C3 = ConstantExpr::getAnd(C3, AndRHS);
Gabor Greifa645dd32008-05-16 19:29:10 +00001232 return BinaryOperator::CreateAnd(NewCast, C3);
Dan Gohmanf17a25c2007-07-18 16:29:46 +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 Lattnerc7694852009-08-30 07:44:24 +00001236 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
Owen Anderson02b48c32009-07-29 18:55:55 +00001237 if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS)
Owen Anderson24be4c12009-07-03 00:17:18 +00001238 // trunc(C1)&C2
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001239 return ReplaceInstUsesWith(I, AndRHS);
1240 }
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00001241 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001242 }
1243 }
1244
1245 // Try to fold constant and into select arguments.
1246 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner54826cd2010-01-04 07:53:58 +00001247 if (Instruction *R = FoldOpIntoSelect(I, SI))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001248 return R;
1249 if (isa<PHINode>(Op0))
1250 if (Instruction *NV = FoldOpIntoPhi(I))
1251 return NV;
1252 }
1253
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001254
1255 // (~A & ~B) == (~(A | B)) - De Morgan's Law
Chris Lattnera3e46f62009-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
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001264 {
1265 Value *A = 0, *B = 0, *C = 0, *D = 0;
Chris Lattnera3e46f62009-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);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001271
Chris Lattnera3e46f62009-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);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001277
1278 if (Op0->hasOneUse() &&
Dan Gohmancdff2122009-08-12 16:23:25 +00001279 match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +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 Wendlingce5e0af2008-11-30 13:08:13 +00001289
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001290 if (Op1->hasOneUse() &&
Dan Gohmancdff2122009-08-12 16:23:25 +00001291 match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001292 if (B == Op0) { // B&(A^B) -> B&(B^A)
1293 cast<BinaryOperator>(Op1)->swapOperands();
1294 std::swap(A, B);
1295 }
Chris Lattnerc7694852009-08-30 07:44:24 +00001296 if (A == Op0) // A&(A^B) -> A & ~B
1297 return BinaryOperator::CreateAnd(A, Builder->CreateNot(B, "tmp"));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001298 }
Bill Wendlingce5e0af2008-11-30 13:08:13 +00001299
1300 // (A&((~A)|B)) -> A&B
Dan Gohmancdff2122009-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 Lattner9db479f2008-12-01 05:16:26 +00001303 return BinaryOperator::CreateAnd(A, Op1);
Dan Gohmancdff2122009-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 Lattner9db479f2008-12-01 05:16:26 +00001306 return BinaryOperator::CreateAnd(A, Op0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001307 }
1308
Chris Lattner41cabbe2010-01-05 06:59:49 +00001309 if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1))
Chris Lattner0631ea72008-11-16 05:06:21 +00001310 if (ICmpInst *LHS = dyn_cast<ICmpInst>(Op0))
1311 if (Instruction *Res = FoldAndOfICmps(I, LHS, RHS))
1312 return Res;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001313
1314 // fold (and (cast A), (cast B)) -> (cast (and A, B))
1315 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 Lattnercf373552009-07-23 05:32:17 +00001319 if (SrcTy == Op1C->getOperand(0)->getType() &&
1320 SrcTy->isIntOrIntVector() &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001321 // Only do this if the casts both really cause code to be generated.
Chris Lattner54826cd2010-01-04 07:53:58 +00001322 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
1323 I.getType()) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001324 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
Chris Lattner54826cd2010-01-04 07:53:58 +00001325 I.getType())) {
Chris Lattnerc7694852009-08-30 07:44:24 +00001326 Value *NewOp = Builder->CreateAnd(Op0C->getOperand(0),
1327 Op1C->getOperand(0), I.getName());
Gabor Greifa645dd32008-05-16 19:29:10 +00001328 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001329 }
1330 }
1331
1332 // (X >> Z) & (Y >> Z) -> (X&Y) >> Z for all shifts.
1333 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
1334 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
1335 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
1336 SI0->getOperand(1) == SI1->getOperand(1) &&
1337 (SI0->hasOneUse() || SI1->hasOneUse())) {
Chris Lattnerc7694852009-08-30 07:44:24 +00001338 Value *NewOp =
1339 Builder->CreateAnd(SI0->getOperand(0), SI1->getOperand(0),
1340 SI0->getName());
Gabor Greifa645dd32008-05-16 19:29:10 +00001341 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001342 SI1->getOperand(1));
1343 }
1344 }
1345
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00001346 // If and'ing two fcmp, try combine them into one.
Chris Lattner91882432007-10-24 05:38:08 +00001347 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
Chris Lattner93a359a2009-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 Lattner91882432007-10-24 05:38:08 +00001351 }
Nick Lewyckyffed71b2008-07-09 04:32:37 +00001352
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001353 return Changed ? &I : 0;
1354}
1355
Chris Lattner567f5112008-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);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001388 }
Chris Lattner567f5112008-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 Lattner44448592008-10-08 06:42:28 +00001408 ByteMask &= (~0U >> (32-ByteValues.size()));
Chris Lattner567f5112008-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 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001450 }
1451
Chris Lattner567f5112008-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);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001459
Chris Lattner567f5112008-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 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +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 Lattner567f5112008-10-05 02:13:19 +00001477 if (ByteValues[DestByteNo] && ByteValues[DestByteNo] != V)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001478 return true;
Chris Lattner567f5112008-10-05 02:13:19 +00001479 ByteValues[DestByteNo] = V;
Dan Gohmanf17a25c2007-07-18 16:29:46 +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) {
1486 const IntegerType *ITy = dyn_cast<IntegerType>(I.getType());
Chris Lattner567f5112008-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)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001490 return 0; // Can only bswap pairs of bytes. Can't do vectors.
1491
1492 /// ByteValues - For each byte of the result, we keep track of which value
1493 /// defines each byte.
1494 SmallVector<Value*, 8> ByteValues;
1495 ByteValues.resize(ITy->getBitWidth()/8);
1496
1497 // Try to find all the pieces corresponding to the bswap.
Chris Lattner567f5112008-10-05 02:13:19 +00001498 uint32_t ByteMask = ~0U >> (32-ByteValues.size());
1499 if (CollectBSwapParts(&I, 0, ByteMask, ByteValues))
Dan Gohmanf17a25c2007-07-18 16:29:46 +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 Carrutha228e392007-08-04 01:51:18 +00001510 const Type *Tys[] = { ITy };
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001511 Module *M = I.getParent()->getParent()->getParent();
Chandler Carrutha228e392007-08-04 01:51:18 +00001512 Function *F = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 1);
Gabor Greifd6da1d02008-04-06 20:25:17 +00001513 return CallInst::Create(F, V);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001514}
1515
Chris Lattnerdd7772b2008-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 Lattner03a27b42010-01-04 07:02:48 +00001520 Value *C, Value *D) {
Chris Lattnerd09b5ba2008-11-16 04:26:55 +00001521 // If A is not a select of -1/0, this cannot match.
Chris Lattner641ea462008-11-16 04:46:19 +00001522 Value *Cond = 0;
Dan Gohmancdff2122009-08-12 16:23:25 +00001523 if (!match(A, m_SelectCst<-1, 0>(m_Value(Cond))))
Chris Lattnerdd7772b2008-11-16 04:24:12 +00001524 return 0;
1525
Chris Lattnerd09b5ba2008-11-16 04:26:55 +00001526 // ((cond?-1:0)&C) | (B&(cond?0:-1)) -> cond ? C : B.
Dan Gohmancdff2122009-08-12 16:23:25 +00001527 if (match(D, m_SelectCst<0, -1>(m_Specific(Cond))))
Chris Lattnerd09b5ba2008-11-16 04:26:55 +00001528 return SelectInst::Create(Cond, C, B);
Dan Gohmancdff2122009-08-12 16:23:25 +00001529 if (match(D, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond)))))
Chris Lattnerd09b5ba2008-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 Gohmancdff2122009-08-12 16:23:25 +00001532 if (match(B, m_SelectCst<0, -1>(m_Specific(Cond))))
Chris Lattnerd09b5ba2008-11-16 04:26:55 +00001533 return SelectInst::Create(Cond, C, D);
Dan Gohmancdff2122009-08-12 16:23:25 +00001534 if (match(B, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond)))))
Chris Lattnerd09b5ba2008-11-16 04:26:55 +00001535 return SelectInst::Create(Cond, C, D);
Chris Lattnerdd7772b2008-11-16 04:24:12 +00001536 return 0;
1537}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001538
Chris Lattner0c678e52008-11-16 05:20:07 +00001539/// FoldOrOfICmps - Fold (icmp)|(icmp) if possible.
1540Instruction *InstCombiner::FoldOrOfICmps(Instruction &I,
1541 ICmpInst *LHS, ICmpInst *RHS) {
Chris Lattner41cabbe2010-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 Lattner0c678e52008-11-16 05:20:07 +00001561
1562 // This only handles icmp of constants: (icmp1 A, C1) | (icmp2 B, C2).
Chris Lattner41cabbe2010-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 Lattner163e6ab2009-11-29 00:51:17 +00001567
Chris Lattner163e6ab2009-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 Lattner0c678e52008-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 Lewyckyb0796c62009-10-25 05:20:17 +00001592 if (CmpInst::isSigned(LHSCC) ||
Chris Lattner0c678e52008-11-16 05:20:07 +00001593 (ICmpInst::isEquality(LHSCC) &&
Nick Lewyckyb0796c62009-10-25 05:20:17 +00001594 CmpInst::isSigned(RHSCC)))
Chris Lattner0c678e52008-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 Lattner41cabbe2010-01-05 06:59:49 +00001609 // icmp folding check above), that the two constants are not
Chris Lattner0c678e52008-11-16 05:20:07 +00001610 // equal.
1611 assert(LHSCst != RHSCst && "Compares not folded above?");
1612
1613 switch (LHSCC) {
Edwin Törökbd448e32009-07-14 16:55:14 +00001614 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner0c678e52008-11-16 05:20:07 +00001615 case ICmpInst::ICMP_EQ:
1616 switch (RHSCC) {
Edwin Törökbd448e32009-07-14 16:55:14 +00001617 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner0c678e52008-11-16 05:20:07 +00001618 case ICmpInst::ICMP_EQ:
Dan Gohmanfe91cd62009-08-12 16:04:34 +00001619 if (LHSCst == SubOne(RHSCst)) {
Owen Anderson24be4c12009-07-03 00:17:18 +00001620 // (X == 13 | X == 14) -> X-13 <u 2
Owen Anderson02b48c32009-07-29 18:55:55 +00001621 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
Chris Lattnerc7694852009-08-30 07:44:24 +00001622 Value *Add = Builder->CreateAdd(Val, AddCST, Val->getName()+".off");
Dan Gohmanfe91cd62009-08-12 16:04:34 +00001623 AddCST = ConstantExpr::getSub(AddOne(RHSCst), LHSCst);
Dan Gohmane6803b82009-08-25 23:17:54 +00001624 return new ICmpInst(ICmpInst::ICMP_ULT, Add, AddCST);
Chris Lattner0c678e52008-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) {
Edwin Törökbd448e32009-07-14 16:55:14 +00001638 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner0c678e52008-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 Lattner03a27b42010-01-04 07:02:48 +00001646 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getContext()));
Chris Lattner0c678e52008-11-16 05:20:07 +00001647 }
1648 break;
1649 case ICmpInst::ICMP_ULT:
1650 switch (RHSCC) {
Edwin Törökbd448e32009-07-14 16:55:14 +00001651 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner0c678e52008-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 Gohmanfe91cd62009-08-12 16:04:34 +00001659 return InsertRangeTest(Val, LHSCst, AddOne(RHSCst),
Owen Anderson24be4c12009-07-03 00:17:18 +00001660 false, false, I);
Chris Lattner0c678e52008-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) {
Edwin Törökbd448e32009-07-14 16:55:14 +00001672 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner0c678e52008-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 Gohmanfe91cd62009-08-12 16:04:34 +00001680 return InsertRangeTest(Val, LHSCst, AddOne(RHSCst),
Owen Anderson24be4c12009-07-03 00:17:18 +00001681 true, false, I);
Chris Lattner0c678e52008-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) {
Edwin Törökbd448e32009-07-14 16:55:14 +00001693 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner0c678e52008-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 Lattner03a27b42010-01-04 07:02:48 +00001701 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getContext()));
Chris Lattner0c678e52008-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) {
Edwin Törökbd448e32009-07-14 16:55:14 +00001708 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner0c678e52008-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 Lattner03a27b42010-01-04 07:02:48 +00001716 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getContext()));
Chris Lattner0c678e52008-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 Lattner57e66fa2009-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 Lattner03a27b42010-01-04 07:02:48 +00001735 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getContext()));
Chris Lattner57e66fa2009-07-23 05:46:22 +00001736
1737 // Otherwise, no need to compare the two constants, compare the
1738 // rest.
Dan Gohmane6803b82009-08-25 23:17:54 +00001739 return new FCmpInst(FCmpInst::FCMP_UNO,
Chris Lattner57e66fa2009-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 Gohmane6803b82009-08-25 23:17:54 +00001747 return new FCmpInst(FCmpInst::FCMP_UNO,
Chris Lattner57e66fa2009-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 Gohmane6803b82009-08-25 23:17:54 +00001765 return new FCmpInst((FCmpInst::Predicate)Op0CC,
Chris Lattner57e66fa2009-07-23 05:46:22 +00001766 Op0LHS, Op0RHS);
1767 if (Op0CC == FCmpInst::FCMP_TRUE || Op1CC == FCmpInst::FCMP_TRUE)
Chris Lattner03a27b42010-01-04 07:02:48 +00001768 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getContext()));
Chris Lattner57e66fa2009-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 Lattner03a27b42010-01-04 07:02:48 +00001780 Value *RV = getFCmpValue(Op0Ordered, Op0Pred|Op1Pred, Op0LHS, Op0RHS);
Chris Lattner57e66fa2009-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 Wendlingdae376a2008-12-01 08:23:25 +00001790/// FoldOrWithConstants - This helper function folds:
1791///
Bill Wendling236a1192008-12-02 05:09:00 +00001792/// ((A | B) & C1) | (B & C2)
Bill Wendlingdae376a2008-12-01 08:23:25 +00001793///
1794/// into:
1795///
Bill Wendling236a1192008-12-02 05:09:00 +00001796/// (A & C1) | B
Bill Wendling9912f712008-12-01 08:32:40 +00001797///
Bill Wendling236a1192008-12-02 05:09:00 +00001798/// when the XOR of the two constants is "all ones" (-1).
Bill Wendling9912f712008-12-01 08:32:40 +00001799Instruction *InstCombiner::FoldOrWithConstants(BinaryOperator &I, Value *Op,
Bill Wendlingdae376a2008-12-01 08:23:25 +00001800 Value *A, Value *B, Value *C) {
Bill Wendlingfc5b8e62008-12-02 05:06:43 +00001801 ConstantInt *CI1 = dyn_cast<ConstantInt>(C);
1802 if (!CI1) return 0;
Bill Wendlingdae376a2008-12-01 08:23:25 +00001803
Bill Wendling0a0dcaf2008-12-02 06:24:20 +00001804 Value *V1 = 0;
1805 ConstantInt *CI2 = 0;
Dan Gohmancdff2122009-08-12 16:23:25 +00001806 if (!match(Op, m_And(m_Value(V1), m_ConstantInt(CI2)))) return 0;
Bill Wendlingdae376a2008-12-01 08:23:25 +00001807
Bill Wendling86ee3162008-12-02 06:18:11 +00001808 APInt Xor = CI1->getValue() ^ CI2->getValue();
1809 if (!Xor.isAllOnesValue()) return 0;
1810
Bill Wendling0a0dcaf2008-12-02 06:24:20 +00001811 if (V1 == A || V1 == B) {
Chris Lattnerc7694852009-08-30 07:44:24 +00001812 Value *NewOp = Builder->CreateAnd((V1 == A) ? B : A, CI1);
Bill Wendling6c8ecbb2008-12-02 06:22:04 +00001813 return BinaryOperator::CreateOr(NewOp, V1);
Bill Wendlingdae376a2008-12-01 08:23:25 +00001814 }
1815
1816 return 0;
1817}
1818
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001819Instruction *InstCombiner::visitOr(BinaryOperator &I) {
1820 bool Changed = SimplifyCommutative(I);
1821 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1822
Chris Lattnera3e46f62009-11-10 00:55:12 +00001823 if (Value *V = SimplifyOrInst(Op0, Op1, TD))
1824 return ReplaceInstUsesWith(I, V);
1825
1826
Dan Gohmanf17a25c2007-07-18 16:29:46 +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 Gohman8fd520a2009-06-15 22:12:54 +00001829 if (SimplifyDemandedInstructionBits(I))
1830 return &I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001831
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001832 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
1833 ConstantInt *C1 = 0; Value *X = 0;
1834 // (X & C1) | C2 --> (X | C2) & (C1|C2)
Dan Gohmancdff2122009-08-12 16:23:25 +00001835 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) &&
Chris Lattner1e680352010-01-05 07:04:23 +00001836 Op0->hasOneUse()) {
Chris Lattnerc7694852009-08-30 07:44:24 +00001837 Value *Or = Builder->CreateOr(X, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001838 Or->takeName(Op0);
Gabor Greifa645dd32008-05-16 19:29:10 +00001839 return BinaryOperator::CreateAnd(Or,
Chris Lattner03a27b42010-01-04 07:02:48 +00001840 ConstantInt::get(I.getContext(),
1841 RHS->getValue() | C1->getValue()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001842 }
1843
1844 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
Dan Gohmancdff2122009-08-12 16:23:25 +00001845 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) &&
Chris Lattner1e680352010-01-05 07:04:23 +00001846 Op0->hasOneUse()) {
Chris Lattnerc7694852009-08-30 07:44:24 +00001847 Value *Or = Builder->CreateOr(X, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001848 Or->takeName(Op0);
Gabor Greifa645dd32008-05-16 19:29:10 +00001849 return BinaryOperator::CreateXor(Or,
Chris Lattner03a27b42010-01-04 07:02:48 +00001850 ConstantInt::get(I.getContext(),
1851 C1->getValue() & ~RHS->getValue()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001852 }
1853
1854 // Try to fold constant and into select arguments.
1855 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner54826cd2010-01-04 07:53:58 +00001856 if (Instruction *R = FoldOpIntoSelect(I, SI))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001857 return R;
1858 if (isa<PHINode>(Op0))
1859 if (Instruction *NV = FoldOpIntoPhi(I))
1860 return NV;
1861 }
1862
1863 Value *A = 0, *B = 0;
1864 ConstantInt *C1 = 0, *C2 = 0;
1865
Dan Gohmanf17a25c2007-07-18 16:29:46 +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 Gohmancdff2122009-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())))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001872 if (Instruction *BSwap = MatchBSwap(I))
1873 return BSwap;
1874 }
1875
1876 // (X^C)|Y -> (X|Y)^C iff Y&C == 0
Owen Andersona21eb582009-07-10 17:35:01 +00001877 if (Op0->hasOneUse() &&
Dan Gohmancdff2122009-08-12 16:23:25 +00001878 match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001879 MaskedValueIsZero(Op1, C1->getValue())) {
Chris Lattnerc7694852009-08-30 07:44:24 +00001880 Value *NOr = Builder->CreateOr(A, Op1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001881 NOr->takeName(Op0);
Gabor Greifa645dd32008-05-16 19:29:10 +00001882 return BinaryOperator::CreateXor(NOr, C1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001883 }
1884
1885 // Y|(X^C) -> (X|Y)^C iff Y&C == 0
Owen Andersona21eb582009-07-10 17:35:01 +00001886 if (Op1->hasOneUse() &&
Dan Gohmancdff2122009-08-12 16:23:25 +00001887 match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001888 MaskedValueIsZero(Op0, C1->getValue())) {
Chris Lattnerc7694852009-08-30 07:44:24 +00001889 Value *NOr = Builder->CreateOr(A, Op0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001890 NOr->takeName(Op0);
Gabor Greifa645dd32008-05-16 19:29:10 +00001891 return BinaryOperator::CreateXor(NOr, C1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001892 }
1893
1894 // (A & C)|(B & D)
1895 Value *C = 0, *D = 0;
Dan Gohmancdff2122009-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)))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +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 Gohmancdff2122009-08-12 16:23:25 +00001907 match(A, m_Add(m_Value(V1), m_Value(V2)))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +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 Gohmancdff2122009-08-12 16:23:25 +00001916 match(B, m_Add(m_Value(V1), m_Value(V2)))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +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 Lattner4fcef8a2010-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 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001942 }
1943
1944 // Check to see if we have any common things being and'ed. If so, find the
1945 // terms for V1 & (V2|V3).
Chris Lattner1e680352010-01-05 07:04:23 +00001946 if (Op0->hasOneUse() || Op1->hasOneUse()) {
Chris Lattner4fcef8a2010-01-04 06:03:59 +00001947 V1 = 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +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 Lattnerc7694852009-08-30 07:44:24 +00001958 Value *Or = Builder->CreateOr(V2, V3, "tmp");
Gabor Greifa645dd32008-05-16 19:29:10 +00001959 return BinaryOperator::CreateAnd(V1, Or);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001960 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001961 }
Dan Gohman279952c2008-10-28 22:38:57 +00001962
Dan Gohman35b76162008-10-30 20:40:10 +00001963 // (A & (C0?-1:0)) | (B & ~(C0?-1:0)) -> C0 ? A : B, and commuted variants
Chris Lattner03a27b42010-01-04 07:02:48 +00001964 if (Instruction *Match = MatchSelectFromAndOr(A, B, C, D))
Chris Lattnerdd7772b2008-11-16 04:24:12 +00001965 return Match;
Chris Lattner03a27b42010-01-04 07:02:48 +00001966 if (Instruction *Match = MatchSelectFromAndOr(B, A, D, C))
Chris Lattnerdd7772b2008-11-16 04:24:12 +00001967 return Match;
Chris Lattner03a27b42010-01-04 07:02:48 +00001968 if (Instruction *Match = MatchSelectFromAndOr(C, B, A, D))
Chris Lattnerdd7772b2008-11-16 04:24:12 +00001969 return Match;
Chris Lattner03a27b42010-01-04 07:02:48 +00001970 if (Instruction *Match = MatchSelectFromAndOr(D, A, B, C))
Chris Lattnerdd7772b2008-11-16 04:24:12 +00001971 return Match;
Bill Wendling22ca8352008-11-30 13:52:49 +00001972
Bill Wendling22ca8352008-11-30 13:52:49 +00001973 // ((A&~B)|(~A&B)) -> A^B
Dan Gohmancdff2122009-08-12 16:23:25 +00001974 if ((match(C, m_Not(m_Specific(D))) &&
1975 match(B, m_Not(m_Specific(A)))))
Bill Wendlingc1f31132008-12-01 08:09:47 +00001976 return BinaryOperator::CreateXor(A, D);
Bill Wendling22ca8352008-11-30 13:52:49 +00001977 // ((~B&A)|(~A&B)) -> A^B
Dan Gohmancdff2122009-08-12 16:23:25 +00001978 if ((match(A, m_Not(m_Specific(D))) &&
1979 match(B, m_Not(m_Specific(C)))))
Bill Wendlingc1f31132008-12-01 08:09:47 +00001980 return BinaryOperator::CreateXor(C, D);
Bill Wendling22ca8352008-11-30 13:52:49 +00001981 // ((A&~B)|(B&~A)) -> A^B
Dan Gohmancdff2122009-08-12 16:23:25 +00001982 if ((match(C, m_Not(m_Specific(B))) &&
1983 match(D, m_Not(m_Specific(A)))))
Bill Wendlingc1f31132008-12-01 08:09:47 +00001984 return BinaryOperator::CreateXor(A, B);
Bill Wendling22ca8352008-11-30 13:52:49 +00001985 // ((~B&A)|(B&~A)) -> A^B
Dan Gohmancdff2122009-08-12 16:23:25 +00001986 if ((match(A, m_Not(m_Specific(B))) &&
1987 match(D, m_Not(m_Specific(C)))))
Bill Wendlingc1f31132008-12-01 08:09:47 +00001988 return BinaryOperator::CreateXor(C, B);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001989 }
1990
1991 // (X >> Z) | (Y >> Z) -> (X|Y) >> Z for all shifts.
1992 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
1993 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
1994 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
1995 SI0->getOperand(1) == SI1->getOperand(1) &&
1996 (SI0->hasOneUse() || SI1->hasOneUse())) {
Chris Lattnerc7694852009-08-30 07:44:24 +00001997 Value *NewOp = Builder->CreateOr(SI0->getOperand(0), SI1->getOperand(0),
1998 SI0->getName());
Gabor Greifa645dd32008-05-16 19:29:10 +00001999 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002000 SI1->getOperand(1));
2001 }
2002 }
2003
Bill Wendlingd8ce2372008-12-01 01:07:11 +00002004 // ((A|B)&1)|(B&-2) -> (A&1) | B
Dan Gohmancdff2122009-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 Wendling9912f712008-12-01 08:32:40 +00002007 Instruction *Ret = FoldOrWithConstants(I, Op1, A, B, C);
Bill Wendlingdae376a2008-12-01 08:23:25 +00002008 if (Ret) return Ret;
Bill Wendlingd8ce2372008-12-01 01:07:11 +00002009 }
2010 // (B&-2)|((A|B)&1) -> (A&1) | B
Dan Gohmancdff2122009-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 Wendling9912f712008-12-01 08:32:40 +00002013 Instruction *Ret = FoldOrWithConstants(I, Op0, A, B, C);
Bill Wendlingdae376a2008-12-01 08:23:25 +00002014 if (Ret) return Ret;
Bill Wendlingd8ce2372008-12-01 01:07:11 +00002015 }
2016
Chris Lattnera3e46f62009-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 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002025
Chris Lattner41cabbe2010-01-05 06:59:49 +00002026 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
Chris Lattner0c678e52008-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;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002030
2031 // fold (or (cast A), (cast B)) -> (cast (or A, B))
Chris Lattner91882432007-10-24 05:38:08 +00002032 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002033 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
2034 if (Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
Evan Chenge3779cf2008-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 Lattnercf373552009-07-23 05:32:17 +00002038 if (SrcTy == Op1C->getOperand(0)->getType() &&
2039 SrcTy->isIntOrIntVector() &&
Evan Chenge3779cf2008-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 Lattner54826cd2010-01-04 07:53:58 +00002043 I.getType()) &&
Evan Chenge3779cf2008-03-24 00:21:34 +00002044 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
Chris Lattner54826cd2010-01-04 07:53:58 +00002045 I.getType())) {
Chris Lattnerc7694852009-08-30 07:44:24 +00002046 Value *NewOp = Builder->CreateOr(Op0C->getOperand(0),
2047 Op1C->getOperand(0), I.getName());
Gabor Greifa645dd32008-05-16 19:29:10 +00002048 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Evan Chenge3779cf2008-03-24 00:21:34 +00002049 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002050 }
2051 }
Chris Lattner91882432007-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 Lattner57e66fa2009-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 Lattner91882432007-10-24 05:38:08 +00002060 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002061
2062 return Changed ? &I : 0;
2063}
2064
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002065Instruction *InstCombiner::visitXor(BinaryOperator &I) {
2066 bool Changed = SimplifyCommutative(I);
2067 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2068
Evan Chenge5cd8032008-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 Andersonaac28372009-07-31 20:28:14 +00002073 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002074 return ReplaceInstUsesWith(I, Op1); // X ^ undef -> undef
Evan Chenge5cd8032008-03-25 20:07:13 +00002075 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002076
Chris Lattnerf6a84252010-01-05 07:01:16 +00002077 // xor X, X = 0
2078 if (Op0 == Op1)
Owen Andersonaac28372009-07-31 20:28:14 +00002079 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +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 Gohman8fd520a2009-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
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002088
2089 // Is this a ~ operation?
Dan Gohmanfe91cd62009-08-12 16:04:34 +00002090 if (Value *NotOp = dyn_castNotVal(&I)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002091 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(NotOp)) {
2092 if (Op0I->getOpcode() == Instruction::And ||
2093 Op0I->getOpcode() == Instruction::Or) {
Chris Lattner6e060db2009-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 Gohmanfe91cd62009-08-12 16:04:34 +00002098 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
Chris Lattnerc7694852009-08-30 07:44:24 +00002099 Value *NotY =
2100 Builder->CreateNot(Op0I->getOperand(1),
2101 Op0I->getOperand(1)->getName()+".not");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002102 if (Op0I->getOpcode() == Instruction::And)
Gabor Greifa645dd32008-05-16 19:29:10 +00002103 return BinaryOperator::CreateOr(Op0NotVal, NotY);
Chris Lattnerc7694852009-08-30 07:44:24 +00002104 return BinaryOperator::CreateAnd(Op0NotVal, NotY);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002105 }
Chris Lattner6e060db2009-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 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002119 }
2120 }
2121 }
2122
2123
2124 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner4580d452009-10-11 22:00:32 +00002125 if (RHS->isOne() && Op0->hasOneUse()) {
Bill Wendling61741952009-01-01 01:18:23 +00002126 // xor (cmp A, B), true = not (cmp A, B) = !cmp A, B
Nick Lewycky1405e922007-08-06 20:04:16 +00002127 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Op0))
Dan Gohmane6803b82009-08-25 23:17:54 +00002128 return new ICmpInst(ICI->getInversePredicate(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002129 ICI->getOperand(0), ICI->getOperand(1));
2130
Nick Lewycky1405e922007-08-06 20:04:16 +00002131 if (FCmpInst *FCI = dyn_cast<FCmpInst>(Op0))
Dan Gohmane6803b82009-08-25 23:17:54 +00002132 return new FCmpInst(FCI->getInversePredicate(),
Nick Lewycky1405e922007-08-06 20:04:16 +00002133 FCI->getOperand(0), FCI->getOperand(1));
2134 }
2135
Nick Lewycky0aa63aa2008-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 Lattnerc7694852009-08-30 07:44:24 +00002141 if ((Opcode == Instruction::ZExt || Opcode == Instruction::SExt) &&
2142 (RHS == ConstantExpr::getCast(Opcode,
Chris Lattner03a27b42010-01-04 07:02:48 +00002143 ConstantInt::getTrue(I.getContext()),
Chris Lattnerc7694852009-08-30 07:44:24 +00002144 Op0C->getDestTy()))) {
2145 CI->setPredicate(CI->getInversePredicate());
2146 return CastInst::Create(Opcode, CI, Op0C->getType());
Nick Lewycky0aa63aa2008-05-31 19:01:33 +00002147 }
2148 }
2149 }
2150 }
2151
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002152 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
2153 // ~(c-X) == X-c-1 == X+(-c-1)
2154 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
2155 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
Owen Anderson02b48c32009-07-29 18:55:55 +00002156 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
2157 Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
Owen Andersoneacb44d2009-07-24 23:12:02 +00002158 ConstantInt::get(I.getType(), 1));
Gabor Greifa645dd32008-05-16 19:29:10 +00002159 return BinaryOperator::CreateAdd(Op0I->getOperand(1), ConstantRHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002160 }
2161
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00002162 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002163 if (Op0I->getOpcode() == Instruction::Add) {
2164 // ~(X-c) --> (-c-1)-X
2165 if (RHS->isAllOnesValue()) {
Owen Anderson02b48c32009-07-29 18:55:55 +00002166 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
Gabor Greifa645dd32008-05-16 19:29:10 +00002167 return BinaryOperator::CreateSub(
Owen Anderson02b48c32009-07-29 18:55:55 +00002168 ConstantExpr::getSub(NegOp0CI,
Owen Andersoneacb44d2009-07-24 23:12:02 +00002169 ConstantInt::get(I.getType(), 1)),
Owen Anderson24be4c12009-07-03 00:17:18 +00002170 Op0I->getOperand(0));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002171 } else if (RHS->getValue().isSignBit()) {
2172 // (X + C) ^ signbit -> (X + C + signbit)
Chris Lattner03a27b42010-01-04 07:02:48 +00002173 Constant *C = ConstantInt::get(I.getContext(),
Owen Andersoneacb44d2009-07-24 23:12:02 +00002174 RHS->getValue() + Op0CI->getValue());
Gabor Greifa645dd32008-05-16 19:29:10 +00002175 return BinaryOperator::CreateAdd(Op0I->getOperand(0), C);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002176
2177 }
2178 } else if (Op0I->getOpcode() == Instruction::Or) {
2179 // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
2180 if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue())) {
Owen Anderson02b48c32009-07-29 18:55:55 +00002181 Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002182 // Anything in both C1 and C2 is known to be zero, remove it from
2183 // NewRHS.
Owen Anderson02b48c32009-07-29 18:55:55 +00002184 Constant *CommonBits = ConstantExpr::getAnd(Op0CI, RHS);
2185 NewRHS = ConstantExpr::getAnd(NewRHS,
2186 ConstantExpr::getNot(CommonBits));
Chris Lattner3183fb62009-08-30 06:13:40 +00002187 Worklist.Add(Op0I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002188 I.setOperand(0, Op0I->getOperand(0));
2189 I.setOperand(1, NewRHS);
2190 return &I;
2191 }
2192 }
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00002193 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002194 }
2195
2196 // Try to fold constant and into select arguments.
2197 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner54826cd2010-01-04 07:53:58 +00002198 if (Instruction *R = FoldOpIntoSelect(I, SI))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002199 return R;
2200 if (isa<PHINode>(Op0))
2201 if (Instruction *NV = FoldOpIntoPhi(I))
2202 return NV;
2203 }
2204
Dan Gohmanfe91cd62009-08-12 16:04:34 +00002205 if (Value *X = dyn_castNotVal(Op0)) // ~A ^ A == -1
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002206 if (X == Op1)
Owen Andersonaac28372009-07-31 20:28:14 +00002207 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002208
Dan Gohmanfe91cd62009-08-12 16:04:34 +00002209 if (Value *X = dyn_castNotVal(Op1)) // A ^ ~A == -1
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002210 if (X == Op0)
Owen Andersonaac28372009-07-31 20:28:14 +00002211 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002212
2213
2214 BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1);
2215 if (Op1I) {
2216 Value *A, *B;
Dan Gohmancdff2122009-08-12 16:23:25 +00002217 if (match(Op1I, m_Or(m_Value(A), m_Value(B)))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002218 if (A == Op0) { // B^(B|A) == (A|B)^B
2219 Op1I->swapOperands();
2220 I.swapOperands();
2221 std::swap(Op0, Op1);
2222 } else if (B == Op0) { // B^(A|B) == (A|B)^B
2223 I.swapOperands(); // Simplified below.
2224 std::swap(Op0, Op1);
2225 }
Dan Gohmancdff2122009-08-12 16:23:25 +00002226 } else if (match(Op1I, m_Xor(m_Specific(Op0), m_Value(B)))) {
Chris Lattner3b874082008-11-16 05:38:51 +00002227 return ReplaceInstUsesWith(I, B); // A^(A^B) == B
Dan Gohmancdff2122009-08-12 16:23:25 +00002228 } else if (match(Op1I, m_Xor(m_Value(A), m_Specific(Op0)))) {
Chris Lattner3b874082008-11-16 05:38:51 +00002229 return ReplaceInstUsesWith(I, A); // A^(B^A) == B
Dan Gohmancdff2122009-08-12 16:23:25 +00002230 } else if (match(Op1I, m_And(m_Value(A), m_Value(B))) &&
Owen Andersona21eb582009-07-10 17:35:01 +00002231 Op1I->hasOneUse()){
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002232 if (A == Op0) { // A^(A&B) -> A^(B&A)
2233 Op1I->swapOperands();
2234 std::swap(A, B);
2235 }
2236 if (B == Op0) { // A^(B&A) -> (B&A)^A
2237 I.swapOperands(); // Simplified below.
2238 std::swap(Op0, Op1);
2239 }
2240 }
2241 }
2242
2243 BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0);
2244 if (Op0I) {
2245 Value *A, *B;
Dan Gohmancdff2122009-08-12 16:23:25 +00002246 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
Owen Andersona21eb582009-07-10 17:35:01 +00002247 Op0I->hasOneUse()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002248 if (A == Op1) // (B|A)^B == (A|B)^B
2249 std::swap(A, B);
Chris Lattnerc7694852009-08-30 07:44:24 +00002250 if (B == Op1) // (A|B)^B == A & ~B
2251 return BinaryOperator::CreateAnd(A, Builder->CreateNot(Op1, "tmp"));
Dan Gohmancdff2122009-08-12 16:23:25 +00002252 } else if (match(Op0I, m_Xor(m_Specific(Op1), m_Value(B)))) {
Chris Lattner3b874082008-11-16 05:38:51 +00002253 return ReplaceInstUsesWith(I, B); // (A^B)^A == B
Dan Gohmancdff2122009-08-12 16:23:25 +00002254 } else if (match(Op0I, m_Xor(m_Value(A), m_Specific(Op1)))) {
Chris Lattner3b874082008-11-16 05:38:51 +00002255 return ReplaceInstUsesWith(I, A); // (B^A)^A == B
Dan Gohmancdff2122009-08-12 16:23:25 +00002256 } else if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
Owen Andersona21eb582009-07-10 17:35:01 +00002257 Op0I->hasOneUse()){
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002258 if (A == Op1) // (A&B)^A -> (B&A)^A
2259 std::swap(A, B);
2260 if (B == Op1 && // (B&A)^A == ~B & A
2261 !isa<ConstantInt>(Op1)) { // Canonical form is (B&C)^C
Chris Lattnerc7694852009-08-30 07:44:24 +00002262 return BinaryOperator::CreateAnd(Builder->CreateNot(A, "tmp"), Op1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002263 }
2264 }
2265 }
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 Lattnerc7694852009-08-30 07:44:24 +00002272 Value *NewOp =
2273 Builder->CreateXor(Op0I->getOperand(0), Op1I->getOperand(0),
2274 Op0I->getName());
Gabor Greifa645dd32008-05-16 19:29:10 +00002275 return BinaryOperator::Create(Op1I->getOpcode(), NewOp,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002276 Op1I->getOperand(1));
2277 }
2278
2279 if (Op0I && Op1I) {
2280 Value *A, *B, *C, *D;
2281 // (A & B)^(A | B) -> A ^ B
Dan Gohmancdff2122009-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)))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002284 if ((A == C && B == D) || (A == D && B == C))
Gabor Greifa645dd32008-05-16 19:29:10 +00002285 return BinaryOperator::CreateXor(A, B);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002286 }
2287 // (A | B)^(A & B) -> A ^ B
Dan Gohmancdff2122009-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)))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002290 if ((A == C && B == D) || (A == D && B == C))
Gabor Greifa645dd32008-05-16 19:29:10 +00002291 return BinaryOperator::CreateXor(A, B);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002292 }
2293
2294 // (A & B)^(C & D)
2295 if ((Op0I->hasOneUse() || Op1I->hasOneUse()) &&
Dan Gohmancdff2122009-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)))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +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 Lattnerc7694852009-08-30 07:44:24 +00002310 Value *NewOp = Builder->CreateXor(Y, Z, Op0->getName());
Gabor Greifa645dd32008-05-16 19:29:10 +00002311 return BinaryOperator::CreateAnd(NewOp, X);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002312 }
2313 }
2314 }
2315
2316 // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
2317 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
Chris Lattner41cabbe2010-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 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002335
2336 // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
Chris Lattner91882432007-10-24 05:38:08 +00002337 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002338 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
2339 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
2340 const Type *SrcTy = Op0C->getOperand(0)->getType();
2341 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
2342 // Only do this if the casts both really cause code to be generated.
2343 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
Chris Lattner54826cd2010-01-04 07:53:58 +00002344 I.getType()) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002345 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
Chris Lattner54826cd2010-01-04 07:53:58 +00002346 I.getType())) {
Chris Lattnerc7694852009-08-30 07:44:24 +00002347 Value *NewOp = Builder->CreateXor(Op0C->getOperand(0),
2348 Op1C->getOperand(0), I.getName());
Gabor Greifa645dd32008-05-16 19:29:10 +00002349 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002350 }
2351 }
Chris Lattner91882432007-10-24 05:38:08 +00002352 }
Nick Lewycky0aa63aa2008-05-31 19:01:33 +00002353
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002354 return Changed ? &I : 0;
2355}
2356
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002357
2358Instruction *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 Lattnere3c504f2007-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 Gohman843649e2009-02-24 02:00:40 +00002376
Dan Gohman2526aea2009-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 Gohman843649e2009-02-24 02:00:40 +00002386
Chris Lattnere3c504f2007-12-06 01:59:46 +00002387 return 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002388}
2389
2390Instruction *InstCombiner::commonShiftTransforms(BinaryOperator &I) {
2391 assert(I.getOperand(1)->getType() == I.getOperand(0)->getType());
2392 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2393
2394 // shl X, 0 == X and shr X, 0 == X
2395 // shl 0, X == 0 and shr 0, X == 0
Owen Andersonaac28372009-07-31 20:28:14 +00002396 if (Op1 == Constant::getNullValue(Op1->getType()) ||
2397 Op0 == Constant::getNullValue(Op0->getType()))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002398 return ReplaceInstUsesWith(I, Op0);
2399
2400 if (isa<UndefValue>(Op0)) {
2401 if (I.getOpcode() == Instruction::AShr) // undef >>s X -> undef
2402 return ReplaceInstUsesWith(I, Op0);
2403 else // undef << X -> 0, undef >>u X -> 0
Owen Andersonaac28372009-07-31 20:28:14 +00002404 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002405 }
2406 if (isa<UndefValue>(Op1)) {
2407 if (I.getOpcode() == Instruction::AShr) // X >>s undef -> X
2408 return ReplaceInstUsesWith(I, Op0);
2409 else // X << undef, X >>u undef -> 0
Owen Andersonaac28372009-07-31 20:28:14 +00002410 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002411 }
2412
Dan Gohman2bc21562009-05-21 02:28:33 +00002413 // See if we can fold away this shift.
Dan Gohman8fd520a2009-06-15 22:12:54 +00002414 if (SimplifyDemandedInstructionBits(I))
Dan Gohman2bc21562009-05-21 02:28:33 +00002415 return &I;
2416
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002417 // Try to fold constant and into select arguments.
2418 if (isa<Constant>(Op0))
2419 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner54826cd2010-01-04 07:53:58 +00002420 if (Instruction *R = FoldOpIntoSelect(I, SI))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002421 return R;
2422
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002423 if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
2424 if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
2425 return Res;
2426 return 0;
2427}
2428
2429Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
2430 BinaryOperator &I) {
Chris Lattner08817332009-01-31 08:24:16 +00002431 bool isLeftShift = I.getOpcode() == Instruction::Shl;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002432
2433 // 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 Gohman2526aea2009-06-16 19:55:29 +00002435 uint32_t TypeBits = Op0->getType()->getScalarSizeInBits();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002436
Dan Gohman9e1657f2009-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.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002439 //
2440 if (Op1->uge(TypeBits)) {
2441 if (I.getOpcode() != Instruction::AShr)
Owen Andersonaac28372009-07-31 20:28:14 +00002442 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002443 else {
Owen Andersoneacb44d2009-07-24 23:12:02 +00002444 I.setOperand(1, ConstantInt::get(I.getType(), TypeBits-1));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002445 return &I;
2446 }
2447 }
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 Greifa645dd32008-05-16 19:29:10 +00002453 return BinaryOperator::CreateMul(BO->getOperand(0),
Owen Anderson02b48c32009-07-29 18:55:55 +00002454 ConstantExpr::getShl(BOOp, Op1));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002455
2456 // Try to fold constant and into select arguments.
2457 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner54826cd2010-01-04 07:53:58 +00002458 if (Instruction *R = FoldOpIntoSelect(I, SI))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002459 return R;
2460 if (isa<PHINode>(Op0))
2461 if (Instruction *NV = FoldOpIntoPhi(I))
2462 return NV;
2463
Chris Lattnerc6d1f642007-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 Anderson02b48c32009-07-29 18:55:55 +00002475 Constant *ShAmt = ConstantExpr::getZExt(Op1, TrOp->getType());
Chris Lattnerc7694852009-08-30 07:44:24 +00002476 // (shift2 (shift1 & 0x00FF), c2)
2477 Value *NSh = Builder->CreateBinOp(I.getOpcode(), TrOp, ShAmt,I.getName());
Chris Lattnerc6d1f642007-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 Gohman2526aea2009-06-16 19:55:29 +00002483 unsigned SrcSize = TrOp->getType()->getScalarSizeInBits();
2484 unsigned DstSize = TI->getType()->getScalarSizeInBits();
Chris Lattnerc6d1f642007-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 Lattnerc7694852009-08-30 07:44:24 +00002498 // shift1 & 0x00FF
Chris Lattner03a27b42010-01-04 07:02:48 +00002499 Value *And = Builder->CreateAnd(NSh,
2500 ConstantInt::get(I.getContext(), MaskV),
Chris Lattnerc7694852009-08-30 07:44:24 +00002501 TI->getName());
Chris Lattnerc6d1f642007-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
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002508 if (Op0->hasOneUse()) {
2509 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()) {
2514 default: break;
2515 case Instruction::Add:
2516 case Instruction::And:
2517 case Instruction::Or:
2518 case Instruction::Xor: {
2519 // These operators commute.
2520 // Turn (Y + (X >> C)) << C -> (X + (Y << C)) & (~0 << C)
2521 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
Owen Andersona21eb582009-07-10 17:35:01 +00002522 match(Op0BO->getOperand(1), m_Shr(m_Value(V1),
Chris Lattnerad7516a2009-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());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002529 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
Chris Lattner03a27b42010-01-04 07:02:48 +00002530 return BinaryOperator::CreateAnd(X, ConstantInt::get(I.getContext(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002531 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
2532 }
2533
2534 // Turn (Y + ((X >> C) & CC)) << C -> ((X & (CC << C)) + (Y << C))
2535 Value *Op0BOOp1 = Op0BO->getOperand(1);
2536 if (isLeftShift && Op0BOOp1->hasOneUse() &&
2537 match(Op0BOOp1,
Chris Lattner3b874082008-11-16 05:38:51 +00002538 m_And(m_Shr(m_Value(V1), m_Specific(Op1)),
Dan Gohmancdff2122009-08-12 16:23:25 +00002539 m_ConstantInt(CC))) &&
Chris Lattner3b874082008-11-16 05:38:51 +00002540 cast<BinaryOperator>(Op0BOOp1)->getOperand(0)->hasOneUse()) {
Chris Lattnerad7516a2009-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 Greifa645dd32008-05-16 19:29:10 +00002547 return BinaryOperator::Create(Op0BO->getOpcode(), YS, XM);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002548 }
2549 }
2550
2551 // FALL THROUGH.
2552 case Instruction::Sub: {
2553 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
2554 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
Owen Andersona21eb582009-07-10 17:35:01 +00002555 match(Op0BO->getOperand(0), m_Shr(m_Value(V1),
Dan Gohmancdff2122009-08-12 16:23:25 +00002556 m_Specific(Op1)))) {
Chris Lattnerad7516a2009-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());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002562 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
Chris Lattner03a27b42010-01-04 07:02:48 +00002563 return BinaryOperator::CreateAnd(X, ConstantInt::get(I.getContext(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002564 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
2565 }
2566
2567 // Turn (((X >> C)&CC) + Y) << C -> (X + (Y << C)) & (CC << C)
2568 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
2569 match(Op0BO->getOperand(0),
2570 m_And(m_Shr(m_Value(V1), m_Value(V2)),
Dan Gohmancdff2122009-08-12 16:23:25 +00002571 m_ConstantInt(CC))) && V2 == Op1 &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002572 cast<BinaryOperator>(Op0BO->getOperand(0))
2573 ->getOperand(0)->hasOneUse()) {
Chris Lattnerad7516a2009-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");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002579
Gabor Greifa645dd32008-05-16 19:29:10 +00002580 return BinaryOperator::Create(Op0BO->getOpcode(), XM, YS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002581 }
2582
2583 break;
2584 }
2585 }
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()) {
2595 default: isValid = false; break; // Do not perform transform!
2596 case Instruction::Add:
2597 isValid = isLeftShift;
2598 break;
2599 case Instruction::Or:
2600 case Instruction::Xor:
2601 highBitSet = false;
2602 break;
2603 case Instruction::And:
2604 highBitSet = true;
2605 break;
2606 }
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 Lattner15b76e32007-12-06 06:25:04 +00002614 if (isValid && I.getOpcode() == Instruction::AShr)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002615 isValid = Op0C->getValue()[TypeBits-1] == highBitSet;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002616
2617 if (isValid) {
Owen Anderson02b48c32009-07-29 18:55:55 +00002618 Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002619
Chris Lattnerad7516a2009-08-30 18:50:58 +00002620 Value *NewShift =
2621 Builder->CreateBinOp(I.getOpcode(), Op0BO->getOperand(0), Op1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002622 NewShift->takeName(Op0BO);
2623
Gabor Greifa645dd32008-05-16 19:29:10 +00002624 return BinaryOperator::Create(Op0BO->getOpcode(), NewShift,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002625 NewRHS);
2626 }
2627 }
2628 }
2629 }
2630
2631 // Find out if this is a shift of a shift by a constant.
2632 BinaryOperator *ShiftOp = dyn_cast<BinaryOperator>(Op0);
2633 if (ShiftOp && !ShiftOp->isShift())
2634 ShiftOp = 0;
2635
2636 if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
2637 ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
2638 uint32_t ShiftAmt1 = ShiftAmt1C->getLimitedValue(TypeBits);
2639 uint32_t ShiftAmt2 = Op1->getLimitedValue(TypeBits);
2640 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);
2643
2644 uint32_t AmtSum = ShiftAmt1+ShiftAmt2; // Fold into one big shift.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002645
2646 const IntegerType *Ty = cast<IntegerType>(I.getType());
2647
2648 // Check for (X << c1) << c2 and (X >> c1) >> c2
2649 if (I.getOpcode() == ShiftOp->getOpcode()) {
Chris Lattnerb36c7012009-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 Andersonaac28372009-07-31 20:28:14 +00002654 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerb36c7012009-03-20 22:41:15 +00002655 AmtSum = TypeBits-1; // Saturate to 31 for i32 ashr.
2656 }
2657
Gabor Greifa645dd32008-05-16 19:29:10 +00002658 return BinaryOperator::Create(I.getOpcode(), X,
Owen Andersoneacb44d2009-07-24 23:12:02 +00002659 ConstantInt::get(Ty, AmtSum));
Chris Lattnerad7516a2009-08-30 18:50:58 +00002660 }
2661
2662 if (ShiftOp->getOpcode() == Instruction::LShr &&
2663 I.getOpcode() == Instruction::AShr) {
Chris Lattnerb36c7012009-03-20 22:41:15 +00002664 if (AmtSum >= TypeBits)
Owen Andersonaac28372009-07-31 20:28:14 +00002665 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerb36c7012009-03-20 22:41:15 +00002666
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002667 // ((X >>u C1) >>s C2) -> (X >>u (C1+C2)) since C1 != 0.
Owen Andersoneacb44d2009-07-24 23:12:02 +00002668 return BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, AmtSum));
Chris Lattnerad7516a2009-08-30 18:50:58 +00002669 }
2670
2671 if (ShiftOp->getOpcode() == Instruction::AShr &&
2672 I.getOpcode() == Instruction::LShr) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002673 // ((X >>s C1) >>u C2) -> ((X >>s (C1+C2)) & mask) since C1 != 0.
Chris Lattnerb36c7012009-03-20 22:41:15 +00002674 if (AmtSum >= TypeBits)
2675 AmtSum = TypeBits-1;
2676
Chris Lattnerad7516a2009-08-30 18:50:58 +00002677 Value *Shift = Builder->CreateAShr(X, ConstantInt::get(Ty, AmtSum));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002678
2679 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Chris Lattner03a27b42010-01-04 07:02:48 +00002680 return BinaryOperator::CreateAnd(Shift,
2681 ConstantInt::get(I.getContext(), Mask));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002682 }
2683
2684 // 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) {
2689 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt1));
Chris Lattner03a27b42010-01-04 07:02:48 +00002690 return BinaryOperator::CreateAnd(X,
2691 ConstantInt::get(I.getContext(),Mask));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002692 }
2693 // If we have ((X << C) >>u C), turn this into X & (-1 >>u C).
2694 if (I.getOpcode() == Instruction::LShr) {
2695 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt1));
Chris Lattner03a27b42010-01-04 07:02:48 +00002696 return BinaryOperator::CreateAnd(X,
2697 ConstantInt::get(I.getContext(), Mask));
Dan Gohmanf17a25c2007-07-18 16:29:46 +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) {
2705 case 1 :
2706 case 8 :
2707 case 16 :
2708 case 32 :
2709 case 64 :
2710 case 128:
Chris Lattner03a27b42010-01-04 07:02:48 +00002711 SExtType = IntegerType::get(I.getContext(),
2712 Ty->getBitWidth() - ShiftAmt1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002713 break;
2714 default: break;
2715 }
Chris Lattnerad7516a2009-08-30 18:50:58 +00002716 if (SExtType)
2717 return new SExtInst(Builder->CreateTrunc(X, SExtType, "sext"), Ty);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002718 // Otherwise, we can't handle it yet.
2719 } else if (ShiftAmt1 < ShiftAmt2) {
2720 uint32_t ShiftDiff = ShiftAmt2-ShiftAmt1;
2721
2722 // (X >>? C1) << C2 --> X << (C2-C1) & (-1 << C2)
2723 if (I.getOpcode() == Instruction::Shl) {
2724 assert(ShiftOp->getOpcode() == Instruction::LShr ||
2725 ShiftOp->getOpcode() == Instruction::AShr);
Chris Lattnerad7516a2009-08-30 18:50:58 +00002726 Value *Shift = Builder->CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002727
2728 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersoneacb44d2009-07-24 23:12:02 +00002729 return BinaryOperator::CreateAnd(Shift,
Chris Lattner03a27b42010-01-04 07:02:48 +00002730 ConstantInt::get(I.getContext(),Mask));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002731 }
2732
2733 // (X << C1) >>u C2 --> X >>u (C2-C1) & (-1 >> C2)
2734 if (I.getOpcode() == Instruction::LShr) {
2735 assert(ShiftOp->getOpcode() == Instruction::Shl);
Chris Lattnerad7516a2009-08-30 18:50:58 +00002736 Value *Shift = Builder->CreateLShr(X, ConstantInt::get(Ty, ShiftDiff));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002737
2738 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersoneacb44d2009-07-24 23:12:02 +00002739 return BinaryOperator::CreateAnd(Shift,
Chris Lattner03a27b42010-01-04 07:02:48 +00002740 ConstantInt::get(I.getContext(),Mask));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002741 }
2742
2743 // We can't handle (X << C1) >>s C2, it shifts arbitrary bits in.
2744 } else {
2745 assert(ShiftAmt2 < ShiftAmt1);
2746 uint32_t ShiftDiff = ShiftAmt1-ShiftAmt2;
2747
2748 // (X >>? C1) << C2 --> X >>? (C1-C2) & (-1 << C2)
2749 if (I.getOpcode() == Instruction::Shl) {
2750 assert(ShiftOp->getOpcode() == Instruction::LShr ||
2751 ShiftOp->getOpcode() == Instruction::AShr);
Chris Lattnerad7516a2009-08-30 18:50:58 +00002752 Value *Shift = Builder->CreateBinOp(ShiftOp->getOpcode(), X,
2753 ConstantInt::get(Ty, ShiftDiff));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002754
2755 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersoneacb44d2009-07-24 23:12:02 +00002756 return BinaryOperator::CreateAnd(Shift,
Chris Lattner03a27b42010-01-04 07:02:48 +00002757 ConstantInt::get(I.getContext(),Mask));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002758 }
2759
2760 // (X << C1) >>u C2 --> X << (C1-C2) & (-1 >> C2)
2761 if (I.getOpcode() == Instruction::LShr) {
2762 assert(ShiftOp->getOpcode() == Instruction::Shl);
Chris Lattnerad7516a2009-08-30 18:50:58 +00002763 Value *Shift = Builder->CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002764
2765 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersoneacb44d2009-07-24 23:12:02 +00002766 return BinaryOperator::CreateAnd(Shift,
Chris Lattner03a27b42010-01-04 07:02:48 +00002767 ConstantInt::get(I.getContext(),Mask));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002768 }
2769
2770 // We can't handle (X << C1) >>a C2, it shifts arbitrary bits in.
2771 }
2772 }
2773 return 0;
2774}
2775
2776
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002777
Chris Lattner94ccd5f2009-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 Lattner54dddc72009-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 Lattner54826cd2010-01-04 07:53:58 +00002782const Type *InstCombiner::FindElementAtOffset(const Type *Ty, int64_t Offset,
2783 SmallVectorImpl<Value*> &NewIndices) {
Dan Gohmana80e2712009-07-21 23:21:54 +00002784 if (!TD) return 0;
Chris Lattner54dddc72009-01-24 01:00:13 +00002785 if (!Ty->isSized()) return 0;
Chris Lattner94ccd5f2009-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 Lattner03a27b42010-01-04 07:02:48 +00002790 const Type *IntPtrTy = TD->getIntPtrType(Ty->getContext());
Chris Lattner94ccd5f2009-01-09 05:44:56 +00002791 int64_t FirstIdx = 0;
Duncan Sandsec4f97d2009-05-09 07:06:46 +00002792 if (int64_t TySize = TD->getTypeAllocSize(Ty)) {
Chris Lattner94ccd5f2009-01-09 05:44:56 +00002793 FirstIdx = Offset/TySize;
Chris Lattner0bd6f2b2009-01-11 20:41:36 +00002794 Offset -= FirstIdx*TySize;
Chris Lattner94ccd5f2009-01-09 05:44:56 +00002795
Chris Lattnerce48c462009-01-11 20:15:20 +00002796 // Handle hosts where % returns negative instead of values [0..TySize).
Chris Lattner94ccd5f2009-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 Andersoneacb44d2009-07-24 23:12:02 +00002805 NewIndices.push_back(ConstantInt::get(IntPtrTy, FirstIdx));
Chris Lattner94ccd5f2009-01-09 05:44:56 +00002806
2807 // Index into the types. If we fail, set OrigBase to null.
2808 while (Offset) {
Chris Lattnerce48c462009-01-11 20:15:20 +00002809 // Indexing into tail padding between struct/array elements.
2810 if (uint64_t(Offset*8) >= TD->getTypeSizeInBits(Ty))
Chris Lattner54dddc72009-01-24 01:00:13 +00002811 return 0;
Chris Lattnerce48c462009-01-11 20:15:20 +00002812
Chris Lattner94ccd5f2009-01-09 05:44:56 +00002813 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
2814 const StructLayout *SL = TD->getStructLayout(STy);
Chris Lattnerce48c462009-01-11 20:15:20 +00002815 assert(Offset < (int64_t)SL->getSizeInBytes() &&
2816 "Offset must stay within the indexed type");
2817
Chris Lattner94ccd5f2009-01-09 05:44:56 +00002818 unsigned Elt = SL->getElementContainingOffset(Offset);
Chris Lattner03a27b42010-01-04 07:02:48 +00002819 NewIndices.push_back(ConstantInt::get(Type::getInt32Ty(Ty->getContext()),
2820 Elt));
Chris Lattner94ccd5f2009-01-09 05:44:56 +00002821
2822 Offset -= SL->getElementOffset(Elt);
2823 Ty = STy->getElementType(Elt);
Chris Lattnerd35ce6a2009-01-11 20:23:52 +00002824 } else if (const ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
Duncan Sandsec4f97d2009-05-09 07:06:46 +00002825 uint64_t EltSize = TD->getTypeAllocSize(AT->getElementType());
Chris Lattnerce48c462009-01-11 20:15:20 +00002826 assert(EltSize && "Cannot index into a zero-sized array");
Owen Andersoneacb44d2009-07-24 23:12:02 +00002827 NewIndices.push_back(ConstantInt::get(IntPtrTy,Offset/EltSize));
Chris Lattnerce48c462009-01-11 20:15:20 +00002828 Offset %= EltSize;
Chris Lattnerd35ce6a2009-01-11 20:23:52 +00002829 Ty = AT->getElementType();
Chris Lattner94ccd5f2009-01-09 05:44:56 +00002830 } else {
Chris Lattnerce48c462009-01-11 20:15:20 +00002831 // Otherwise, we can't index into the middle of this atomic type, bail.
Chris Lattner54dddc72009-01-24 01:00:13 +00002832 return 0;
Chris Lattner94ccd5f2009-01-09 05:44:56 +00002833 }
2834 }
2835
Chris Lattner54dddc72009-01-24 01:00:13 +00002836 return Ty;
Chris Lattner94ccd5f2009-01-09 05:44:56 +00002837}
2838
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002839
Dan Gohman2d648bb2008-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 Lattner47cf3452007-08-09 19:05:49 +00002848
Dan Gohman2d648bb2008-04-10 18:43:06 +00002849 User *U = dyn_cast<User>(V);
2850 if (!U) return Align;
2851
Dan Gohman9545fb02009-07-17 20:47:02 +00002852 switch (Operator::getOpcode(U)) {
Dan Gohman2d648bb2008-04-10 18:43:06 +00002853 default: break;
2854 case Instruction::BitCast:
2855 return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
2856 case Instruction::GetElementPtr: {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002857 // If all indexes are zero, it is just the alignment of the base pointer.
2858 bool AllZeroOperands = true;
Gabor Greife92fbe22008-06-12 21:51:29 +00002859 for (User::op_iterator i = U->op_begin() + 1, e = U->op_end(); i != e; ++i)
Gabor Greif17396002008-06-12 21:37:33 +00002860 if (!isa<Constant>(*i) ||
2861 !cast<Constant>(*i)->isNullValue()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002862 AllZeroOperands = false;
2863 break;
2864 }
Chris Lattner47cf3452007-08-09 19:05:49 +00002865
2866 if (AllZeroOperands) {
2867 // Treat this like a bitcast.
Dan Gohman2d648bb2008-04-10 18:43:06 +00002868 return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
Chris Lattner47cf3452007-08-09 19:05:49 +00002869 }
Dan Gohman2d648bb2008-04-10 18:43:06 +00002870 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002871 }
Dan Gohman2d648bb2008-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 Gohmanf6fe71e2009-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 Gohman2d648bb2008-04-10 18:43:06 +00002884 }
Chris Lattnere8ad9ae2009-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 Gohman2d648bb2008-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;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002917}
2918
Chris Lattner00ae5132008-01-13 23:50:23 +00002919Instruction *InstCombiner::SimplifyMemTransfer(MemIntrinsic *MI) {
Dan Gohman2d648bb2008-04-10 18:43:06 +00002920 unsigned DstAlign = GetOrEnforceKnownAlignment(MI->getOperand(1));
Dan Gohmaneb254912009-02-22 18:06:32 +00002921 unsigned SrcAlign = GetOrEnforceKnownAlignment(MI->getOperand(2));
Chris Lattner00ae5132008-01-13 23:50:23 +00002922 unsigned MinAlign = std::min(DstAlign, SrcAlign);
Chris Lattner3947da72009-03-08 03:59:00 +00002923 unsigned CopyAlign = MI->getAlignment();
Chris Lattner00ae5132008-01-13 23:50:23 +00002924
2925 if (CopyAlign < MinAlign) {
Owen Andersoneacb44d2009-07-24 23:12:02 +00002926 MI->setAlignment(ConstantInt::get(MI->getAlignmentType(),
Owen Andersonf9f99362009-07-09 18:36:20 +00002927 MinAlign, false));
Chris Lattner00ae5132008-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 Lattnerc669fb62008-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 Lattner00ae5132008-01-13 23:50:23 +00002940 unsigned Size = MemOpLength->getZExtValue();
Chris Lattner5af8a912008-04-30 06:39:11 +00002941 if (Size == 0) return MI; // Delete this mem transfer.
2942
2943 if (Size > 8 || (Size&(Size-1)))
Chris Lattnerc669fb62008-01-14 00:28:35 +00002944 return 0; // If not 1/2/4/8 bytes, exit.
Chris Lattner00ae5132008-01-13 23:50:23 +00002945
Chris Lattnerc669fb62008-01-14 00:28:35 +00002946 // Use an integer load+store unless we can find something better.
Owen Anderson24be4c12009-07-03 00:17:18 +00002947 Type *NewPtrTy =
Chris Lattner03a27b42010-01-04 07:02:48 +00002948 PointerType::getUnqual(IntegerType::get(MI->getContext(), Size<<3));
Chris Lattnerc669fb62008-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 Gohmana80e2712009-07-21 23:21:54 +00002958 if (TD && SrcETy->isSized() && TD->getTypeStoreSize(SrcETy) == Size) {
Chris Lattnerc669fb62008-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 Gohmanb8e94f62008-05-23 01:52:21 +00002961 while (!SrcETy->isSingleValueType()) {
Chris Lattnerc669fb62008-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 Gohmanb8e94f62008-05-23 01:52:21 +00002976 if (SrcETy->isSingleValueType())
Owen Anderson6b6e2d92009-07-29 22:17:13 +00002977 NewPtrTy = PointerType::getUnqual(SrcETy);
Chris Lattnerc669fb62008-01-14 00:28:35 +00002978 }
2979 }
2980
2981
Chris Lattner00ae5132008-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 Lattner78628292009-08-30 19:47:22 +00002987 Value *Src = Builder->CreateBitCast(MI->getOperand(2), NewPtrTy);
2988 Value *Dest = Builder->CreateBitCast(MI->getOperand(1), NewPtrTy);
Chris Lattnerc669fb62008-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 Andersonaac28372009-07-31 20:28:14 +00002994 MI->setOperand(3, Constant::getNullValue(MemOpLength->getType()));
Chris Lattnerc669fb62008-01-14 00:28:35 +00002995 return MI;
Chris Lattner00ae5132008-01-13 23:50:23 +00002996}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002997
Chris Lattner5af8a912008-04-30 06:39:11 +00002998Instruction *InstCombiner::SimplifyMemSet(MemSetInst *MI) {
2999 unsigned Alignment = GetOrEnforceKnownAlignment(MI->getDest());
Chris Lattner3947da72009-03-08 03:59:00 +00003000 if (MI->getAlignment() < Alignment) {
Owen Andersoneacb44d2009-07-24 23:12:02 +00003001 MI->setAlignment(ConstantInt::get(MI->getAlignmentType(),
Owen Andersonf9f99362009-07-09 18:36:20 +00003002 Alignment, false));
Chris Lattner5af8a912008-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 Lattner03a27b42010-01-04 07:02:48 +00003009 if (!LenC || !FillC || FillC->getType() != Type::getInt8Ty(MI->getContext()))
Chris Lattner5af8a912008-04-30 06:39:11 +00003010 return 0;
3011 uint64_t Len = LenC->getZExtValue();
Chris Lattner3947da72009-03-08 03:59:00 +00003012 Alignment = MI->getAlignment();
Chris Lattner5af8a912008-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 Lattner03a27b42010-01-04 07:02:48 +00003019 const Type *ITy = IntegerType::get(MI->getContext(), Len*8); // n=1 -> i8.
Chris Lattner5af8a912008-04-30 06:39:11 +00003020
3021 Value *Dest = MI->getDest();
Chris Lattner78628292009-08-30 19:47:22 +00003022 Dest = Builder->CreateBitCast(Dest, PointerType::getUnqual(ITy));
Chris Lattner5af8a912008-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 Andersoneacb44d2009-07-24 23:12:02 +00003029 InsertNewInstBefore(new StoreInst(ConstantInt::get(ITy, Fill),
Owen Anderson24be4c12009-07-03 00:17:18 +00003030 Dest, false, Alignment), *MI);
Chris Lattner5af8a912008-04-30 06:39:11 +00003031
3032 // Set the size of the copy to 0, it will be deleted on the next iteration.
Owen Andersonaac28372009-07-31 20:28:14 +00003033 MI->setLength(Constant::getNullValue(LenC->getType()));
Chris Lattner5af8a912008-04-30 06:39:11 +00003034 return MI;
3035 }
3036
3037 return 0;
3038}
3039
3040
Dan Gohmanf17a25c2007-07-18 16:29:46 +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///
3045Instruction *InstCombiner::visitCallInst(CallInst &CI) {
Victor Hernandez93946082009-10-24 04:23:03 +00003046 if (isFreeCall(&CI))
3047 return visitFree(CI);
3048
Chris Lattneraa295aa2009-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
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003057 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
3058 if (!II) return visitCallSite(&CI);
3059
3060 // Intrinsics cannot occur in an invoke, so handle them here instead of in
3061 // visitCallSite.
3062 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
3063 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
3069 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
3070 if (CI->getZExtValue() == 1) {
3071 // 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 }
3075 }
3076
3077 // 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 Lattner00ae5132008-01-13 23:50:23 +00003080 if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003081 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
3082 if (GVSrc->isConstant()) {
3083 Module *M = CI.getParent()->getParent()->getParent();
Chris Lattner82c2e432008-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));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003089 Changed = true;
3090 }
Eli Friedman626e32a2009-12-17 21:07:31 +00003091 }
Chris Lattner59b27d92008-05-28 05:30:41 +00003092
Eli Friedman626e32a2009-12-17 21:07:31 +00003093 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(MI)) {
Chris Lattner59b27d92008-05-28 05:30:41 +00003094 // memmove(x,x,size) -> noop.
Eli Friedman626e32a2009-12-17 21:07:31 +00003095 if (MTI->getSource() == MTI->getDest())
Chris Lattner59b27d92008-05-28 05:30:41 +00003096 return EraseInstFromFunction(CI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003097 }
3098
3099 // If we can determine a pointer alignment that is bigger than currently
3100 // set, update the alignment.
Chris Lattnera86628a2009-03-08 03:37:16 +00003101 if (isa<MemTransferInst>(MI)) {
Chris Lattner00ae5132008-01-13 23:50:23 +00003102 if (Instruction *I = SimplifyMemTransfer(MI))
3103 return I;
Chris Lattner5af8a912008-04-30 06:39:11 +00003104 } else if (MemSetInst *MSI = dyn_cast<MemSetInst>(MI)) {
3105 if (Instruction *I = SimplifyMemSet(MSI))
3106 return I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003107 }
3108
3109 if (Changed) return II;
Chris Lattner989ba312008-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 Lattner723b9642010-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 Lattner989ba312008-06-18 04:33:20 +00003132 break;
Chris Lattnerfd4f21a2010-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 Lattner60179fb2010-01-01 01:54:08 +00003142 if (Power->isAllOnesValue())
3143 return BinaryOperator::CreateFDiv(ConstantFP::get(CI.getType(), 1.0),
3144 II->getOperand(1));
Chris Lattnerfd4f21a2010-01-01 01:52:15 +00003145 }
3146 break;
Chris Lattnerf01e3cc2010-01-05 07:23:56 +00003147 case Intrinsic::cttz: {
3148 // If all bits below the first known one are known zero,
3149 // this value is constant.
3150 const IntegerType *IT = cast<IntegerType>(II->getOperand(1)->getType());
3151 uint32_t BitWidth = IT->getBitWidth();
3152 APInt KnownZero(BitWidth, 0);
3153 APInt KnownOne(BitWidth, 0);
3154 ComputeMaskedBits(II->getOperand(1), APInt::getAllOnesValue(BitWidth),
3155 KnownZero, KnownOne);
3156 unsigned TrailingZeros = KnownOne.countTrailingZeros();
3157 APInt Mask(APInt::getLowBitsSet(BitWidth, TrailingZeros));
3158 if ((Mask & KnownZero) == Mask)
3159 return ReplaceInstUsesWith(CI, ConstantInt::get(IT,
3160 APInt(BitWidth, TrailingZeros)));
3161
3162 }
3163 break;
3164 case Intrinsic::ctlz: {
3165 // If all bits above the first known one are known zero,
3166 // this value is constant.
3167 const IntegerType *IT = cast<IntegerType>(II->getOperand(1)->getType());
3168 uint32_t BitWidth = IT->getBitWidth();
3169 APInt KnownZero(BitWidth, 0);
3170 APInt KnownOne(BitWidth, 0);
3171 ComputeMaskedBits(II->getOperand(1), APInt::getAllOnesValue(BitWidth),
3172 KnownZero, KnownOne);
3173 unsigned LeadingZeros = KnownOne.countLeadingZeros();
3174 APInt Mask(APInt::getHighBitsSet(BitWidth, LeadingZeros));
3175 if ((Mask & KnownZero) == Mask)
3176 return ReplaceInstUsesWith(CI, ConstantInt::get(IT,
3177 APInt(BitWidth, LeadingZeros)));
3178
3179 }
3180 break;
Chris Lattner0b452262009-11-26 21:42:47 +00003181 case Intrinsic::uadd_with_overflow: {
3182 Value *LHS = II->getOperand(1), *RHS = II->getOperand(2);
3183 const IntegerType *IT = cast<IntegerType>(II->getOperand(1)->getType());
3184 uint32_t BitWidth = IT->getBitWidth();
3185 APInt Mask = APInt::getSignBit(BitWidth);
Chris Lattner65e34842009-11-26 22:08:06 +00003186 APInt LHSKnownZero(BitWidth, 0);
3187 APInt LHSKnownOne(BitWidth, 0);
Chris Lattner0b452262009-11-26 21:42:47 +00003188 ComputeMaskedBits(LHS, Mask, LHSKnownZero, LHSKnownOne);
3189 bool LHSKnownNegative = LHSKnownOne[BitWidth - 1];
3190 bool LHSKnownPositive = LHSKnownZero[BitWidth - 1];
3191
3192 if (LHSKnownNegative || LHSKnownPositive) {
Chris Lattner65e34842009-11-26 22:08:06 +00003193 APInt RHSKnownZero(BitWidth, 0);
3194 APInt RHSKnownOne(BitWidth, 0);
Chris Lattner0b452262009-11-26 21:42:47 +00003195 ComputeMaskedBits(RHS, Mask, RHSKnownZero, RHSKnownOne);
3196 bool RHSKnownNegative = RHSKnownOne[BitWidth - 1];
3197 bool RHSKnownPositive = RHSKnownZero[BitWidth - 1];
3198 if (LHSKnownNegative && RHSKnownNegative) {
3199 // The sign bit is set in both cases: this MUST overflow.
3200 // Create a simple add instruction, and insert it into the struct.
3201 Instruction *Add = BinaryOperator::CreateAdd(LHS, RHS, "", &CI);
3202 Worklist.Add(Add);
Chris Lattnerdbbf1b22009-11-29 02:57:29 +00003203 Constant *V[] = {
Chris Lattner03a27b42010-01-04 07:02:48 +00003204 UndefValue::get(LHS->getType()),ConstantInt::getTrue(II->getContext())
Chris Lattnerdbbf1b22009-11-29 02:57:29 +00003205 };
Chris Lattner03a27b42010-01-04 07:02:48 +00003206 Constant *Struct = ConstantStruct::get(II->getContext(), V, 2, false);
Chris Lattner0b452262009-11-26 21:42:47 +00003207 return InsertValueInst::Create(Struct, Add, 0);
3208 }
3209
3210 if (LHSKnownPositive && RHSKnownPositive) {
3211 // The sign bit is clear in both cases: this CANNOT overflow.
3212 // Create a simple add instruction, and insert it into the struct.
3213 Instruction *Add = BinaryOperator::CreateNUWAdd(LHS, RHS, "", &CI);
3214 Worklist.Add(Add);
Chris Lattnerdbbf1b22009-11-29 02:57:29 +00003215 Constant *V[] = {
Chris Lattner03a27b42010-01-04 07:02:48 +00003216 UndefValue::get(LHS->getType()),
3217 ConstantInt::getFalse(II->getContext())
Chris Lattnerdbbf1b22009-11-29 02:57:29 +00003218 };
Chris Lattner03a27b42010-01-04 07:02:48 +00003219 Constant *Struct = ConstantStruct::get(II->getContext(), V, 2, false);
Chris Lattner0b452262009-11-26 21:42:47 +00003220 return InsertValueInst::Create(Struct, Add, 0);
3221 }
3222 }
3223 }
3224 // FALL THROUGH uadd into sadd
3225 case Intrinsic::sadd_with_overflow:
3226 // Canonicalize constants into the RHS.
3227 if (isa<Constant>(II->getOperand(1)) &&
3228 !isa<Constant>(II->getOperand(2))) {
3229 Value *LHS = II->getOperand(1);
3230 II->setOperand(1, II->getOperand(2));
3231 II->setOperand(2, LHS);
3232 return II;
3233 }
3234
3235 // X + undef -> undef
3236 if (isa<UndefValue>(II->getOperand(2)))
3237 return ReplaceInstUsesWith(CI, UndefValue::get(II->getType()));
3238
3239 if (ConstantInt *RHS = dyn_cast<ConstantInt>(II->getOperand(2))) {
3240 // X + 0 -> {X, false}
3241 if (RHS->isZero()) {
3242 Constant *V[] = {
Chris Lattnerdbbf1b22009-11-29 02:57:29 +00003243 UndefValue::get(II->getOperand(0)->getType()),
Chris Lattner03a27b42010-01-04 07:02:48 +00003244 ConstantInt::getFalse(II->getContext())
Chris Lattner0b452262009-11-26 21:42:47 +00003245 };
Chris Lattner03a27b42010-01-04 07:02:48 +00003246 Constant *Struct = ConstantStruct::get(II->getContext(), V, 2, false);
Chris Lattner0b452262009-11-26 21:42:47 +00003247 return InsertValueInst::Create(Struct, II->getOperand(1), 0);
3248 }
3249 }
3250 break;
3251 case Intrinsic::usub_with_overflow:
3252 case Intrinsic::ssub_with_overflow:
3253 // undef - X -> undef
3254 // X - undef -> undef
3255 if (isa<UndefValue>(II->getOperand(1)) ||
3256 isa<UndefValue>(II->getOperand(2)))
3257 return ReplaceInstUsesWith(CI, UndefValue::get(II->getType()));
3258
3259 if (ConstantInt *RHS = dyn_cast<ConstantInt>(II->getOperand(2))) {
3260 // X - 0 -> {X, false}
3261 if (RHS->isZero()) {
3262 Constant *V[] = {
Chris Lattnerdbbf1b22009-11-29 02:57:29 +00003263 UndefValue::get(II->getOperand(1)->getType()),
Chris Lattner03a27b42010-01-04 07:02:48 +00003264 ConstantInt::getFalse(II->getContext())
Chris Lattner0b452262009-11-26 21:42:47 +00003265 };
Chris Lattner03a27b42010-01-04 07:02:48 +00003266 Constant *Struct = ConstantStruct::get(II->getContext(), V, 2, false);
Chris Lattner0b452262009-11-26 21:42:47 +00003267 return InsertValueInst::Create(Struct, II->getOperand(1), 0);
3268 }
3269 }
3270 break;
3271 case Intrinsic::umul_with_overflow:
3272 case Intrinsic::smul_with_overflow:
3273 // Canonicalize constants into the RHS.
3274 if (isa<Constant>(II->getOperand(1)) &&
3275 !isa<Constant>(II->getOperand(2))) {
3276 Value *LHS = II->getOperand(1);
3277 II->setOperand(1, II->getOperand(2));
3278 II->setOperand(2, LHS);
3279 return II;
3280 }
3281
3282 // X * undef -> undef
3283 if (isa<UndefValue>(II->getOperand(2)))
3284 return ReplaceInstUsesWith(CI, UndefValue::get(II->getType()));
3285
3286 if (ConstantInt *RHSI = dyn_cast<ConstantInt>(II->getOperand(2))) {
3287 // X*0 -> {0, false}
3288 if (RHSI->isZero())
3289 return ReplaceInstUsesWith(CI, Constant::getNullValue(II->getType()));
3290
3291 // X * 1 -> {X, false}
3292 if (RHSI->equalsInt(1)) {
Chris Lattnerdbbf1b22009-11-29 02:57:29 +00003293 Constant *V[] = {
3294 UndefValue::get(II->getOperand(1)->getType()),
Chris Lattner03a27b42010-01-04 07:02:48 +00003295 ConstantInt::getFalse(II->getContext())
Chris Lattnerdbbf1b22009-11-29 02:57:29 +00003296 };
Chris Lattner03a27b42010-01-04 07:02:48 +00003297 Constant *Struct = ConstantStruct::get(II->getContext(), V, 2, false);
Chris Lattnerdbbf1b22009-11-29 02:57:29 +00003298 return InsertValueInst::Create(Struct, II->getOperand(1), 0);
Chris Lattner0b452262009-11-26 21:42:47 +00003299 }
3300 }
3301 break;
Chris Lattner989ba312008-06-18 04:33:20 +00003302 case Intrinsic::ppc_altivec_lvx:
3303 case Intrinsic::ppc_altivec_lvxl:
3304 case Intrinsic::x86_sse_loadu_ps:
3305 case Intrinsic::x86_sse2_loadu_pd:
3306 case Intrinsic::x86_sse2_loadu_dq:
3307 // Turn PPC lvx -> load if the pointer is known aligned.
3308 // Turn X86 loadups -> load if the pointer is known aligned.
3309 if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
Chris Lattner78628292009-08-30 19:47:22 +00003310 Value *Ptr = Builder->CreateBitCast(II->getOperand(1),
3311 PointerType::getUnqual(II->getType()));
Chris Lattner989ba312008-06-18 04:33:20 +00003312 return new LoadInst(Ptr);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003313 }
Chris Lattner989ba312008-06-18 04:33:20 +00003314 break;
3315 case Intrinsic::ppc_altivec_stvx:
3316 case Intrinsic::ppc_altivec_stvxl:
3317 // Turn stvx -> store if the pointer is known aligned.
3318 if (GetOrEnforceKnownAlignment(II->getOperand(2), 16) >= 16) {
3319 const Type *OpPtrTy =
Owen Anderson6b6e2d92009-07-29 22:17:13 +00003320 PointerType::getUnqual(II->getOperand(1)->getType());
Chris Lattner78628292009-08-30 19:47:22 +00003321 Value *Ptr = Builder->CreateBitCast(II->getOperand(2), OpPtrTy);
Chris Lattner989ba312008-06-18 04:33:20 +00003322 return new StoreInst(II->getOperand(1), Ptr);
3323 }
3324 break;
3325 case Intrinsic::x86_sse_storeu_ps:
3326 case Intrinsic::x86_sse2_storeu_pd:
3327 case Intrinsic::x86_sse2_storeu_dq:
Chris Lattner989ba312008-06-18 04:33:20 +00003328 // Turn X86 storeu -> store if the pointer is known aligned.
3329 if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
3330 const Type *OpPtrTy =
Owen Anderson6b6e2d92009-07-29 22:17:13 +00003331 PointerType::getUnqual(II->getOperand(2)->getType());
Chris Lattner78628292009-08-30 19:47:22 +00003332 Value *Ptr = Builder->CreateBitCast(II->getOperand(1), OpPtrTy);
Chris Lattner989ba312008-06-18 04:33:20 +00003333 return new StoreInst(II->getOperand(2), Ptr);
3334 }
3335 break;
3336
3337 case Intrinsic::x86_sse_cvttss2si: {
3338 // These intrinsics only demands the 0th element of its input vector. If
3339 // we can simplify the input based on that, do so now.
Evan Cheng63295ab2009-02-03 10:05:09 +00003340 unsigned VWidth =
3341 cast<VectorType>(II->getOperand(1)->getType())->getNumElements();
3342 APInt DemandedElts(VWidth, 1);
3343 APInt UndefElts(VWidth, 0);
3344 if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
Chris Lattner989ba312008-06-18 04:33:20 +00003345 UndefElts)) {
3346 II->setOperand(1, V);
3347 return II;
3348 }
3349 break;
3350 }
3351
3352 case Intrinsic::ppc_altivec_vperm:
3353 // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
3354 if (ConstantVector *Mask = dyn_cast<ConstantVector>(II->getOperand(3))) {
3355 assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003356
Chris Lattner989ba312008-06-18 04:33:20 +00003357 // Check that all of the elements are integer constants or undefs.
3358 bool AllEltsOk = true;
3359 for (unsigned i = 0; i != 16; ++i) {
3360 if (!isa<ConstantInt>(Mask->getOperand(i)) &&
3361 !isa<UndefValue>(Mask->getOperand(i))) {
3362 AllEltsOk = false;
3363 break;
3364 }
3365 }
3366
3367 if (AllEltsOk) {
3368 // Cast the input vectors to byte vectors.
Chris Lattner78628292009-08-30 19:47:22 +00003369 Value *Op0 = Builder->CreateBitCast(II->getOperand(1), Mask->getType());
3370 Value *Op1 = Builder->CreateBitCast(II->getOperand(2), Mask->getType());
Owen Andersonb99ecca2009-07-30 23:03:37 +00003371 Value *Result = UndefValue::get(Op0->getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003372
Chris Lattner989ba312008-06-18 04:33:20 +00003373 // Only extract each element once.
3374 Value *ExtractedElts[32];
3375 memset(ExtractedElts, 0, sizeof(ExtractedElts));
3376
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003377 for (unsigned i = 0; i != 16; ++i) {
Chris Lattner989ba312008-06-18 04:33:20 +00003378 if (isa<UndefValue>(Mask->getOperand(i)))
3379 continue;
3380 unsigned Idx=cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
3381 Idx &= 31; // Match the hardware behavior.
3382
3383 if (ExtractedElts[Idx] == 0) {
Chris Lattnerad7516a2009-08-30 18:50:58 +00003384 ExtractedElts[Idx] =
3385 Builder->CreateExtractElement(Idx < 16 ? Op0 : Op1,
Chris Lattner03a27b42010-01-04 07:02:48 +00003386 ConstantInt::get(Type::getInt32Ty(II->getContext()),
3387 Idx&15, false), "tmp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003388 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003389
Chris Lattner989ba312008-06-18 04:33:20 +00003390 // Insert this value into the result vector.
Chris Lattnerad7516a2009-08-30 18:50:58 +00003391 Result = Builder->CreateInsertElement(Result, ExtractedElts[Idx],
Chris Lattner03a27b42010-01-04 07:02:48 +00003392 ConstantInt::get(Type::getInt32Ty(II->getContext()),
3393 i, false), "tmp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003394 }
Chris Lattner989ba312008-06-18 04:33:20 +00003395 return CastInst::Create(Instruction::BitCast, Result, CI.getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003396 }
Chris Lattner989ba312008-06-18 04:33:20 +00003397 }
3398 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003399
Chris Lattner989ba312008-06-18 04:33:20 +00003400 case Intrinsic::stackrestore: {
3401 // If the save is right next to the restore, remove the restore. This can
3402 // happen when variable allocas are DCE'd.
3403 if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
3404 if (SS->getIntrinsicID() == Intrinsic::stacksave) {
3405 BasicBlock::iterator BI = SS;
3406 if (&*++BI == II)
3407 return EraseInstFromFunction(CI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003408 }
Chris Lattner989ba312008-06-18 04:33:20 +00003409 }
3410
3411 // Scan down this block to see if there is another stack restore in the
3412 // same block without an intervening call/alloca.
3413 BasicBlock::iterator BI = II;
3414 TerminatorInst *TI = II->getParent()->getTerminator();
3415 bool CannotRemove = false;
3416 for (++BI; &*BI != TI; ++BI) {
Victor Hernandez48c3c542009-09-18 22:35:49 +00003417 if (isa<AllocaInst>(BI) || isMalloc(BI)) {
Chris Lattner989ba312008-06-18 04:33:20 +00003418 CannotRemove = true;
3419 break;
3420 }
Chris Lattnera6b477c2008-06-25 05:59:28 +00003421 if (CallInst *BCI = dyn_cast<CallInst>(BI)) {
3422 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(BCI)) {
3423 // If there is a stackrestore below this one, remove this one.
3424 if (II->getIntrinsicID() == Intrinsic::stackrestore)
3425 return EraseInstFromFunction(CI);
3426 // Otherwise, ignore the intrinsic.
3427 } else {
3428 // If we found a non-intrinsic call, we can't remove the stack
3429 // restore.
Chris Lattner416d91c2008-02-18 06:12:38 +00003430 CannotRemove = true;
3431 break;
3432 }
Chris Lattner989ba312008-06-18 04:33:20 +00003433 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003434 }
Chris Lattner989ba312008-06-18 04:33:20 +00003435
3436 // If the stack restore is in a return/unwind block and if there are no
3437 // allocas or calls between the restore and the return, nuke the restore.
3438 if (!CannotRemove && (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)))
3439 return EraseInstFromFunction(CI);
3440 break;
3441 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003442 }
3443
3444 return visitCallSite(II);
3445}
3446
3447// InvokeInst simplification
3448//
3449Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
3450 return visitCallSite(&II);
3451}
3452
Dale Johannesen96021832008-04-25 21:16:07 +00003453/// isSafeToEliminateVarargsCast - If this cast does not affect the value
3454/// passed through the varargs area, we can eliminate the use of the cast.
Dale Johannesen35615462008-04-23 18:34:37 +00003455static bool isSafeToEliminateVarargsCast(const CallSite CS,
3456 const CastInst * const CI,
3457 const TargetData * const TD,
3458 const int ix) {
3459 if (!CI->isLosslessCast())
3460 return false;
3461
3462 // The size of ByVal arguments is derived from the type, so we
3463 // can't change to a type with a different size. If the size were
3464 // passed explicitly we could avoid this check.
Devang Pateld222f862008-09-25 21:00:45 +00003465 if (!CS.paramHasAttr(ix, Attribute::ByVal))
Dale Johannesen35615462008-04-23 18:34:37 +00003466 return true;
3467
3468 const Type* SrcTy =
3469 cast<PointerType>(CI->getOperand(0)->getType())->getElementType();
3470 const Type* DstTy = cast<PointerType>(CI->getType())->getElementType();
3471 if (!SrcTy->isSized() || !DstTy->isSized())
3472 return false;
Dan Gohmana80e2712009-07-21 23:21:54 +00003473 if (!TD || TD->getTypeAllocSize(SrcTy) != TD->getTypeAllocSize(DstTy))
Dale Johannesen35615462008-04-23 18:34:37 +00003474 return false;
3475 return true;
3476}
3477
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003478// visitCallSite - Improvements for call and invoke instructions.
3479//
3480Instruction *InstCombiner::visitCallSite(CallSite CS) {
3481 bool Changed = false;
3482
3483 // If the callee is a constexpr cast of a function, attempt to move the cast
3484 // to the arguments of the call/invoke.
3485 if (transformConstExprCastCall(CS)) return 0;
3486
3487 Value *Callee = CS.getCalledValue();
3488
3489 if (Function *CalleeF = dyn_cast<Function>(Callee))
3490 if (CalleeF->getCallingConv() != CS.getCallingConv()) {
3491 Instruction *OldCall = CS.getInstruction();
3492 // If the call and callee calling conventions don't match, this call must
3493 // be unreachable, as the call is undefined.
Chris Lattner03a27b42010-01-04 07:02:48 +00003494 new StoreInst(ConstantInt::getTrue(Callee->getContext()),
3495 UndefValue::get(Type::getInt1PtrTy(Callee->getContext())),
Owen Anderson24be4c12009-07-03 00:17:18 +00003496 OldCall);
Devang Patele3829c82009-10-13 22:56:32 +00003497 // If OldCall dues not return void then replaceAllUsesWith undef.
3498 // This allows ValueHandlers and custom metadata to adjust itself.
Devang Patele9d08b82009-10-14 17:29:00 +00003499 if (!OldCall->getType()->isVoidTy())
Devang Patele3829c82009-10-13 22:56:32 +00003500 OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003501 if (isa<CallInst>(OldCall)) // Not worth removing an invoke here.
3502 return EraseInstFromFunction(*OldCall);
3503 return 0;
3504 }
3505
3506 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
3507 // This instruction is not reachable, just remove it. We insert a store to
3508 // undef so that we know that this code is not reachable, despite the fact
3509 // that we can't modify the CFG here.
Chris Lattner03a27b42010-01-04 07:02:48 +00003510 new StoreInst(ConstantInt::getTrue(Callee->getContext()),
3511 UndefValue::get(Type::getInt1PtrTy(Callee->getContext())),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003512 CS.getInstruction());
3513
Devang Patele3829c82009-10-13 22:56:32 +00003514 // If CS dues not return void then replaceAllUsesWith undef.
3515 // This allows ValueHandlers and custom metadata to adjust itself.
Devang Patele9d08b82009-10-14 17:29:00 +00003516 if (!CS.getInstruction()->getType()->isVoidTy())
Devang Patele3829c82009-10-13 22:56:32 +00003517 CS.getInstruction()->
3518 replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003519
3520 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
3521 // Don't break the CFG, insert a dummy cond branch.
Gabor Greifd6da1d02008-04-06 20:25:17 +00003522 BranchInst::Create(II->getNormalDest(), II->getUnwindDest(),
Chris Lattner03a27b42010-01-04 07:02:48 +00003523 ConstantInt::getTrue(Callee->getContext()), II);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003524 }
3525 return EraseInstFromFunction(*CS.getInstruction());
3526 }
3527
Duncan Sands74833f22007-09-17 10:26:40 +00003528 if (BitCastInst *BC = dyn_cast<BitCastInst>(Callee))
3529 if (IntrinsicInst *In = dyn_cast<IntrinsicInst>(BC->getOperand(0)))
3530 if (In->getIntrinsicID() == Intrinsic::init_trampoline)
3531 return transformCallThroughTrampoline(CS);
3532
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003533 const PointerType *PTy = cast<PointerType>(Callee->getType());
3534 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
3535 if (FTy->isVarArg()) {
Dale Johannesen502336c2008-04-23 01:03:05 +00003536 int ix = FTy->getNumParams() + (isa<InvokeInst>(Callee) ? 3 : 1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003537 // See if we can optimize any arguments passed through the varargs area of
3538 // the call.
3539 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
Dale Johannesen35615462008-04-23 18:34:37 +00003540 E = CS.arg_end(); I != E; ++I, ++ix) {
3541 CastInst *CI = dyn_cast<CastInst>(*I);
3542 if (CI && isSafeToEliminateVarargsCast(CS, CI, TD, ix)) {
3543 *I = CI->getOperand(0);
3544 Changed = true;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003545 }
Dale Johannesen35615462008-04-23 18:34:37 +00003546 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003547 }
3548
Duncan Sands2937e352007-12-19 21:13:37 +00003549 if (isa<InlineAsm>(Callee) && !CS.doesNotThrow()) {
Duncan Sands7868f3c2007-12-16 15:51:49 +00003550 // Inline asm calls cannot throw - mark them 'nounwind'.
Duncan Sands2937e352007-12-19 21:13:37 +00003551 CS.setDoesNotThrow();
Duncan Sands7868f3c2007-12-16 15:51:49 +00003552 Changed = true;
3553 }
3554
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003555 return Changed ? CS.getInstruction() : 0;
3556}
3557
3558// transformConstExprCastCall - If the callee is a constexpr cast of a function,
3559// attempt to move the cast to the arguments of the call/invoke.
3560//
3561bool InstCombiner::transformConstExprCastCall(CallSite CS) {
3562 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
3563 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
3564 if (CE->getOpcode() != Instruction::BitCast ||
3565 !isa<Function>(CE->getOperand(0)))
3566 return false;
3567 Function *Callee = cast<Function>(CE->getOperand(0));
3568 Instruction *Caller = CS.getInstruction();
Devang Pateld222f862008-09-25 21:00:45 +00003569 const AttrListPtr &CallerPAL = CS.getAttributes();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003570
3571 // Okay, this is a cast from a function to a different type. Unless doing so
3572 // would cause a type conversion of one of our arguments, change this call to
3573 // be a direct call with arguments casted to the appropriate types.
3574 //
3575 const FunctionType *FT = Callee->getFunctionType();
3576 const Type *OldRetTy = Caller->getType();
Duncan Sands7901ce12008-06-01 07:38:42 +00003577 const Type *NewRetTy = FT->getReturnType();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003578
Duncan Sands7901ce12008-06-01 07:38:42 +00003579 if (isa<StructType>(NewRetTy))
Devang Pateld091d322008-03-11 18:04:06 +00003580 return false; // TODO: Handle multiple return values.
3581
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003582 // Check to see if we are changing the return type...
Duncan Sands7901ce12008-06-01 07:38:42 +00003583 if (OldRetTy != NewRetTy) {
Bill Wendlingd9644a42008-05-14 22:45:20 +00003584 if (Callee->isDeclaration() &&
Duncan Sands7901ce12008-06-01 07:38:42 +00003585 // Conversion is ok if changing from one pointer type to another or from
3586 // a pointer to an integer of the same size.
Dan Gohmana80e2712009-07-21 23:21:54 +00003587 !((isa<PointerType>(OldRetTy) || !TD ||
Owen Anderson35b47072009-08-13 21:58:54 +00003588 OldRetTy == TD->getIntPtrType(Caller->getContext())) &&
Dan Gohmana80e2712009-07-21 23:21:54 +00003589 (isa<PointerType>(NewRetTy) || !TD ||
Owen Anderson35b47072009-08-13 21:58:54 +00003590 NewRetTy == TD->getIntPtrType(Caller->getContext()))))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003591 return false; // Cannot transform this return value.
3592
Duncan Sands5c489582008-01-06 10:12:28 +00003593 if (!Caller->use_empty() &&
Duncan Sands5c489582008-01-06 10:12:28 +00003594 // void -> non-void is handled specially
Devang Patele9d08b82009-10-14 17:29:00 +00003595 !NewRetTy->isVoidTy() && !CastInst::isCastable(NewRetTy, OldRetTy))
Duncan Sands5c489582008-01-06 10:12:28 +00003596 return false; // Cannot transform this return value.
3597
Chris Lattner1c8733e2008-03-12 17:45:29 +00003598 if (!CallerPAL.isEmpty() && !Caller->use_empty()) {
Devang Patelf2a4a922008-09-26 22:53:05 +00003599 Attributes RAttrs = CallerPAL.getRetAttributes();
Devang Pateld222f862008-09-25 21:00:45 +00003600 if (RAttrs & Attribute::typeIncompatible(NewRetTy))
Duncan Sandsdbe97dc2008-01-07 17:16:06 +00003601 return false; // Attribute not compatible with transformed value.
3602 }
Duncan Sandsc849e662008-01-06 18:27:01 +00003603
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003604 // If the callsite is an invoke instruction, and the return value is used by
3605 // a PHI node in a successor, we cannot change the return type of the call
3606 // because there is no place to put the cast instruction (without breaking
3607 // the critical edge). Bail out in this case.
3608 if (!Caller->use_empty())
3609 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
3610 for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
3611 UI != E; ++UI)
3612 if (PHINode *PN = dyn_cast<PHINode>(*UI))
3613 if (PN->getParent() == II->getNormalDest() ||
3614 PN->getParent() == II->getUnwindDest())
3615 return false;
3616 }
3617
3618 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
3619 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
3620
3621 CallSite::arg_iterator AI = CS.arg_begin();
3622 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
3623 const Type *ParamTy = FT->getParamType(i);
3624 const Type *ActTy = (*AI)->getType();
Duncan Sands5c489582008-01-06 10:12:28 +00003625
3626 if (!CastInst::isCastable(ActTy, ParamTy))
Duncan Sandsc849e662008-01-06 18:27:01 +00003627 return false; // Cannot transform this parameter value.
3628
Devang Patelf2a4a922008-09-26 22:53:05 +00003629 if (CallerPAL.getParamAttributes(i + 1)
3630 & Attribute::typeIncompatible(ParamTy))
Chris Lattner1c8733e2008-03-12 17:45:29 +00003631 return false; // Attribute not compatible with transformed value.
Duncan Sands5c489582008-01-06 10:12:28 +00003632
Duncan Sands7901ce12008-06-01 07:38:42 +00003633 // Converting from one pointer type to another or between a pointer and an
3634 // integer of the same size is safe even if we do not have a body.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003635 bool isConvertible = ActTy == ParamTy ||
Owen Anderson35b47072009-08-13 21:58:54 +00003636 (TD && ((isa<PointerType>(ParamTy) ||
3637 ParamTy == TD->getIntPtrType(Caller->getContext())) &&
3638 (isa<PointerType>(ActTy) ||
3639 ActTy == TD->getIntPtrType(Caller->getContext()))));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003640 if (Callee->isDeclaration() && !isConvertible) return false;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003641 }
3642
3643 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
3644 Callee->isDeclaration())
Chris Lattner1c8733e2008-03-12 17:45:29 +00003645 return false; // Do not delete arguments unless we have a function body.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003646
Chris Lattner1c8733e2008-03-12 17:45:29 +00003647 if (FT->getNumParams() < NumActualArgs && FT->isVarArg() &&
3648 !CallerPAL.isEmpty())
Duncan Sandsc849e662008-01-06 18:27:01 +00003649 // In this case we have more arguments than the new function type, but we
Duncan Sands4ced1f82008-01-13 08:02:44 +00003650 // won't be dropping them. Check that these extra arguments have attributes
3651 // that are compatible with being a vararg call argument.
Chris Lattner1c8733e2008-03-12 17:45:29 +00003652 for (unsigned i = CallerPAL.getNumSlots(); i; --i) {
3653 if (CallerPAL.getSlot(i - 1).Index <= FT->getNumParams())
Duncan Sands4ced1f82008-01-13 08:02:44 +00003654 break;
Devang Patele480dfa2008-09-23 23:03:40 +00003655 Attributes PAttrs = CallerPAL.getSlot(i - 1).Attrs;
Devang Pateld222f862008-09-25 21:00:45 +00003656 if (PAttrs & Attribute::VarArgsIncompatible)
Duncan Sands4ced1f82008-01-13 08:02:44 +00003657 return false;
3658 }
Duncan Sandsc849e662008-01-06 18:27:01 +00003659
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003660 // Okay, we decided that this is a safe thing to do: go ahead and start
3661 // inserting cast instructions as necessary...
3662 std::vector<Value*> Args;
3663 Args.reserve(NumActualArgs);
Devang Pateld222f862008-09-25 21:00:45 +00003664 SmallVector<AttributeWithIndex, 8> attrVec;
Duncan Sandsc849e662008-01-06 18:27:01 +00003665 attrVec.reserve(NumCommonArgs);
3666
3667 // Get any return attributes.
Devang Patelf2a4a922008-09-26 22:53:05 +00003668 Attributes RAttrs = CallerPAL.getRetAttributes();
Duncan Sandsc849e662008-01-06 18:27:01 +00003669
3670 // If the return value is not being used, the type may not be compatible
3671 // with the existing attributes. Wipe out any problematic attributes.
Devang Pateld222f862008-09-25 21:00:45 +00003672 RAttrs &= ~Attribute::typeIncompatible(NewRetTy);
Duncan Sandsc849e662008-01-06 18:27:01 +00003673
3674 // Add the new return attributes.
3675 if (RAttrs)
Devang Pateld222f862008-09-25 21:00:45 +00003676 attrVec.push_back(AttributeWithIndex::get(0, RAttrs));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003677
3678 AI = CS.arg_begin();
3679 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
3680 const Type *ParamTy = FT->getParamType(i);
3681 if ((*AI)->getType() == ParamTy) {
3682 Args.push_back(*AI);
3683 } else {
3684 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
3685 false, ParamTy, false);
Chris Lattnerad7516a2009-08-30 18:50:58 +00003686 Args.push_back(Builder->CreateCast(opcode, *AI, ParamTy, "tmp"));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003687 }
Duncan Sandsc849e662008-01-06 18:27:01 +00003688
3689 // Add any parameter attributes.
Devang Patelf2a4a922008-09-26 22:53:05 +00003690 if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
Devang Pateld222f862008-09-25 21:00:45 +00003691 attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003692 }
3693
3694 // If the function takes more arguments than the call was taking, add them
Chris Lattnerad7516a2009-08-30 18:50:58 +00003695 // now.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003696 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
Owen Andersonaac28372009-07-31 20:28:14 +00003697 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003698
Chris Lattnerad7516a2009-08-30 18:50:58 +00003699 // If we are removing arguments to the function, emit an obnoxious warning.
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00003700 if (FT->getNumParams() < NumActualArgs) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003701 if (!FT->isVarArg()) {
Daniel Dunbar005975c2009-07-25 00:23:56 +00003702 errs() << "WARNING: While resolving call to function '"
3703 << Callee->getName() << "' arguments were dropped!\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003704 } else {
Chris Lattnerad7516a2009-08-30 18:50:58 +00003705 // Add all of the arguments in their promoted form to the arg list.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003706 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
3707 const Type *PTy = getPromotedType((*AI)->getType());
3708 if (PTy != (*AI)->getType()) {
3709 // Must promote to pass through va_arg area!
Chris Lattnerad7516a2009-08-30 18:50:58 +00003710 Instruction::CastOps opcode =
3711 CastInst::getCastOpcode(*AI, false, PTy, false);
3712 Args.push_back(Builder->CreateCast(opcode, *AI, PTy, "tmp"));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003713 } else {
3714 Args.push_back(*AI);
3715 }
Duncan Sandsc849e662008-01-06 18:27:01 +00003716
Duncan Sands4ced1f82008-01-13 08:02:44 +00003717 // Add any parameter attributes.
Devang Patelf2a4a922008-09-26 22:53:05 +00003718 if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
Devang Pateld222f862008-09-25 21:00:45 +00003719 attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
Duncan Sands4ced1f82008-01-13 08:02:44 +00003720 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003721 }
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00003722 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003723
Devang Patelf2a4a922008-09-26 22:53:05 +00003724 if (Attributes FnAttrs = CallerPAL.getFnAttributes())
3725 attrVec.push_back(AttributeWithIndex::get(~0, FnAttrs));
3726
Devang Patele9d08b82009-10-14 17:29:00 +00003727 if (NewRetTy->isVoidTy())
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003728 Caller->setName(""); // Void type should not have a name.
3729
Eric Christopher3e7381f2009-07-25 02:45:27 +00003730 const AttrListPtr &NewCallerPAL = AttrListPtr::get(attrVec.begin(),
3731 attrVec.end());
Duncan Sandsc849e662008-01-06 18:27:01 +00003732
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003733 Instruction *NC;
3734 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Gabor Greifd6da1d02008-04-06 20:25:17 +00003735 NC = InvokeInst::Create(Callee, II->getNormalDest(), II->getUnwindDest(),
Gabor Greifb91ea9d2008-05-15 10:04:30 +00003736 Args.begin(), Args.end(),
3737 Caller->getName(), Caller);
Reid Spencer6b0b09a2007-07-30 19:53:57 +00003738 cast<InvokeInst>(NC)->setCallingConv(II->getCallingConv());
Devang Pateld222f862008-09-25 21:00:45 +00003739 cast<InvokeInst>(NC)->setAttributes(NewCallerPAL);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003740 } else {
Gabor Greifd6da1d02008-04-06 20:25:17 +00003741 NC = CallInst::Create(Callee, Args.begin(), Args.end(),
3742 Caller->getName(), Caller);
Duncan Sandsf5588dc2007-11-27 13:23:08 +00003743 CallInst *CI = cast<CallInst>(Caller);
3744 if (CI->isTailCall())
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003745 cast<CallInst>(NC)->setTailCall();
Duncan Sandsf5588dc2007-11-27 13:23:08 +00003746 cast<CallInst>(NC)->setCallingConv(CI->getCallingConv());
Devang Pateld222f862008-09-25 21:00:45 +00003747 cast<CallInst>(NC)->setAttributes(NewCallerPAL);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003748 }
3749
3750 // Insert a cast of the return type as necessary.
3751 Value *NV = NC;
Duncan Sands5c489582008-01-06 10:12:28 +00003752 if (OldRetTy != NV->getType() && !Caller->use_empty()) {
Devang Patele9d08b82009-10-14 17:29:00 +00003753 if (!NV->getType()->isVoidTy()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003754 Instruction::CastOps opcode = CastInst::getCastOpcode(NC, false,
Duncan Sands5c489582008-01-06 10:12:28 +00003755 OldRetTy, false);
Gabor Greifa645dd32008-05-16 19:29:10 +00003756 NV = NC = CastInst::Create(opcode, NC, OldRetTy, "tmp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003757
3758 // If this is an invoke instruction, we should insert it after the first
3759 // non-phi, instruction in the normal successor block.
3760 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Dan Gohman514277c2008-05-23 21:05:58 +00003761 BasicBlock::iterator I = II->getNormalDest()->getFirstNonPHI();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003762 InsertNewInstBefore(NC, *I);
3763 } else {
3764 // Otherwise, it's a call, just insert cast right after the call instr
3765 InsertNewInstBefore(NC, *Caller);
3766 }
Chris Lattner4796b622009-08-30 06:22:51 +00003767 Worklist.AddUsersToWorkList(*Caller);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003768 } else {
Owen Andersonb99ecca2009-07-30 23:03:37 +00003769 NV = UndefValue::get(Caller->getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003770 }
3771 }
3772
Devang Pateledad36f2009-10-13 21:41:20 +00003773
Chris Lattner26b7f942009-08-31 05:17:58 +00003774 if (!Caller->use_empty())
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003775 Caller->replaceAllUsesWith(NV);
Chris Lattner26b7f942009-08-31 05:17:58 +00003776
3777 EraseInstFromFunction(*Caller);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003778 return true;
3779}
3780
Duncan Sands74833f22007-09-17 10:26:40 +00003781// transformCallThroughTrampoline - Turn a call to a function created by the
3782// init_trampoline intrinsic into a direct call to the underlying function.
3783//
3784Instruction *InstCombiner::transformCallThroughTrampoline(CallSite CS) {
3785 Value *Callee = CS.getCalledValue();
3786 const PointerType *PTy = cast<PointerType>(Callee->getType());
3787 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
Devang Pateld222f862008-09-25 21:00:45 +00003788 const AttrListPtr &Attrs = CS.getAttributes();
Duncan Sands48b81112008-01-14 19:52:09 +00003789
3790 // If the call already has the 'nest' attribute somewhere then give up -
3791 // otherwise 'nest' would occur twice after splicing in the chain.
Devang Pateld222f862008-09-25 21:00:45 +00003792 if (Attrs.hasAttrSomewhere(Attribute::Nest))
Duncan Sands48b81112008-01-14 19:52:09 +00003793 return 0;
Duncan Sands74833f22007-09-17 10:26:40 +00003794
3795 IntrinsicInst *Tramp =
3796 cast<IntrinsicInst>(cast<BitCastInst>(Callee)->getOperand(0));
3797
Anton Korobeynikov48fc88f2008-05-07 22:54:15 +00003798 Function *NestF = cast<Function>(Tramp->getOperand(2)->stripPointerCasts());
Duncan Sands74833f22007-09-17 10:26:40 +00003799 const PointerType *NestFPTy = cast<PointerType>(NestF->getType());
3800 const FunctionType *NestFTy = cast<FunctionType>(NestFPTy->getElementType());
3801
Devang Pateld222f862008-09-25 21:00:45 +00003802 const AttrListPtr &NestAttrs = NestF->getAttributes();
Chris Lattner1c8733e2008-03-12 17:45:29 +00003803 if (!NestAttrs.isEmpty()) {
Duncan Sands74833f22007-09-17 10:26:40 +00003804 unsigned NestIdx = 1;
3805 const Type *NestTy = 0;
Devang Pateld222f862008-09-25 21:00:45 +00003806 Attributes NestAttr = Attribute::None;
Duncan Sands74833f22007-09-17 10:26:40 +00003807
3808 // Look for a parameter marked with the 'nest' attribute.
3809 for (FunctionType::param_iterator I = NestFTy->param_begin(),
3810 E = NestFTy->param_end(); I != E; ++NestIdx, ++I)
Devang Pateld222f862008-09-25 21:00:45 +00003811 if (NestAttrs.paramHasAttr(NestIdx, Attribute::Nest)) {
Duncan Sands74833f22007-09-17 10:26:40 +00003812 // Record the parameter type and any other attributes.
3813 NestTy = *I;
Devang Patelf2a4a922008-09-26 22:53:05 +00003814 NestAttr = NestAttrs.getParamAttributes(NestIdx);
Duncan Sands74833f22007-09-17 10:26:40 +00003815 break;
3816 }
3817
3818 if (NestTy) {
3819 Instruction *Caller = CS.getInstruction();
3820 std::vector<Value*> NewArgs;
3821 NewArgs.reserve(unsigned(CS.arg_end()-CS.arg_begin())+1);
3822
Devang Pateld222f862008-09-25 21:00:45 +00003823 SmallVector<AttributeWithIndex, 8> NewAttrs;
Chris Lattner1c8733e2008-03-12 17:45:29 +00003824 NewAttrs.reserve(Attrs.getNumSlots() + 1);
Duncan Sands48b81112008-01-14 19:52:09 +00003825
Duncan Sands74833f22007-09-17 10:26:40 +00003826 // Insert the nest argument into the call argument list, which may
Duncan Sands48b81112008-01-14 19:52:09 +00003827 // mean appending it. Likewise for attributes.
3828
Devang Patelf2a4a922008-09-26 22:53:05 +00003829 // Add any result attributes.
3830 if (Attributes Attr = Attrs.getRetAttributes())
Devang Pateld222f862008-09-25 21:00:45 +00003831 NewAttrs.push_back(AttributeWithIndex::get(0, Attr));
Duncan Sands48b81112008-01-14 19:52:09 +00003832
Duncan Sands74833f22007-09-17 10:26:40 +00003833 {
3834 unsigned Idx = 1;
3835 CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
3836 do {
3837 if (Idx == NestIdx) {
Duncan Sands48b81112008-01-14 19:52:09 +00003838 // Add the chain argument and attributes.
Duncan Sands74833f22007-09-17 10:26:40 +00003839 Value *NestVal = Tramp->getOperand(3);
3840 if (NestVal->getType() != NestTy)
3841 NestVal = new BitCastInst(NestVal, NestTy, "nest", Caller);
3842 NewArgs.push_back(NestVal);
Devang Pateld222f862008-09-25 21:00:45 +00003843 NewAttrs.push_back(AttributeWithIndex::get(NestIdx, NestAttr));
Duncan Sands74833f22007-09-17 10:26:40 +00003844 }
3845
3846 if (I == E)
3847 break;
3848
Duncan Sands48b81112008-01-14 19:52:09 +00003849 // Add the original argument and attributes.
Duncan Sands74833f22007-09-17 10:26:40 +00003850 NewArgs.push_back(*I);
Devang Patelf2a4a922008-09-26 22:53:05 +00003851 if (Attributes Attr = Attrs.getParamAttributes(Idx))
Duncan Sands48b81112008-01-14 19:52:09 +00003852 NewAttrs.push_back
Devang Pateld222f862008-09-25 21:00:45 +00003853 (AttributeWithIndex::get(Idx + (Idx >= NestIdx), Attr));
Duncan Sands74833f22007-09-17 10:26:40 +00003854
3855 ++Idx, ++I;
3856 } while (1);
3857 }
3858
Devang Patelf2a4a922008-09-26 22:53:05 +00003859 // Add any function attributes.
3860 if (Attributes Attr = Attrs.getFnAttributes())
3861 NewAttrs.push_back(AttributeWithIndex::get(~0, Attr));
3862
Duncan Sands74833f22007-09-17 10:26:40 +00003863 // The trampoline may have been bitcast to a bogus type (FTy).
3864 // Handle this by synthesizing a new function type, equal to FTy
Duncan Sands48b81112008-01-14 19:52:09 +00003865 // with the chain parameter inserted.
Duncan Sands74833f22007-09-17 10:26:40 +00003866
Duncan Sands74833f22007-09-17 10:26:40 +00003867 std::vector<const Type*> NewTypes;
Duncan Sands74833f22007-09-17 10:26:40 +00003868 NewTypes.reserve(FTy->getNumParams()+1);
3869
Duncan Sands74833f22007-09-17 10:26:40 +00003870 // Insert the chain's type into the list of parameter types, which may
Duncan Sands48b81112008-01-14 19:52:09 +00003871 // mean appending it.
Duncan Sands74833f22007-09-17 10:26:40 +00003872 {
3873 unsigned Idx = 1;
3874 FunctionType::param_iterator I = FTy->param_begin(),
3875 E = FTy->param_end();
3876
3877 do {
Duncan Sands48b81112008-01-14 19:52:09 +00003878 if (Idx == NestIdx)
3879 // Add the chain's type.
Duncan Sands74833f22007-09-17 10:26:40 +00003880 NewTypes.push_back(NestTy);
Duncan Sands74833f22007-09-17 10:26:40 +00003881
3882 if (I == E)
3883 break;
3884
Duncan Sands48b81112008-01-14 19:52:09 +00003885 // Add the original type.
Duncan Sands74833f22007-09-17 10:26:40 +00003886 NewTypes.push_back(*I);
Duncan Sands74833f22007-09-17 10:26:40 +00003887
3888 ++Idx, ++I;
3889 } while (1);
3890 }
3891
3892 // Replace the trampoline call with a direct call. Let the generic
3893 // code sort out any function type mismatches.
Owen Anderson6b6e2d92009-07-29 22:17:13 +00003894 FunctionType *NewFTy = FunctionType::get(FTy->getReturnType(), NewTypes,
Owen Anderson24be4c12009-07-03 00:17:18 +00003895 FTy->isVarArg());
3896 Constant *NewCallee =
Owen Anderson6b6e2d92009-07-29 22:17:13 +00003897 NestF->getType() == PointerType::getUnqual(NewFTy) ?
Owen Anderson02b48c32009-07-29 18:55:55 +00003898 NestF : ConstantExpr::getBitCast(NestF,
Owen Anderson6b6e2d92009-07-29 22:17:13 +00003899 PointerType::getUnqual(NewFTy));
Eric Christopher3e7381f2009-07-25 02:45:27 +00003900 const AttrListPtr &NewPAL = AttrListPtr::get(NewAttrs.begin(),
3901 NewAttrs.end());
Duncan Sands74833f22007-09-17 10:26:40 +00003902
3903 Instruction *NewCaller;
3904 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Gabor Greifd6da1d02008-04-06 20:25:17 +00003905 NewCaller = InvokeInst::Create(NewCallee,
3906 II->getNormalDest(), II->getUnwindDest(),
3907 NewArgs.begin(), NewArgs.end(),
3908 Caller->getName(), Caller);
Duncan Sands74833f22007-09-17 10:26:40 +00003909 cast<InvokeInst>(NewCaller)->setCallingConv(II->getCallingConv());
Devang Pateld222f862008-09-25 21:00:45 +00003910 cast<InvokeInst>(NewCaller)->setAttributes(NewPAL);
Duncan Sands74833f22007-09-17 10:26:40 +00003911 } else {
Gabor Greifd6da1d02008-04-06 20:25:17 +00003912 NewCaller = CallInst::Create(NewCallee, NewArgs.begin(), NewArgs.end(),
3913 Caller->getName(), Caller);
Duncan Sands74833f22007-09-17 10:26:40 +00003914 if (cast<CallInst>(Caller)->isTailCall())
3915 cast<CallInst>(NewCaller)->setTailCall();
3916 cast<CallInst>(NewCaller)->
3917 setCallingConv(cast<CallInst>(Caller)->getCallingConv());
Devang Pateld222f862008-09-25 21:00:45 +00003918 cast<CallInst>(NewCaller)->setAttributes(NewPAL);
Duncan Sands74833f22007-09-17 10:26:40 +00003919 }
Devang Patele9d08b82009-10-14 17:29:00 +00003920 if (!Caller->getType()->isVoidTy())
Duncan Sands74833f22007-09-17 10:26:40 +00003921 Caller->replaceAllUsesWith(NewCaller);
3922 Caller->eraseFromParent();
Chris Lattner3183fb62009-08-30 06:13:40 +00003923 Worklist.Remove(Caller);
Duncan Sands74833f22007-09-17 10:26:40 +00003924 return 0;
3925 }
3926 }
3927
3928 // Replace the trampoline call with a direct call. Since there is no 'nest'
3929 // parameter, there is no need to adjust the argument list. Let the generic
3930 // code sort out any function type mismatches.
3931 Constant *NewCallee =
Owen Anderson24be4c12009-07-03 00:17:18 +00003932 NestF->getType() == PTy ? NestF :
Owen Anderson02b48c32009-07-29 18:55:55 +00003933 ConstantExpr::getBitCast(NestF, PTy);
Duncan Sands74833f22007-09-17 10:26:40 +00003934 CS.setCalledFunction(NewCallee);
3935 return CS.getInstruction();
3936}
3937
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003938
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003939
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003940Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
Chris Lattner5594a482009-11-27 00:29:05 +00003941 SmallVector<Value*, 8> Ops(GEP.op_begin(), GEP.op_end());
3942
3943 if (Value *V = SimplifyGEPInst(&Ops[0], Ops.size(), TD))
3944 return ReplaceInstUsesWith(GEP, V);
3945
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003946 Value *PtrOp = GEP.getOperand(0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003947
3948 if (isa<UndefValue>(GEP.getOperand(0)))
Owen Andersonb99ecca2009-07-30 23:03:37 +00003949 return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003950
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003951 // Eliminate unneeded casts for indices.
Chris Lattnerc0f553e2009-08-30 04:49:01 +00003952 if (TD) {
3953 bool MadeChange = false;
3954 unsigned PtrSize = TD->getPointerSizeInBits();
3955
3956 gep_type_iterator GTI = gep_type_begin(GEP);
3957 for (User::op_iterator I = GEP.op_begin() + 1, E = GEP.op_end();
3958 I != E; ++I, ++GTI) {
3959 if (!isa<SequentialType>(*GTI)) continue;
3960
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003961 // If we are using a wider index than needed for this platform, shrink it
Chris Lattnerc0f553e2009-08-30 04:49:01 +00003962 // to what we need. If narrower, sign-extend it to what we need. This
3963 // explicit cast can make subsequent optimizations more obvious.
3964 unsigned OpBits = cast<IntegerType>((*I)->getType())->getBitWidth();
Chris Lattnerc0f553e2009-08-30 04:49:01 +00003965 if (OpBits == PtrSize)
3966 continue;
3967
Chris Lattnerd6164c22009-08-30 20:01:10 +00003968 *I = Builder->CreateIntCast(*I, TD->getIntPtrType(GEP.getContext()),true);
Chris Lattnerc0f553e2009-08-30 04:49:01 +00003969 MadeChange = true;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003970 }
Chris Lattnerc0f553e2009-08-30 04:49:01 +00003971 if (MadeChange) return &GEP;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003972 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003973
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003974 // Combine Indices - If the source pointer to this getelementptr instruction
3975 // is a getelementptr instruction, combine the indices of the two
3976 // getelementptr instructions into a single instruction.
3977 //
Dan Gohman17f46f72009-07-28 01:40:03 +00003978 if (GEPOperator *Src = dyn_cast<GEPOperator>(PtrOp)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003979 // Note that if our source is a gep chain itself that we wait for that
3980 // chain to be resolved before we perform this transformation. This
3981 // avoids us creating a TON of code in some cases.
3982 //
Chris Lattnerc2c8a0a2009-08-30 05:08:50 +00003983 if (GetElementPtrInst *SrcGEP =
3984 dyn_cast<GetElementPtrInst>(Src->getOperand(0)))
3985 if (SrcGEP->getNumOperands() == 2)
3986 return 0; // Wait until our source is folded to completion.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003987
3988 SmallVector<Value*, 8> Indices;
3989
3990 // Find out whether the last index in the source GEP is a sequential idx.
3991 bool EndsWithSequential = false;
Chris Lattner1c641fc2009-08-30 05:30:55 +00003992 for (gep_type_iterator I = gep_type_begin(*Src), E = gep_type_end(*Src);
3993 I != E; ++I)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003994 EndsWithSequential = !isa<StructType>(*I);
3995
3996 // Can we combine the two pointer arithmetics offsets?
3997 if (EndsWithSequential) {
3998 // Replace: gep (gep %P, long B), long A, ...
3999 // With: T = long A+B; gep %P, T, ...
4000 //
Chris Lattnerc2c8a0a2009-08-30 05:08:50 +00004001 Value *Sum;
4002 Value *SO1 = Src->getOperand(Src->getNumOperands()-1);
4003 Value *GO1 = GEP.getOperand(1);
Owen Andersonaac28372009-07-31 20:28:14 +00004004 if (SO1 == Constant::getNullValue(SO1->getType())) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004005 Sum = GO1;
Owen Andersonaac28372009-07-31 20:28:14 +00004006 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004007 Sum = SO1;
4008 } else {
Chris Lattner1c641fc2009-08-30 05:30:55 +00004009 // If they aren't the same type, then the input hasn't been processed
4010 // by the loop above yet (which canonicalizes sequential index types to
4011 // intptr_t). Just avoid transforming this until the input has been
4012 // normalized.
4013 if (SO1->getType() != GO1->getType())
4014 return 0;
Chris Lattnerad7516a2009-08-30 18:50:58 +00004015 Sum = Builder->CreateAdd(SO1, GO1, PtrOp->getName()+".sum");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004016 }
4017
Chris Lattner1c641fc2009-08-30 05:30:55 +00004018 // Update the GEP in place if possible.
Chris Lattnerc2c8a0a2009-08-30 05:08:50 +00004019 if (Src->getNumOperands() == 2) {
4020 GEP.setOperand(0, Src->getOperand(0));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004021 GEP.setOperand(1, Sum);
4022 return &GEP;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004023 }
Chris Lattner1c641fc2009-08-30 05:30:55 +00004024 Indices.append(Src->op_begin()+1, Src->op_end()-1);
Chris Lattnerc0f553e2009-08-30 04:49:01 +00004025 Indices.push_back(Sum);
Chris Lattner1c641fc2009-08-30 05:30:55 +00004026 Indices.append(GEP.op_begin()+2, GEP.op_end());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004027 } else if (isa<Constant>(*GEP.idx_begin()) &&
4028 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
Chris Lattnerc2c8a0a2009-08-30 05:08:50 +00004029 Src->getNumOperands() != 1) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004030 // Otherwise we can do the fold if the first index of the GEP is a zero
Chris Lattner1c641fc2009-08-30 05:30:55 +00004031 Indices.append(Src->op_begin()+1, Src->op_end());
4032 Indices.append(GEP.idx_begin()+1, GEP.idx_end());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004033 }
4034
Dan Gohmanf3a08b82009-09-07 23:54:19 +00004035 if (!Indices.empty())
4036 return (cast<GEPOperator>(&GEP)->isInBounds() &&
4037 Src->isInBounds()) ?
4038 GetElementPtrInst::CreateInBounds(Src->getOperand(0), Indices.begin(),
4039 Indices.end(), GEP.getName()) :
Chris Lattnerc2c8a0a2009-08-30 05:08:50 +00004040 GetElementPtrInst::Create(Src->getOperand(0), Indices.begin(),
Chris Lattnerc0f553e2009-08-30 04:49:01 +00004041 Indices.end(), GEP.getName());
Chris Lattner95ba1ec2009-08-30 05:00:50 +00004042 }
4043
Chris Lattnerc2c8a0a2009-08-30 05:08:50 +00004044 // Handle gep(bitcast x) and gep(gep x, 0, 0, 0).
4045 if (Value *X = getBitCastOperand(PtrOp)) {
Chris Lattner95ba1ec2009-08-30 05:00:50 +00004046 assert(isa<PointerType>(X->getType()) && "Must be cast from pointer");
Chris Lattnerf3a23592009-08-30 20:36:46 +00004047
Chris Lattner83288fa2009-08-30 20:38:21 +00004048 // If the input bitcast is actually "bitcast(bitcast(x))", then we don't
4049 // want to change the gep until the bitcasts are eliminated.
4050 if (getBitCastOperand(X)) {
4051 Worklist.AddValue(PtrOp);
4052 return 0;
4053 }
4054
Chris Lattner5594a482009-11-27 00:29:05 +00004055 bool HasZeroPointerIndex = false;
4056 if (ConstantInt *C = dyn_cast<ConstantInt>(GEP.getOperand(1)))
4057 HasZeroPointerIndex = C->isZero();
4058
Chris Lattnerf3a23592009-08-30 20:36:46 +00004059 // Transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ...
4060 // into : GEP [10 x i8]* X, i32 0, ...
4061 //
4062 // Likewise, transform: GEP (bitcast i8* X to [0 x i8]*), i32 0, ...
4063 // into : GEP i8* X, ...
4064 //
4065 // This occurs when the program declares an array extern like "int X[];"
Chris Lattner95ba1ec2009-08-30 05:00:50 +00004066 if (HasZeroPointerIndex) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004067 const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
4068 const PointerType *XTy = cast<PointerType>(X->getType());
Duncan Sandscf866e62009-03-02 09:18:21 +00004069 if (const ArrayType *CATy =
4070 dyn_cast<ArrayType>(CPTy->getElementType())) {
4071 // GEP (bitcast i8* X to [0 x i8]*), i32 0, ... ?
4072 if (CATy->getElementType() == XTy->getElementType()) {
4073 // -> GEP i8* X, ...
4074 SmallVector<Value*, 8> Indices(GEP.idx_begin()+1, GEP.idx_end());
Dan Gohmanf3a08b82009-09-07 23:54:19 +00004075 return cast<GEPOperator>(&GEP)->isInBounds() ?
4076 GetElementPtrInst::CreateInBounds(X, Indices.begin(), Indices.end(),
4077 GEP.getName()) :
Dan Gohman17f46f72009-07-28 01:40:03 +00004078 GetElementPtrInst::Create(X, Indices.begin(), Indices.end(),
4079 GEP.getName());
Chris Lattnerf3a23592009-08-30 20:36:46 +00004080 }
4081
4082 if (const ArrayType *XATy = dyn_cast<ArrayType>(XTy->getElementType())){
Duncan Sandscf866e62009-03-02 09:18:21 +00004083 // GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ... ?
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004084 if (CATy->getElementType() == XATy->getElementType()) {
Duncan Sandscf866e62009-03-02 09:18:21 +00004085 // -> GEP [10 x i8]* X, i32 0, ...
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004086 // At this point, we know that the cast source type is a pointer
4087 // to an array of the same type as the destination pointer
4088 // array. Because the array type is never stepped over (there
4089 // is a leading zero) we can fold the cast into this GEP.
4090 GEP.setOperand(0, X);
4091 return &GEP;
4092 }
Duncan Sandscf866e62009-03-02 09:18:21 +00004093 }
4094 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004095 } else if (GEP.getNumOperands() == 2) {
4096 // Transform things like:
Wojciech Matyjewicz5b5ab532007-12-12 15:21:32 +00004097 // %t = getelementptr i32* bitcast ([2 x i32]* %str to i32*), i32 %V
4098 // into: %t1 = getelementptr [2 x i32]* %str, i32 0, i32 %V; bitcast
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004099 const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
4100 const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
Dan Gohmana80e2712009-07-21 23:21:54 +00004101 if (TD && isa<ArrayType>(SrcElTy) &&
Duncan Sandsec4f97d2009-05-09 07:06:46 +00004102 TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
4103 TD->getTypeAllocSize(ResElTy)) {
David Greene393be882007-09-04 15:46:09 +00004104 Value *Idx[2];
Chris Lattner03a27b42010-01-04 07:02:48 +00004105 Idx[0] = Constant::getNullValue(Type::getInt32Ty(GEP.getContext()));
David Greene393be882007-09-04 15:46:09 +00004106 Idx[1] = GEP.getOperand(1);
Dan Gohmanf3a08b82009-09-07 23:54:19 +00004107 Value *NewGEP = cast<GEPOperator>(&GEP)->isInBounds() ?
4108 Builder->CreateInBoundsGEP(X, Idx, Idx + 2, GEP.getName()) :
Chris Lattnerad7516a2009-08-30 18:50:58 +00004109 Builder->CreateGEP(X, Idx, Idx + 2, GEP.getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004110 // V and GEP are both pointer types --> BitCast
Chris Lattnerad7516a2009-08-30 18:50:58 +00004111 return new BitCastInst(NewGEP, GEP.getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004112 }
4113
4114 // Transform things like:
Wojciech Matyjewicz5b5ab532007-12-12 15:21:32 +00004115 // getelementptr i8* bitcast ([100 x double]* X to i8*), i32 %tmp
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004116 // (where tmp = 8*tmp2) into:
Wojciech Matyjewicz5b5ab532007-12-12 15:21:32 +00004117 // getelementptr [100 x double]* %arr, i32 0, i32 %tmp2; bitcast
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004118
Chris Lattner03a27b42010-01-04 07:02:48 +00004119 if (TD && isa<ArrayType>(SrcElTy) &&
4120 ResElTy == Type::getInt8Ty(GEP.getContext())) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004121 uint64_t ArrayEltSize =
Duncan Sandsec4f97d2009-05-09 07:06:46 +00004122 TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004123
4124 // Check to see if "tmp" is a scale by a multiple of ArrayEltSize. We
4125 // allow either a mul, shift, or constant here.
4126 Value *NewIdx = 0;
4127 ConstantInt *Scale = 0;
4128 if (ArrayEltSize == 1) {
4129 NewIdx = GEP.getOperand(1);
Chris Lattner1c641fc2009-08-30 05:30:55 +00004130 Scale = ConstantInt::get(cast<IntegerType>(NewIdx->getType()), 1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004131 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
Owen Andersoneacb44d2009-07-24 23:12:02 +00004132 NewIdx = ConstantInt::get(CI->getType(), 1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004133 Scale = CI;
4134 } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
4135 if (Inst->getOpcode() == Instruction::Shl &&
4136 isa<ConstantInt>(Inst->getOperand(1))) {
4137 ConstantInt *ShAmt = cast<ConstantInt>(Inst->getOperand(1));
4138 uint32_t ShAmtVal = ShAmt->getLimitedValue(64);
Owen Andersoneacb44d2009-07-24 23:12:02 +00004139 Scale = ConstantInt::get(cast<IntegerType>(Inst->getType()),
Dan Gohman8fd520a2009-06-15 22:12:54 +00004140 1ULL << ShAmtVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004141 NewIdx = Inst->getOperand(0);
4142 } else if (Inst->getOpcode() == Instruction::Mul &&
4143 isa<ConstantInt>(Inst->getOperand(1))) {
4144 Scale = cast<ConstantInt>(Inst->getOperand(1));
4145 NewIdx = Inst->getOperand(0);
4146 }
4147 }
Wojciech Matyjewicz5b5ab532007-12-12 15:21:32 +00004148
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004149 // If the index will be to exactly the right offset with the scale taken
Wojciech Matyjewicz5b5ab532007-12-12 15:21:32 +00004150 // out, perform the transformation. Note, we don't know whether Scale is
4151 // signed or not. We'll use unsigned version of division/modulo
4152 // operation after making sure Scale doesn't have the sign bit set.
Chris Lattner02962712009-02-25 18:20:01 +00004153 if (ArrayEltSize && Scale && Scale->getSExtValue() >= 0LL &&
Wojciech Matyjewicz5b5ab532007-12-12 15:21:32 +00004154 Scale->getZExtValue() % ArrayEltSize == 0) {
Owen Andersoneacb44d2009-07-24 23:12:02 +00004155 Scale = ConstantInt::get(Scale->getType(),
Wojciech Matyjewicz5b5ab532007-12-12 15:21:32 +00004156 Scale->getZExtValue() / ArrayEltSize);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004157 if (Scale->getZExtValue() != 1) {
Chris Lattnerbf09d632009-08-30 05:56:44 +00004158 Constant *C = ConstantExpr::getIntegerCast(Scale, NewIdx->getType(),
4159 false /*ZExt*/);
Chris Lattnerad7516a2009-08-30 18:50:58 +00004160 NewIdx = Builder->CreateMul(NewIdx, C, "idxscale");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004161 }
4162
4163 // Insert the new GEP instruction.
David Greene393be882007-09-04 15:46:09 +00004164 Value *Idx[2];
Chris Lattner03a27b42010-01-04 07:02:48 +00004165 Idx[0] = Constant::getNullValue(Type::getInt32Ty(GEP.getContext()));
David Greene393be882007-09-04 15:46:09 +00004166 Idx[1] = NewIdx;
Dan Gohmanf3a08b82009-09-07 23:54:19 +00004167 Value *NewGEP = cast<GEPOperator>(&GEP)->isInBounds() ?
4168 Builder->CreateInBoundsGEP(X, Idx, Idx + 2, GEP.getName()) :
4169 Builder->CreateGEP(X, Idx, Idx + 2, GEP.getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004170 // The NewGEP must be pointer typed, so must the old one -> BitCast
4171 return new BitCastInst(NewGEP, GEP.getType());
4172 }
4173 }
4174 }
4175 }
Chris Lattner111ea772009-01-09 04:53:57 +00004176
Chris Lattner94ccd5f2009-01-09 05:44:56 +00004177 /// See if we can simplify:
Chris Lattner5119c702009-08-30 05:55:36 +00004178 /// X = bitcast A* to B*
Chris Lattner94ccd5f2009-01-09 05:44:56 +00004179 /// Y = gep X, <...constant indices...>
4180 /// into a gep of the original struct. This is important for SROA and alias
4181 /// analysis of unions. If "A" is also a bitcast, wait for A/X to be merged.
Chris Lattner111ea772009-01-09 04:53:57 +00004182 if (BitCastInst *BCI = dyn_cast<BitCastInst>(PtrOp)) {
Dan Gohmana80e2712009-07-21 23:21:54 +00004183 if (TD &&
4184 !isa<BitCastInst>(BCI->getOperand(0)) && GEP.hasAllConstantIndices()) {
Chris Lattner94ccd5f2009-01-09 05:44:56 +00004185 // Determine how much the GEP moves the pointer. We are guaranteed to get
4186 // a constant back from EmitGEPOffset.
Chris Lattner63ac8422010-01-04 07:37:31 +00004187 ConstantInt *OffsetV = cast<ConstantInt>(EmitGEPOffset(&GEP));
Chris Lattner94ccd5f2009-01-09 05:44:56 +00004188 int64_t Offset = OffsetV->getSExtValue();
4189
4190 // If this GEP instruction doesn't move the pointer, just replace the GEP
4191 // with a bitcast of the real input to the dest type.
4192 if (Offset == 0) {
4193 // If the bitcast is of an allocation, and the allocation will be
4194 // converted to match the type of the cast, don't touch this.
Victor Hernandezb1687302009-10-23 21:09:37 +00004195 if (isa<AllocaInst>(BCI->getOperand(0)) ||
Victor Hernandez48c3c542009-09-18 22:35:49 +00004196 isMalloc(BCI->getOperand(0))) {
Chris Lattner94ccd5f2009-01-09 05:44:56 +00004197 // See if the bitcast simplifies, if so, don't nuke this GEP yet.
4198 if (Instruction *I = visitBitCast(*BCI)) {
4199 if (I != BCI) {
4200 I->takeName(BCI);
4201 BCI->getParent()->getInstList().insert(BCI, I);
4202 ReplaceInstUsesWith(*BCI, I);
4203 }
4204 return &GEP;
Chris Lattner111ea772009-01-09 04:53:57 +00004205 }
Chris Lattner111ea772009-01-09 04:53:57 +00004206 }
Chris Lattner94ccd5f2009-01-09 05:44:56 +00004207 return new BitCastInst(BCI->getOperand(0), GEP.getType());
Chris Lattner111ea772009-01-09 04:53:57 +00004208 }
Chris Lattner94ccd5f2009-01-09 05:44:56 +00004209
4210 // Otherwise, if the offset is non-zero, we need to find out if there is a
4211 // field at Offset in 'A's type. If so, we can pull the cast through the
4212 // GEP.
4213 SmallVector<Value*, 8> NewIndices;
4214 const Type *InTy =
4215 cast<PointerType>(BCI->getOperand(0)->getType())->getElementType();
Chris Lattner54826cd2010-01-04 07:53:58 +00004216 if (FindElementAtOffset(InTy, Offset, NewIndices)) {
Dan Gohmanf3a08b82009-09-07 23:54:19 +00004217 Value *NGEP = cast<GEPOperator>(&GEP)->isInBounds() ?
4218 Builder->CreateInBoundsGEP(BCI->getOperand(0), NewIndices.begin(),
4219 NewIndices.end()) :
4220 Builder->CreateGEP(BCI->getOperand(0), NewIndices.begin(),
4221 NewIndices.end());
Chris Lattnerad7516a2009-08-30 18:50:58 +00004222
4223 if (NGEP->getType() == GEP.getType())
4224 return ReplaceInstUsesWith(GEP, NGEP);
Chris Lattner94ccd5f2009-01-09 05:44:56 +00004225 NGEP->takeName(&GEP);
4226 return new BitCastInst(NGEP, GEP.getType());
4227 }
Chris Lattner111ea772009-01-09 04:53:57 +00004228 }
4229 }
4230
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004231 return 0;
4232}
4233
Victor Hernandez93946082009-10-24 04:23:03 +00004234Instruction *InstCombiner::visitFree(Instruction &FI) {
4235 Value *Op = FI.getOperand(1);
4236
4237 // free undef -> unreachable.
4238 if (isa<UndefValue>(Op)) {
4239 // Insert a new store to null because we cannot modify the CFG here.
Chris Lattner03a27b42010-01-04 07:02:48 +00004240 new StoreInst(ConstantInt::getTrue(FI.getContext()),
4241 UndefValue::get(Type::getInt1PtrTy(FI.getContext())), &FI);
Victor Hernandez93946082009-10-24 04:23:03 +00004242 return EraseInstFromFunction(FI);
4243 }
4244
4245 // If we have 'free null' delete the instruction. This can happen in stl code
4246 // when lots of inlining happens.
4247 if (isa<ConstantPointerNull>(Op))
4248 return EraseInstFromFunction(FI);
4249
Victor Hernandezf9a7a332009-10-26 23:43:48 +00004250 // If we have a malloc call whose only use is a free call, delete both.
Dan Gohman1674ea52009-10-27 00:11:02 +00004251 if (isMalloc(Op)) {
Victor Hernandez93946082009-10-24 04:23:03 +00004252 if (CallInst* CI = extractMallocCallFromBitCast(Op)) {
4253 if (Op->hasOneUse() && CI->hasOneUse()) {
4254 EraseInstFromFunction(FI);
4255 EraseInstFromFunction(*CI);
4256 return EraseInstFromFunction(*cast<Instruction>(Op));
4257 }
4258 } else {
4259 // Op is a call to malloc
4260 if (Op->hasOneUse()) {
4261 EraseInstFromFunction(FI);
4262 return EraseInstFromFunction(*cast<Instruction>(Op));
4263 }
4264 }
Dan Gohman1674ea52009-10-27 00:11:02 +00004265 }
Victor Hernandez93946082009-10-24 04:23:03 +00004266
4267 return 0;
4268}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004269
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004270
4271
4272Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
4273 // Change br (not X), label True, label False to: br X, label False, True
4274 Value *X = 0;
4275 BasicBlock *TrueDest;
4276 BasicBlock *FalseDest;
Dan Gohmancdff2122009-08-12 16:23:25 +00004277 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004278 !isa<Constant>(X)) {
4279 // Swap Destinations and condition...
4280 BI.setCondition(X);
4281 BI.setSuccessor(0, FalseDest);
4282 BI.setSuccessor(1, TrueDest);
4283 return &BI;
4284 }
4285
4286 // Cannonicalize fcmp_one -> fcmp_oeq
4287 FCmpInst::Predicate FPred; Value *Y;
4288 if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)),
Chris Lattner3183fb62009-08-30 06:13:40 +00004289 TrueDest, FalseDest)) &&
4290 BI.getCondition()->hasOneUse())
4291 if (FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
4292 FPred == FCmpInst::FCMP_OGE) {
4293 FCmpInst *Cond = cast<FCmpInst>(BI.getCondition());
4294 Cond->setPredicate(FCmpInst::getInversePredicate(FPred));
4295
4296 // Swap Destinations and condition.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004297 BI.setSuccessor(0, FalseDest);
4298 BI.setSuccessor(1, TrueDest);
Chris Lattner3183fb62009-08-30 06:13:40 +00004299 Worklist.Add(Cond);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004300 return &BI;
4301 }
4302
4303 // Cannonicalize icmp_ne -> icmp_eq
4304 ICmpInst::Predicate IPred;
4305 if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
Chris Lattner3183fb62009-08-30 06:13:40 +00004306 TrueDest, FalseDest)) &&
4307 BI.getCondition()->hasOneUse())
4308 if (IPred == ICmpInst::ICMP_NE || IPred == ICmpInst::ICMP_ULE ||
4309 IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
4310 IPred == ICmpInst::ICMP_SGE) {
4311 ICmpInst *Cond = cast<ICmpInst>(BI.getCondition());
4312 Cond->setPredicate(ICmpInst::getInversePredicate(IPred));
4313 // Swap Destinations and condition.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004314 BI.setSuccessor(0, FalseDest);
4315 BI.setSuccessor(1, TrueDest);
Chris Lattner3183fb62009-08-30 06:13:40 +00004316 Worklist.Add(Cond);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004317 return &BI;
4318 }
4319
4320 return 0;
4321}
4322
4323Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
4324 Value *Cond = SI.getCondition();
4325 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
4326 if (I->getOpcode() == Instruction::Add)
4327 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
4328 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
4329 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
Owen Anderson24be4c12009-07-03 00:17:18 +00004330 SI.setOperand(i,
Owen Anderson02b48c32009-07-29 18:55:55 +00004331 ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004332 AddRHS));
4333 SI.setOperand(0, I->getOperand(0));
Chris Lattner3183fb62009-08-30 06:13:40 +00004334 Worklist.Add(I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004335 return &SI;
4336 }
4337 }
4338 return 0;
4339}
4340
Matthijs Kooijmanda9ef702008-06-11 14:05:05 +00004341Instruction *InstCombiner::visitExtractValueInst(ExtractValueInst &EV) {
Matthijs Kooijman45e8eb42008-07-16 12:55:45 +00004342 Value *Agg = EV.getAggregateOperand();
Matthijs Kooijmanda9ef702008-06-11 14:05:05 +00004343
Matthijs Kooijman45e8eb42008-07-16 12:55:45 +00004344 if (!EV.hasIndices())
4345 return ReplaceInstUsesWith(EV, Agg);
4346
4347 if (Constant *C = dyn_cast<Constant>(Agg)) {
4348 if (isa<UndefValue>(C))
Owen Andersonb99ecca2009-07-30 23:03:37 +00004349 return ReplaceInstUsesWith(EV, UndefValue::get(EV.getType()));
Matthijs Kooijman45e8eb42008-07-16 12:55:45 +00004350
4351 if (isa<ConstantAggregateZero>(C))
Owen Andersonaac28372009-07-31 20:28:14 +00004352 return ReplaceInstUsesWith(EV, Constant::getNullValue(EV.getType()));
Matthijs Kooijman45e8eb42008-07-16 12:55:45 +00004353
4354 if (isa<ConstantArray>(C) || isa<ConstantStruct>(C)) {
4355 // Extract the element indexed by the first index out of the constant
4356 Value *V = C->getOperand(*EV.idx_begin());
4357 if (EV.getNumIndices() > 1)
4358 // Extract the remaining indices out of the constant indexed by the
4359 // first index
4360 return ExtractValueInst::Create(V, EV.idx_begin() + 1, EV.idx_end());
4361 else
4362 return ReplaceInstUsesWith(EV, V);
4363 }
4364 return 0; // Can't handle other constants
4365 }
4366 if (InsertValueInst *IV = dyn_cast<InsertValueInst>(Agg)) {
4367 // We're extracting from an insertvalue instruction, compare the indices
4368 const unsigned *exti, *exte, *insi, *inse;
4369 for (exti = EV.idx_begin(), insi = IV->idx_begin(),
4370 exte = EV.idx_end(), inse = IV->idx_end();
4371 exti != exte && insi != inse;
4372 ++exti, ++insi) {
4373 if (*insi != *exti)
4374 // The insert and extract both reference distinctly different elements.
4375 // This means the extract is not influenced by the insert, and we can
4376 // replace the aggregate operand of the extract with the aggregate
4377 // operand of the insert. i.e., replace
4378 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
4379 // %E = extractvalue { i32, { i32 } } %I, 0
4380 // with
4381 // %E = extractvalue { i32, { i32 } } %A, 0
4382 return ExtractValueInst::Create(IV->getAggregateOperand(),
4383 EV.idx_begin(), EV.idx_end());
4384 }
4385 if (exti == exte && insi == inse)
4386 // Both iterators are at the end: Index lists are identical. Replace
4387 // %B = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
4388 // %C = extractvalue { i32, { i32 } } %B, 1, 0
4389 // with "i32 42"
4390 return ReplaceInstUsesWith(EV, IV->getInsertedValueOperand());
4391 if (exti == exte) {
4392 // The extract list is a prefix of the insert list. i.e. replace
4393 // %I = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
4394 // %E = extractvalue { i32, { i32 } } %I, 1
4395 // with
4396 // %X = extractvalue { i32, { i32 } } %A, 1
4397 // %E = insertvalue { i32 } %X, i32 42, 0
4398 // by switching the order of the insert and extract (though the
4399 // insertvalue should be left in, since it may have other uses).
Chris Lattnerad7516a2009-08-30 18:50:58 +00004400 Value *NewEV = Builder->CreateExtractValue(IV->getAggregateOperand(),
4401 EV.idx_begin(), EV.idx_end());
Matthijs Kooijman45e8eb42008-07-16 12:55:45 +00004402 return InsertValueInst::Create(NewEV, IV->getInsertedValueOperand(),
4403 insi, inse);
4404 }
4405 if (insi == inse)
4406 // The insert list is a prefix of the extract list
4407 // We can simply remove the common indices from the extract and make it
4408 // operate on the inserted value instead of the insertvalue result.
4409 // i.e., replace
4410 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
4411 // %E = extractvalue { i32, { i32 } } %I, 1, 0
4412 // with
4413 // %E extractvalue { i32 } { i32 42 }, 0
4414 return ExtractValueInst::Create(IV->getInsertedValueOperand(),
4415 exti, exte);
4416 }
Chris Lattner69a70752009-11-09 07:07:56 +00004417 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Agg)) {
4418 // We're extracting from an intrinsic, see if we're the only user, which
4419 // allows us to simplify multiple result intrinsics to simpler things that
4420 // just get one value..
4421 if (II->hasOneUse()) {
4422 // Check if we're grabbing the overflow bit or the result of a 'with
4423 // overflow' intrinsic. If it's the latter we can remove the intrinsic
4424 // and replace it with a traditional binary instruction.
4425 switch (II->getIntrinsicID()) {
4426 case Intrinsic::uadd_with_overflow:
4427 case Intrinsic::sadd_with_overflow:
4428 if (*EV.idx_begin() == 0) { // Normal result.
4429 Value *LHS = II->getOperand(1), *RHS = II->getOperand(2);
4430 II->replaceAllUsesWith(UndefValue::get(II->getType()));
4431 EraseInstFromFunction(*II);
4432 return BinaryOperator::CreateAdd(LHS, RHS);
4433 }
4434 break;
4435 case Intrinsic::usub_with_overflow:
4436 case Intrinsic::ssub_with_overflow:
4437 if (*EV.idx_begin() == 0) { // Normal result.
4438 Value *LHS = II->getOperand(1), *RHS = II->getOperand(2);
4439 II->replaceAllUsesWith(UndefValue::get(II->getType()));
4440 EraseInstFromFunction(*II);
4441 return BinaryOperator::CreateSub(LHS, RHS);
4442 }
4443 break;
4444 case Intrinsic::umul_with_overflow:
4445 case Intrinsic::smul_with_overflow:
4446 if (*EV.idx_begin() == 0) { // Normal result.
4447 Value *LHS = II->getOperand(1), *RHS = II->getOperand(2);
4448 II->replaceAllUsesWith(UndefValue::get(II->getType()));
4449 EraseInstFromFunction(*II);
4450 return BinaryOperator::CreateMul(LHS, RHS);
4451 }
4452 break;
4453 default:
4454 break;
4455 }
4456 }
4457 }
Matthijs Kooijman45e8eb42008-07-16 12:55:45 +00004458 // Can't simplify extracts from other values. Note that nested extracts are
4459 // already simplified implicitely by the above (extract ( extract (insert) )
4460 // will be translated into extract ( insert ( extract ) ) first and then just
4461 // the value inserted, if appropriate).
Matthijs Kooijmanda9ef702008-06-11 14:05:05 +00004462 return 0;
4463}
4464
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004465
4466
4467
4468/// TryToSinkInstruction - Try to move the specified instruction from its
4469/// current block into the beginning of DestBlock, which can only happen if it's
4470/// safe to move the instruction past all of the instructions between it and the
4471/// end of its block.
4472static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
4473 assert(I->hasOneUse() && "Invariants didn't hold!");
4474
4475 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
Duncan Sands2f500832009-05-06 06:49:50 +00004476 if (isa<PHINode>(I) || I->mayHaveSideEffects() || isa<TerminatorInst>(I))
Chris Lattnercb19a1c2008-05-09 15:07:33 +00004477 return false;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004478
4479 // Do not sink alloca instructions out of the entry block.
4480 if (isa<AllocaInst>(I) && I->getParent() ==
4481 &DestBlock->getParent()->getEntryBlock())
4482 return false;
4483
4484 // We can only sink load instructions if there is nothing between the load and
4485 // the end of block that could change the value.
Chris Lattner0db40a62008-05-08 17:37:37 +00004486 if (I->mayReadFromMemory()) {
4487 for (BasicBlock::iterator Scan = I, E = I->getParent()->end();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004488 Scan != E; ++Scan)
4489 if (Scan->mayWriteToMemory())
4490 return false;
4491 }
4492
Dan Gohman514277c2008-05-23 21:05:58 +00004493 BasicBlock::iterator InsertPos = DestBlock->getFirstNonPHI();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004494
4495 I->moveBefore(InsertPos);
4496 ++NumSunkInst;
4497 return true;
4498}
4499
4500
4501/// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
4502/// all reachable code to the worklist.
4503///
4504/// This has a couple of tricks to make the code faster and more powerful. In
4505/// particular, we constant fold and DCE instructions as we go, to avoid adding
4506/// them to the worklist (this significantly speeds up instcombine on code where
4507/// many instructions are dead or constant). Additionally, if we find a branch
4508/// whose condition is a known constant, we only visit the reachable successors.
4509///
Chris Lattnerc4269e52009-10-15 04:59:28 +00004510static bool AddReachableCodeToWorklist(BasicBlock *BB,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004511 SmallPtrSet<BasicBlock*, 64> &Visited,
4512 InstCombiner &IC,
4513 const TargetData *TD) {
Chris Lattnerc4269e52009-10-15 04:59:28 +00004514 bool MadeIRChange = false;
Chris Lattnera06291a2008-08-15 04:03:01 +00004515 SmallVector<BasicBlock*, 256> Worklist;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004516 Worklist.push_back(BB);
Chris Lattnerb5663c72009-10-12 03:58:40 +00004517
4518 std::vector<Instruction*> InstrsForInstCombineWorklist;
4519 InstrsForInstCombineWorklist.reserve(128);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004520
Chris Lattnerc4269e52009-10-15 04:59:28 +00004521 SmallPtrSet<ConstantExpr*, 64> FoldedConstants;
4522
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004523 while (!Worklist.empty()) {
4524 BB = Worklist.back();
4525 Worklist.pop_back();
4526
4527 // We have now visited this block! If we've already been here, ignore it.
4528 if (!Visited.insert(BB)) continue;
Devang Patel794140c2008-11-19 18:56:50 +00004529
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004530 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
4531 Instruction *Inst = BBI++;
4532
4533 // DCE instruction if trivially dead.
4534 if (isInstructionTriviallyDead(Inst)) {
4535 ++NumDeadInst;
Chris Lattner8a6411c2009-08-23 04:37:46 +00004536 DEBUG(errs() << "IC: DCE: " << *Inst << '\n');
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004537 Inst->eraseFromParent();
4538 continue;
4539 }
4540
4541 // ConstantProp instruction if trivially constant.
Chris Lattneree5839b2009-10-15 04:13:44 +00004542 if (!Inst->use_empty() && isa<Constant>(Inst->getOperand(0)))
Chris Lattner6070c012009-11-06 04:27:31 +00004543 if (Constant *C = ConstantFoldInstruction(Inst, TD)) {
Chris Lattneree5839b2009-10-15 04:13:44 +00004544 DEBUG(errs() << "IC: ConstFold to: " << *C << " from: "
4545 << *Inst << '\n');
4546 Inst->replaceAllUsesWith(C);
4547 ++NumConstProp;
4548 Inst->eraseFromParent();
4549 continue;
4550 }
Chris Lattnerc4269e52009-10-15 04:59:28 +00004551
4552
4553
4554 if (TD) {
4555 // See if we can constant fold its operands.
4556 for (User::op_iterator i = Inst->op_begin(), e = Inst->op_end();
4557 i != e; ++i) {
4558 ConstantExpr *CE = dyn_cast<ConstantExpr>(i);
4559 if (CE == 0) continue;
4560
4561 // If we already folded this constant, don't try again.
4562 if (!FoldedConstants.insert(CE))
4563 continue;
4564
Chris Lattner6070c012009-11-06 04:27:31 +00004565 Constant *NewC = ConstantFoldConstantExpression(CE, TD);
Chris Lattnerc4269e52009-10-15 04:59:28 +00004566 if (NewC && NewC != CE) {
4567 *i = NewC;
4568 MadeIRChange = true;
4569 }
4570 }
4571 }
4572
Devang Patel794140c2008-11-19 18:56:50 +00004573
Chris Lattnerb5663c72009-10-12 03:58:40 +00004574 InstrsForInstCombineWorklist.push_back(Inst);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004575 }
4576
4577 // Recursively visit successors. If this is a branch or switch on a
4578 // constant, only visit the reachable successor.
4579 TerminatorInst *TI = BB->getTerminator();
4580 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
4581 if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
4582 bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
Nick Lewyckyd551cf12008-03-09 08:50:23 +00004583 BasicBlock *ReachableBB = BI->getSuccessor(!CondVal);
Nick Lewyckyd8aa33a2008-04-25 16:53:59 +00004584 Worklist.push_back(ReachableBB);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004585 continue;
4586 }
4587 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
4588 if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
4589 // See if this is an explicit destination.
4590 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
4591 if (SI->getCaseValue(i) == Cond) {
Nick Lewyckyd551cf12008-03-09 08:50:23 +00004592 BasicBlock *ReachableBB = SI->getSuccessor(i);
Nick Lewyckyd8aa33a2008-04-25 16:53:59 +00004593 Worklist.push_back(ReachableBB);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004594 continue;
4595 }
4596
4597 // Otherwise it is the default destination.
4598 Worklist.push_back(SI->getSuccessor(0));
4599 continue;
4600 }
4601 }
4602
4603 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
4604 Worklist.push_back(TI->getSuccessor(i));
4605 }
Chris Lattnerb5663c72009-10-12 03:58:40 +00004606
4607 // Once we've found all of the instructions to add to instcombine's worklist,
4608 // add them in reverse order. This way instcombine will visit from the top
4609 // of the function down. This jives well with the way that it adds all uses
4610 // of instructions to the worklist after doing a transformation, thus avoiding
4611 // some N^2 behavior in pathological cases.
4612 IC.Worklist.AddInitialGroup(&InstrsForInstCombineWorklist[0],
4613 InstrsForInstCombineWorklist.size());
Chris Lattnerc4269e52009-10-15 04:59:28 +00004614
4615 return MadeIRChange;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004616}
4617
4618bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) {
Chris Lattner21d79e22009-08-31 06:57:37 +00004619 MadeIRChange = false;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004620
Daniel Dunbar005975c2009-07-25 00:23:56 +00004621 DEBUG(errs() << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
4622 << F.getNameStr() << "\n");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004623
4624 {
4625 // Do a depth-first traversal of the function, populate the worklist with
4626 // the reachable instructions. Ignore blocks that are not reachable. Keep
4627 // track of which blocks we visit.
4628 SmallPtrSet<BasicBlock*, 64> Visited;
Chris Lattnerc4269e52009-10-15 04:59:28 +00004629 MadeIRChange |= AddReachableCodeToWorklist(F.begin(), Visited, *this, TD);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004630
4631 // Do a quick scan over the function. If we find any blocks that are
4632 // unreachable, remove any instructions inside of them. This prevents
4633 // the instcombine code from having to deal with some bad special cases.
4634 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
4635 if (!Visited.count(BB)) {
4636 Instruction *Term = BB->getTerminator();
4637 while (Term != BB->begin()) { // Remove instrs bottom-up
4638 BasicBlock::iterator I = Term; --I;
4639
Chris Lattner8a6411c2009-08-23 04:37:46 +00004640 DEBUG(errs() << "IC: DCE: " << *I << '\n');
Dale Johannesendf356c62009-03-10 21:19:49 +00004641 // A debug intrinsic shouldn't force another iteration if we weren't
4642 // going to do one without it.
4643 if (!isa<DbgInfoIntrinsic>(I)) {
4644 ++NumDeadInst;
Chris Lattner21d79e22009-08-31 06:57:37 +00004645 MadeIRChange = true;
Dale Johannesendf356c62009-03-10 21:19:49 +00004646 }
Devang Patele3829c82009-10-13 22:56:32 +00004647
Devang Patele3829c82009-10-13 22:56:32 +00004648 // If I is not void type then replaceAllUsesWith undef.
4649 // This allows ValueHandlers and custom metadata to adjust itself.
Devang Patele9d08b82009-10-14 17:29:00 +00004650 if (!I->getType()->isVoidTy())
Devang Patele3829c82009-10-13 22:56:32 +00004651 I->replaceAllUsesWith(UndefValue::get(I->getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004652 I->eraseFromParent();
4653 }
4654 }
4655 }
4656
Chris Lattner5119c702009-08-30 05:55:36 +00004657 while (!Worklist.isEmpty()) {
4658 Instruction *I = Worklist.RemoveOne();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004659 if (I == 0) continue; // skip null values.
4660
4661 // Check to see if we can DCE the instruction.
4662 if (isInstructionTriviallyDead(I)) {
Chris Lattner8a6411c2009-08-23 04:37:46 +00004663 DEBUG(errs() << "IC: DCE: " << *I << '\n');
Chris Lattner3183fb62009-08-30 06:13:40 +00004664 EraseInstFromFunction(*I);
4665 ++NumDeadInst;
Chris Lattner21d79e22009-08-31 06:57:37 +00004666 MadeIRChange = true;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004667 continue;
4668 }
4669
4670 // Instruction isn't dead, see if we can constant propagate it.
Chris Lattneree5839b2009-10-15 04:13:44 +00004671 if (!I->use_empty() && isa<Constant>(I->getOperand(0)))
Chris Lattner6070c012009-11-06 04:27:31 +00004672 if (Constant *C = ConstantFoldInstruction(I, TD)) {
Chris Lattneree5839b2009-10-15 04:13:44 +00004673 DEBUG(errs() << "IC: ConstFold to: " << *C << " from: " << *I << '\n');
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004674
Chris Lattneree5839b2009-10-15 04:13:44 +00004675 // Add operands to the worklist.
4676 ReplaceInstUsesWith(*I, C);
4677 ++NumConstProp;
4678 EraseInstFromFunction(*I);
4679 MadeIRChange = true;
4680 continue;
4681 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004682
4683 // See if we can trivially sink this instruction to a successor basic block.
Dan Gohman29474e92008-07-23 00:34:11 +00004684 if (I->hasOneUse()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004685 BasicBlock *BB = I->getParent();
Chris Lattnerf27a0432009-10-14 15:21:58 +00004686 Instruction *UserInst = cast<Instruction>(I->use_back());
4687 BasicBlock *UserParent;
4688
4689 // Get the block the use occurs in.
4690 if (PHINode *PN = dyn_cast<PHINode>(UserInst))
4691 UserParent = PN->getIncomingBlock(I->use_begin().getUse());
4692 else
4693 UserParent = UserInst->getParent();
4694
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004695 if (UserParent != BB) {
4696 bool UserIsSuccessor = false;
4697 // See if the user is one of our successors.
4698 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
4699 if (*SI == UserParent) {
4700 UserIsSuccessor = true;
4701 break;
4702 }
4703
4704 // If the user is one of our immediate successors, and if that successor
4705 // only has us as a predecessors (we'd have to split the critical edge
4706 // otherwise), we can keep going.
Chris Lattnerf27a0432009-10-14 15:21:58 +00004707 if (UserIsSuccessor && UserParent->getSinglePredecessor())
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004708 // Okay, the CFG is simple enough, try to sink this instruction.
Chris Lattner21d79e22009-08-31 06:57:37 +00004709 MadeIRChange |= TryToSinkInstruction(I, UserParent);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004710 }
4711 }
4712
Chris Lattnerc7694852009-08-30 07:44:24 +00004713 // Now that we have an instruction, try combining it to simplify it.
4714 Builder->SetInsertPoint(I->getParent(), I);
4715
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004716#ifndef NDEBUG
4717 std::string OrigI;
4718#endif
Chris Lattner8a6411c2009-08-23 04:37:46 +00004719 DEBUG(raw_string_ostream SS(OrigI); I->print(SS); OrigI = SS.str(););
Jeffrey Yasskin17091f02009-10-08 00:12:24 +00004720 DEBUG(errs() << "IC: Visiting: " << OrigI << '\n');
4721
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004722 if (Instruction *Result = visit(*I)) {
4723 ++NumCombined;
4724 // Should we replace the old instruction with a new one?
4725 if (Result != I) {
Chris Lattner8a6411c2009-08-23 04:37:46 +00004726 DEBUG(errs() << "IC: Old = " << *I << '\n'
4727 << " New = " << *Result << '\n');
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004728
4729 // Everything uses the new instruction now.
4730 I->replaceAllUsesWith(Result);
4731
4732 // Push the new instruction and any users onto the worklist.
Chris Lattner3183fb62009-08-30 06:13:40 +00004733 Worklist.Add(Result);
Chris Lattner4796b622009-08-30 06:22:51 +00004734 Worklist.AddUsersToWorkList(*Result);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004735
4736 // Move the name to the new instruction first.
4737 Result->takeName(I);
4738
4739 // Insert the new instruction into the basic block...
4740 BasicBlock *InstParent = I->getParent();
4741 BasicBlock::iterator InsertPos = I;
4742
4743 if (!isa<PHINode>(Result)) // If combining a PHI, don't insert
4744 while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
4745 ++InsertPos;
4746
4747 InstParent->getInstList().insert(InsertPos, Result);
4748
Chris Lattner3183fb62009-08-30 06:13:40 +00004749 EraseInstFromFunction(*I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004750 } else {
4751#ifndef NDEBUG
Chris Lattner8a6411c2009-08-23 04:37:46 +00004752 DEBUG(errs() << "IC: Mod = " << OrigI << '\n'
4753 << " New = " << *I << '\n');
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004754#endif
4755
4756 // If the instruction was modified, it's possible that it is now dead.
4757 // if so, remove it.
4758 if (isInstructionTriviallyDead(I)) {
Chris Lattner3183fb62009-08-30 06:13:40 +00004759 EraseInstFromFunction(*I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004760 } else {
Chris Lattner3183fb62009-08-30 06:13:40 +00004761 Worklist.Add(I);
Chris Lattner4796b622009-08-30 06:22:51 +00004762 Worklist.AddUsersToWorkList(*I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004763 }
4764 }
Chris Lattner21d79e22009-08-31 06:57:37 +00004765 MadeIRChange = true;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004766 }
4767 }
4768
Chris Lattner5119c702009-08-30 05:55:36 +00004769 Worklist.Zap();
Chris Lattner21d79e22009-08-31 06:57:37 +00004770 return MadeIRChange;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004771}
4772
4773
4774bool InstCombiner::runOnFunction(Function &F) {
4775 MustPreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
Chris Lattneree5839b2009-10-15 04:13:44 +00004776 TD = getAnalysisIfAvailable<TargetData>();
4777
Chris Lattnerc7694852009-08-30 07:44:24 +00004778
4779 /// Builder - This is an IRBuilder that automatically inserts new
4780 /// instructions into the worklist when they are created.
Chris Lattneree5839b2009-10-15 04:13:44 +00004781 IRBuilder<true, TargetFolder, InstCombineIRInserter>
Chris Lattner002e65d2009-11-06 05:59:53 +00004782 TheBuilder(F.getContext(), TargetFolder(TD),
Chris Lattnerc7694852009-08-30 07:44:24 +00004783 InstCombineIRInserter(Worklist));
4784 Builder = &TheBuilder;
4785
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004786 bool EverMadeChange = false;
4787
4788 // Iterate while there is work to do.
4789 unsigned Iteration = 0;
Bill Wendlingd9644a42008-05-14 22:45:20 +00004790 while (DoOneIteration(F, Iteration++))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004791 EverMadeChange = true;
Chris Lattnerc7694852009-08-30 07:44:24 +00004792
4793 Builder = 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004794 return EverMadeChange;
4795}
4796
4797FunctionPass *llvm::createInstructionCombiningPass() {
4798 return new InstCombiner();
4799}