blob: 1cd2c4657eec3aba078b9a9d15d7475413c35d1e [file] [log] [blame]
Chris Lattnere6794492002-08-12 21:17:25 +00001//===- InstructionCombining.cpp - Combine multiple instructions -----------===//
John Criswell482202a2003-10-20 19:43:21 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file was developed by the LLVM research group and is distributed under
6// the University of Illinois Open Source License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
Chris Lattnerca081252001-12-14 16:52:21 +00009//
10// InstructionCombining - Combine instructions to form fewer, simple
Chris Lattner99f48c62002-09-02 04:59:56 +000011// instructions. This pass does not modify the CFG This pass is where algebraic
12// simplification happens.
Chris Lattnerca081252001-12-14 16:52:21 +000013//
14// This pass combines things like:
Chris Lattnerdd1a86d2004-05-04 15:19:33 +000015// %Y = add int %X, 1
16// %Z = add int %Y, 1
Chris Lattnerca081252001-12-14 16:52:21 +000017// into:
Chris Lattnerdd1a86d2004-05-04 15:19:33 +000018// %Z = add int %X, 2
Chris Lattnerca081252001-12-14 16:52:21 +000019//
20// This is a simple worklist driven algorithm.
21//
Chris Lattner216c7b82003-09-10 05:29:43 +000022// This pass guarantees that the following canonicalizations are performed on
Chris Lattnerbfb1d032003-07-23 21:41:57 +000023// the program:
24// 1. If a binary operator has a constant operand, it is moved to the RHS
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +000025// 2. Bitwise operators with constant operands are always grouped so that
26// shifts are performed first, then or's, then and's, then xor's.
Chris Lattnerbfb1d032003-07-23 21:41:57 +000027// 3. SetCC instructions are converted from <,>,<=,>= to ==,!= if possible
28// 4. All SetCC instructions on boolean values are replaced with logical ops
Chris Lattnerede3fe02003-08-13 04:18:28 +000029// 5. add X, X is represented as (X*2) => (X << 1)
30// 6. Multiplies with a power-of-two constant argument are transformed into
31// shifts.
Chris Lattnerbfb1d032003-07-23 21:41:57 +000032// N. This list is incomplete
33//
Chris Lattnerca081252001-12-14 16:52:21 +000034//===----------------------------------------------------------------------===//
35
Chris Lattner7d2a5392004-03-13 23:54:27 +000036#define DEBUG_TYPE "instcombine"
Chris Lattnerb4cfa7f2002-05-07 20:03:00 +000037#include "llvm/Transforms/Scalar.h"
Chris Lattner471bd762003-05-22 19:07:21 +000038#include "llvm/Instructions.h"
Chris Lattner51ea1272004-02-28 05:22:00 +000039#include "llvm/Intrinsics.h"
Chris Lattner04805fa2002-02-26 21:46:54 +000040#include "llvm/Pass.h"
Chris Lattner34428442003-05-27 16:40:51 +000041#include "llvm/Constants.h"
Chris Lattner1085bdf2002-11-04 16:18:53 +000042#include "llvm/DerivedTypes.h"
Chris Lattner0f1d8a32003-06-26 05:06:25 +000043#include "llvm/GlobalVariable.h"
Chris Lattnerf4ad1652003-11-02 05:57:39 +000044#include "llvm/Target/TargetData.h"
45#include "llvm/Transforms/Utils/BasicBlockUtils.h"
46#include "llvm/Transforms/Utils/Local.h"
Chris Lattner69193f92004-04-05 01:30:19 +000047#include "llvm/Support/CallSite.h"
48#include "llvm/Support/GetElementPtrTypeIterator.h"
Chris Lattner60a65912002-02-12 21:07:25 +000049#include "llvm/Support/InstIterator.h"
Chris Lattner260ab202002-04-18 17:39:14 +000050#include "llvm/Support/InstVisitor.h"
Chris Lattnerd4252a72004-07-30 07:50:03 +000051#include "llvm/Support/PatternMatch.h"
Reid Spencer7c16caa2004-09-01 22:55:40 +000052#include "llvm/Support/Debug.h"
53#include "llvm/ADT/Statistic.h"
Chris Lattner053c0932002-05-14 15:24:07 +000054#include <algorithm>
Chris Lattner8427bff2003-12-07 01:24:23 +000055using namespace llvm;
Chris Lattnerd4252a72004-07-30 07:50:03 +000056using namespace llvm::PatternMatch;
Brian Gaeke960707c2003-11-11 22:41:34 +000057
Chris Lattner260ab202002-04-18 17:39:14 +000058namespace {
Chris Lattnerbf3a0992002-10-01 22:38:41 +000059 Statistic<> NumCombined ("instcombine", "Number of insts combined");
60 Statistic<> NumConstProp("instcombine", "Number of constant folds");
61 Statistic<> NumDeadInst ("instcombine", "Number of dead inst eliminated");
62
Chris Lattnerc8e66542002-04-27 06:56:12 +000063 class InstCombiner : public FunctionPass,
Chris Lattner260ab202002-04-18 17:39:14 +000064 public InstVisitor<InstCombiner, Instruction*> {
65 // Worklist of all of the instructions that need to be simplified.
66 std::vector<Instruction*> WorkList;
Chris Lattnerf4ad1652003-11-02 05:57:39 +000067 TargetData *TD;
Chris Lattner260ab202002-04-18 17:39:14 +000068
Chris Lattner51ea1272004-02-28 05:22:00 +000069 /// AddUsersToWorkList - When an instruction is simplified, add all users of
70 /// the instruction to the work lists because they might get more simplified
71 /// now.
72 ///
73 void AddUsersToWorkList(Instruction &I) {
Chris Lattner113f4f42002-06-25 16:13:24 +000074 for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
Chris Lattner260ab202002-04-18 17:39:14 +000075 UI != UE; ++UI)
76 WorkList.push_back(cast<Instruction>(*UI));
77 }
78
Chris Lattner51ea1272004-02-28 05:22:00 +000079 /// AddUsesToWorkList - When an instruction is simplified, add operands to
80 /// the work lists because they might get more simplified now.
81 ///
82 void AddUsesToWorkList(Instruction &I) {
83 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
84 if (Instruction *Op = dyn_cast<Instruction>(I.getOperand(i)))
85 WorkList.push_back(Op);
86 }
87
Chris Lattner99f48c62002-09-02 04:59:56 +000088 // removeFromWorkList - remove all instances of I from the worklist.
89 void removeFromWorkList(Instruction *I);
Chris Lattner260ab202002-04-18 17:39:14 +000090 public:
Chris Lattner113f4f42002-06-25 16:13:24 +000091 virtual bool runOnFunction(Function &F);
Chris Lattner260ab202002-04-18 17:39:14 +000092
Chris Lattnerf12cc842002-04-28 21:27:06 +000093 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Chris Lattnerf4ad1652003-11-02 05:57:39 +000094 AU.addRequired<TargetData>();
Chris Lattner820d9712002-10-21 20:00:28 +000095 AU.setPreservesCFG();
Chris Lattnerf12cc842002-04-28 21:27:06 +000096 }
97
Chris Lattner69193f92004-04-05 01:30:19 +000098 TargetData &getTargetData() const { return *TD; }
99
Chris Lattner260ab202002-04-18 17:39:14 +0000100 // Visitation implementation - Implement instruction combining for different
101 // instruction types. The semantics are as follows:
102 // Return Value:
103 // null - No change was made
Chris Lattnere6794492002-08-12 21:17:25 +0000104 // I - Change was made, I is still valid, I may be dead though
Chris Lattner260ab202002-04-18 17:39:14 +0000105 // otherwise - Change was made, replace I with returned instruction
106 //
Chris Lattner113f4f42002-06-25 16:13:24 +0000107 Instruction *visitAdd(BinaryOperator &I);
108 Instruction *visitSub(BinaryOperator &I);
109 Instruction *visitMul(BinaryOperator &I);
110 Instruction *visitDiv(BinaryOperator &I);
111 Instruction *visitRem(BinaryOperator &I);
112 Instruction *visitAnd(BinaryOperator &I);
113 Instruction *visitOr (BinaryOperator &I);
114 Instruction *visitXor(BinaryOperator &I);
115 Instruction *visitSetCondInst(BinaryOperator &I);
Chris Lattnere8d6c602003-03-10 19:16:08 +0000116 Instruction *visitShiftInst(ShiftInst &I);
Chris Lattner113f4f42002-06-25 16:13:24 +0000117 Instruction *visitCastInst(CastInst &CI);
Chris Lattnerb909e8b2004-03-12 05:52:32 +0000118 Instruction *visitSelectInst(SelectInst &CI);
Chris Lattner970c33a2003-06-19 17:00:31 +0000119 Instruction *visitCallInst(CallInst &CI);
120 Instruction *visitInvokeInst(InvokeInst &II);
Chris Lattner113f4f42002-06-25 16:13:24 +0000121 Instruction *visitPHINode(PHINode &PN);
122 Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
Chris Lattner1085bdf2002-11-04 16:18:53 +0000123 Instruction *visitAllocationInst(AllocationInst &AI);
Chris Lattner8427bff2003-12-07 01:24:23 +0000124 Instruction *visitFreeInst(FreeInst &FI);
Chris Lattner0f1d8a32003-06-26 05:06:25 +0000125 Instruction *visitLoadInst(LoadInst &LI);
Chris Lattner9eef8a72003-06-04 04:46:00 +0000126 Instruction *visitBranchInst(BranchInst &BI);
Chris Lattner4c9c20a2004-07-03 00:26:11 +0000127 Instruction *visitSwitchInst(SwitchInst &SI);
Chris Lattner260ab202002-04-18 17:39:14 +0000128
129 // visitInstruction - Specify what to return for unhandled instructions...
Chris Lattner113f4f42002-06-25 16:13:24 +0000130 Instruction *visitInstruction(Instruction &I) { return 0; }
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000131
Chris Lattner970c33a2003-06-19 17:00:31 +0000132 private:
Chris Lattneraec3d942003-10-07 22:32:43 +0000133 Instruction *visitCallSite(CallSite CS);
Chris Lattner970c33a2003-06-19 17:00:31 +0000134 bool transformConstExprCastCall(CallSite CS);
135
Chris Lattner69193f92004-04-05 01:30:19 +0000136 public:
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000137 // InsertNewInstBefore - insert an instruction New before instruction Old
138 // in the program. Add the new instruction to the worklist.
139 //
Chris Lattner623826c2004-09-28 21:48:02 +0000140 Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
Chris Lattner65217ff2002-08-23 18:32:43 +0000141 assert(New && New->getParent() == 0 &&
142 "New instruction already inserted into a basic block!");
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000143 BasicBlock *BB = Old.getParent();
144 BB->getInstList().insert(&Old, New); // Insert inst
145 WorkList.push_back(New); // Add to worklist
Chris Lattnere79e8542004-02-23 06:38:22 +0000146 return New;
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000147 }
148
Chris Lattner7e794272004-09-24 15:21:34 +0000149 /// InsertCastBefore - Insert a cast of V to TY before the instruction POS.
150 /// This also adds the cast to the worklist. Finally, this returns the
151 /// cast.
152 Value *InsertCastBefore(Value *V, const Type *Ty, Instruction &Pos) {
153 if (V->getType() == Ty) return V;
154
155 Instruction *C = new CastInst(V, Ty, V->getName(), &Pos);
156 WorkList.push_back(C);
157 return C;
158 }
159
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000160 // ReplaceInstUsesWith - This method is to be used when an instruction is
161 // found to be dead, replacable with another preexisting expression. Here
162 // we add all uses of I to the worklist, replace all uses of I with the new
163 // value, then return I, so that the inst combiner will know that I was
164 // modified.
165 //
166 Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
Chris Lattner51ea1272004-02-28 05:22:00 +0000167 AddUsersToWorkList(I); // Add all modified instrs to worklist
Chris Lattner8953b902004-04-05 02:10:19 +0000168 if (&I != V) {
169 I.replaceAllUsesWith(V);
170 return &I;
171 } else {
172 // If we are replacing the instruction with itself, this must be in a
173 // segment of unreachable code, so just clobber the instruction.
174 I.replaceAllUsesWith(Constant::getNullValue(I.getType()));
175 return &I;
176 }
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000177 }
Chris Lattner51ea1272004-02-28 05:22:00 +0000178
179 // EraseInstFromFunction - When dealing with an instruction that has side
180 // effects or produces a void value, we can't rely on DCE to delete the
181 // instruction. Instead, visit methods should return the value returned by
182 // this function.
183 Instruction *EraseInstFromFunction(Instruction &I) {
184 assert(I.use_empty() && "Cannot erase instruction that is used!");
185 AddUsesToWorkList(I);
186 removeFromWorkList(&I);
187 I.getParent()->getInstList().erase(&I);
188 return 0; // Don't do anything with FI
189 }
190
191
Chris Lattner3ac7c262003-08-13 20:16:26 +0000192 private:
Chris Lattnerdfae8be2003-07-24 17:35:25 +0000193 /// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
194 /// InsertBefore instruction. This is specialized a bit to avoid inserting
195 /// casts that are known to not do anything...
196 ///
197 Value *InsertOperandCastBefore(Value *V, const Type *DestTy,
198 Instruction *InsertBefore);
199
Chris Lattner7fb29e12003-03-11 00:12:48 +0000200 // SimplifyCommutative - This performs a few simplifications for commutative
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000201 // operators.
Chris Lattner7fb29e12003-03-11 00:12:48 +0000202 bool SimplifyCommutative(BinaryOperator &I);
Chris Lattnerba1cb382003-09-19 17:17:26 +0000203
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000204
205 // FoldOpIntoPhi - Given a binary operator or cast instruction which has a
206 // PHI node as operand #0, see if we can fold the instruction into the PHI
207 // (which is only possible if all operands to the PHI are constants).
208 Instruction *FoldOpIntoPhi(Instruction &I);
209
Chris Lattnerba1cb382003-09-19 17:17:26 +0000210 Instruction *OptAndOp(Instruction *Op, ConstantIntegral *OpRHS,
211 ConstantIntegral *AndRHS, BinaryOperator &TheAnd);
Chris Lattner260ab202002-04-18 17:39:14 +0000212 };
Chris Lattnerb28b6802002-07-23 18:06:35 +0000213
Chris Lattnerc8b70922002-07-26 21:12:46 +0000214 RegisterOpt<InstCombiner> X("instcombine", "Combine redundant instructions");
Chris Lattner260ab202002-04-18 17:39:14 +0000215}
216
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000217// getComplexity: Assign a complexity or rank value to LLVM Values...
218// 0 -> Constant, 1 -> Other, 2 -> Argument, 2 -> Unary, 3 -> OtherInst
219static unsigned getComplexity(Value *V) {
220 if (isa<Instruction>(V)) {
221 if (BinaryOperator::isNeg(V) || BinaryOperator::isNot(V))
222 return 2;
223 return 3;
224 }
225 if (isa<Argument>(V)) return 2;
226 return isa<Constant>(V) ? 0 : 1;
227}
Chris Lattner260ab202002-04-18 17:39:14 +0000228
Chris Lattner7fb29e12003-03-11 00:12:48 +0000229// isOnlyUse - Return true if this instruction will be deleted if we stop using
230// it.
231static bool isOnlyUse(Value *V) {
Chris Lattnerf95d9b92003-10-15 16:48:29 +0000232 return V->hasOneUse() || isa<Constant>(V);
Chris Lattner7fb29e12003-03-11 00:12:48 +0000233}
234
Chris Lattnere79e8542004-02-23 06:38:22 +0000235// getPromotedType - Return the specified type promoted as it would be to pass
236// though a va_arg area...
237static const Type *getPromotedType(const Type *Ty) {
Chris Lattner97bfcea2004-06-17 18:16:02 +0000238 switch (Ty->getTypeID()) {
Chris Lattnere79e8542004-02-23 06:38:22 +0000239 case Type::SByteTyID:
240 case Type::ShortTyID: return Type::IntTy;
241 case Type::UByteTyID:
242 case Type::UShortTyID: return Type::UIntTy;
243 case Type::FloatTyID: return Type::DoubleTy;
244 default: return Ty;
245 }
246}
247
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000248// SimplifyCommutative - This performs a few simplifications for commutative
249// operators:
Chris Lattner260ab202002-04-18 17:39:14 +0000250//
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000251// 1. Order operands such that they are listed from right (least complex) to
252// left (most complex). This puts constants before unary operators before
253// binary operators.
254//
Chris Lattner7fb29e12003-03-11 00:12:48 +0000255// 2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
256// 3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000257//
Chris Lattner7fb29e12003-03-11 00:12:48 +0000258bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000259 bool Changed = false;
260 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
261 Changed = !I.swapOperands();
262
263 if (!I.isAssociative()) return Changed;
264 Instruction::BinaryOps Opcode = I.getOpcode();
Chris Lattner7fb29e12003-03-11 00:12:48 +0000265 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
266 if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
267 if (isa<Constant>(I.getOperand(1))) {
Chris Lattner34428442003-05-27 16:40:51 +0000268 Constant *Folded = ConstantExpr::get(I.getOpcode(),
269 cast<Constant>(I.getOperand(1)),
270 cast<Constant>(Op->getOperand(1)));
Chris Lattner7fb29e12003-03-11 00:12:48 +0000271 I.setOperand(0, Op->getOperand(0));
272 I.setOperand(1, Folded);
273 return true;
274 } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
275 if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
276 isOnlyUse(Op) && isOnlyUse(Op1)) {
277 Constant *C1 = cast<Constant>(Op->getOperand(1));
278 Constant *C2 = cast<Constant>(Op1->getOperand(1));
279
280 // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattner34428442003-05-27 16:40:51 +0000281 Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
Chris Lattner7fb29e12003-03-11 00:12:48 +0000282 Instruction *New = BinaryOperator::create(Opcode, Op->getOperand(0),
283 Op1->getOperand(0),
284 Op1->getName(), &I);
285 WorkList.push_back(New);
286 I.setOperand(0, New);
287 I.setOperand(1, Folded);
288 return true;
289 }
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000290 }
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000291 return Changed;
Chris Lattner260ab202002-04-18 17:39:14 +0000292}
Chris Lattnerca081252001-12-14 16:52:21 +0000293
Chris Lattnerbb74e222003-03-10 23:06:50 +0000294// dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
295// if the LHS is a constant zero (which is the 'negate' form).
Chris Lattner9fa53de2002-05-06 16:49:18 +0000296//
Chris Lattnerbb74e222003-03-10 23:06:50 +0000297static inline Value *dyn_castNegVal(Value *V) {
298 if (BinaryOperator::isNeg(V))
299 return BinaryOperator::getNegArgument(cast<BinaryOperator>(V));
300
Chris Lattner9244df62003-04-30 22:19:10 +0000301 // Constants can be considered to be negated values if they can be folded...
302 if (Constant *C = dyn_cast<Constant>(V))
Chris Lattnerc8e7e292004-06-10 02:12:35 +0000303 return ConstantExpr::getNeg(C);
Chris Lattnerbb74e222003-03-10 23:06:50 +0000304 return 0;
Chris Lattner9fa53de2002-05-06 16:49:18 +0000305}
306
Chris Lattnerbb74e222003-03-10 23:06:50 +0000307static inline Value *dyn_castNotVal(Value *V) {
308 if (BinaryOperator::isNot(V))
309 return BinaryOperator::getNotArgument(cast<BinaryOperator>(V));
310
311 // Constants can be considered to be not'ed values...
Chris Lattnerdd65d862003-04-30 22:34:06 +0000312 if (ConstantIntegral *C = dyn_cast<ConstantIntegral>(V))
Chris Lattnerc8e7e292004-06-10 02:12:35 +0000313 return ConstantExpr::getNot(C);
Chris Lattnerbb74e222003-03-10 23:06:50 +0000314 return 0;
315}
316
Chris Lattner7fb29e12003-03-11 00:12:48 +0000317// dyn_castFoldableMul - If this value is a multiply that can be folded into
318// other computations (because it has a constant operand), return the
319// non-constant operand of the multiply.
320//
321static inline Value *dyn_castFoldableMul(Value *V) {
Chris Lattnerf95d9b92003-10-15 16:48:29 +0000322 if (V->hasOneUse() && V->getType()->isInteger())
Chris Lattner7fb29e12003-03-11 00:12:48 +0000323 if (Instruction *I = dyn_cast<Instruction>(V))
324 if (I->getOpcode() == Instruction::Mul)
325 if (isa<Constant>(I->getOperand(1)))
326 return I->getOperand(0);
327 return 0;
Chris Lattner3082c5a2003-02-18 19:28:33 +0000328}
Chris Lattner31ae8632002-08-14 17:51:49 +0000329
Chris Lattner3082c5a2003-02-18 19:28:33 +0000330// Log2 - Calculate the log base 2 for the specified value if it is exactly a
331// power of 2.
332static unsigned Log2(uint64_t Val) {
333 assert(Val > 1 && "Values 0 and 1 should be handled elsewhere!");
334 unsigned Count = 0;
335 while (Val != 1) {
336 if (Val & 1) return 0; // Multiple bits set?
337 Val >>= 1;
338 ++Count;
339 }
340 return Count;
Chris Lattner31ae8632002-08-14 17:51:49 +0000341}
342
Chris Lattner623826c2004-09-28 21:48:02 +0000343// AddOne, SubOne - Add or subtract a constant one from an integer constant...
344static Constant *AddOne(ConstantInt *C) {
345 return ConstantExpr::getAdd(C, ConstantInt::get(C->getType(), 1));
346}
347static Constant *SubOne(ConstantInt *C) {
348 return ConstantExpr::getSub(C, ConstantInt::get(C->getType(), 1));
349}
350
351// isTrueWhenEqual - Return true if the specified setcondinst instruction is
352// true when both operands are equal...
353//
354static bool isTrueWhenEqual(Instruction &I) {
355 return I.getOpcode() == Instruction::SetEQ ||
356 I.getOpcode() == Instruction::SetGE ||
357 I.getOpcode() == Instruction::SetLE;
358}
Chris Lattnerb8b97502003-08-13 19:01:45 +0000359
360/// AssociativeOpt - Perform an optimization on an associative operator. This
361/// function is designed to check a chain of associative operators for a
362/// potential to apply a certain optimization. Since the optimization may be
363/// applicable if the expression was reassociated, this checks the chain, then
364/// reassociates the expression as necessary to expose the optimization
365/// opportunity. This makes use of a special Functor, which must define
366/// 'shouldApply' and 'apply' methods.
367///
368template<typename Functor>
369Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
370 unsigned Opcode = Root.getOpcode();
371 Value *LHS = Root.getOperand(0);
372
373 // Quick check, see if the immediate LHS matches...
374 if (F.shouldApply(LHS))
375 return F.apply(Root);
376
377 // Otherwise, if the LHS is not of the same opcode as the root, return.
378 Instruction *LHSI = dyn_cast<Instruction>(LHS);
Chris Lattnerf95d9b92003-10-15 16:48:29 +0000379 while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
Chris Lattnerb8b97502003-08-13 19:01:45 +0000380 // Should we apply this transform to the RHS?
381 bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
382
383 // If not to the RHS, check to see if we should apply to the LHS...
384 if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
385 cast<BinaryOperator>(LHSI)->swapOperands(); // Make the LHS the RHS
386 ShouldApply = true;
387 }
388
389 // If the functor wants to apply the optimization to the RHS of LHSI,
390 // reassociate the expression from ((? op A) op B) to (? op (A op B))
391 if (ShouldApply) {
392 BasicBlock *BB = Root.getParent();
Chris Lattnerb8b97502003-08-13 19:01:45 +0000393
394 // Now all of the instructions are in the current basic block, go ahead
395 // and perform the reassociation.
396 Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
397
398 // First move the selected RHS to the LHS of the root...
399 Root.setOperand(0, LHSI->getOperand(1));
400
401 // Make what used to be the LHS of the root be the user of the root...
402 Value *ExtraOperand = TmpLHSI->getOperand(1);
Chris Lattner284d3b02004-04-16 18:08:07 +0000403 if (&Root == TmpLHSI) {
Chris Lattner8953b902004-04-05 02:10:19 +0000404 Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
405 return 0;
406 }
Chris Lattner284d3b02004-04-16 18:08:07 +0000407 Root.replaceAllUsesWith(TmpLHSI); // Users now use TmpLHSI
Chris Lattnerb8b97502003-08-13 19:01:45 +0000408 TmpLHSI->setOperand(1, &Root); // TmpLHSI now uses the root
Chris Lattner284d3b02004-04-16 18:08:07 +0000409 TmpLHSI->getParent()->getInstList().remove(TmpLHSI);
410 BasicBlock::iterator ARI = &Root; ++ARI;
411 BB->getInstList().insert(ARI, TmpLHSI); // Move TmpLHSI to after Root
412 ARI = Root;
Chris Lattnerb8b97502003-08-13 19:01:45 +0000413
414 // Now propagate the ExtraOperand down the chain of instructions until we
415 // get to LHSI.
416 while (TmpLHSI != LHSI) {
417 Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
Chris Lattner284d3b02004-04-16 18:08:07 +0000418 // Move the instruction to immediately before the chain we are
419 // constructing to avoid breaking dominance properties.
420 NextLHSI->getParent()->getInstList().remove(NextLHSI);
421 BB->getInstList().insert(ARI, NextLHSI);
422 ARI = NextLHSI;
423
Chris Lattnerb8b97502003-08-13 19:01:45 +0000424 Value *NextOp = NextLHSI->getOperand(1);
425 NextLHSI->setOperand(1, ExtraOperand);
426 TmpLHSI = NextLHSI;
427 ExtraOperand = NextOp;
428 }
429
430 // Now that the instructions are reassociated, have the functor perform
431 // the transformation...
432 return F.apply(Root);
433 }
434
435 LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
436 }
437 return 0;
438}
439
440
441// AddRHS - Implements: X + X --> X << 1
442struct AddRHS {
443 Value *RHS;
444 AddRHS(Value *rhs) : RHS(rhs) {}
445 bool shouldApply(Value *LHS) const { return LHS == RHS; }
446 Instruction *apply(BinaryOperator &Add) const {
447 return new ShiftInst(Instruction::Shl, Add.getOperand(0),
448 ConstantInt::get(Type::UByteTy, 1));
449 }
450};
451
452// AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
453// iff C1&C2 == 0
454struct AddMaskingAnd {
455 Constant *C2;
456 AddMaskingAnd(Constant *c) : C2(c) {}
457 bool shouldApply(Value *LHS) const {
Chris Lattnerd4252a72004-07-30 07:50:03 +0000458 ConstantInt *C1;
459 return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
460 ConstantExpr::getAnd(C1, C2)->isNullValue();
Chris Lattnerb8b97502003-08-13 19:01:45 +0000461 }
462 Instruction *apply(BinaryOperator &Add) const {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000463 return BinaryOperator::createOr(Add.getOperand(0), Add.getOperand(1));
Chris Lattnerb8b97502003-08-13 19:01:45 +0000464 }
465};
466
Chris Lattner183b3362004-04-09 19:05:30 +0000467static Value *FoldOperationIntoSelectOperand(Instruction &BI, Value *SO,
468 InstCombiner *IC) {
469 // Figure out if the constant is the left or the right argument.
470 bool ConstIsRHS = isa<Constant>(BI.getOperand(1));
471 Constant *ConstOperand = cast<Constant>(BI.getOperand(ConstIsRHS));
Chris Lattnerb8b97502003-08-13 19:01:45 +0000472
Chris Lattner183b3362004-04-09 19:05:30 +0000473 if (Constant *SOC = dyn_cast<Constant>(SO)) {
474 if (ConstIsRHS)
475 return ConstantExpr::get(BI.getOpcode(), SOC, ConstOperand);
476 return ConstantExpr::get(BI.getOpcode(), ConstOperand, SOC);
477 }
478
479 Value *Op0 = SO, *Op1 = ConstOperand;
480 if (!ConstIsRHS)
481 std::swap(Op0, Op1);
482 Instruction *New;
483 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&BI))
484 New = BinaryOperator::create(BO->getOpcode(), Op0, Op1);
485 else if (ShiftInst *SI = dyn_cast<ShiftInst>(&BI))
486 New = new ShiftInst(SI->getOpcode(), Op0, Op1);
Chris Lattnerf9d96652004-04-10 19:15:56 +0000487 else {
Chris Lattner183b3362004-04-09 19:05:30 +0000488 assert(0 && "Unknown binary instruction type!");
Chris Lattnerf9d96652004-04-10 19:15:56 +0000489 abort();
490 }
Chris Lattner183b3362004-04-09 19:05:30 +0000491 return IC->InsertNewInstBefore(New, BI);
492}
493
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000494
495/// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
496/// node as operand #0, see if we can fold the instruction into the PHI (which
497/// is only possible if all operands to the PHI are constants).
498Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
499 PHINode *PN = cast<PHINode>(I.getOperand(0));
500 if (!PN->hasOneUse()) return 0;
501
502 // Check to see if all of the operands of the PHI are constants. If not, we
503 // cannot do the transformation.
504 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
505 if (!isa<Constant>(PN->getIncomingValue(i)))
506 return 0;
507
508 // Okay, we can do the transformation: create the new PHI node.
509 PHINode *NewPN = new PHINode(I.getType(), I.getName());
510 I.setName("");
511 NewPN->op_reserve(PN->getNumOperands());
512 InsertNewInstBefore(NewPN, *PN);
513
514 // Next, add all of the operands to the PHI.
515 if (I.getNumOperands() == 2) {
516 Constant *C = cast<Constant>(I.getOperand(1));
517 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
518 Constant *InV = cast<Constant>(PN->getIncomingValue(i));
519 NewPN->addIncoming(ConstantExpr::get(I.getOpcode(), InV, C),
520 PN->getIncomingBlock(i));
521 }
522 } else {
523 assert(isa<CastInst>(I) && "Unary op should be a cast!");
524 const Type *RetTy = I.getType();
525 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
526 Constant *InV = cast<Constant>(PN->getIncomingValue(i));
527 NewPN->addIncoming(ConstantExpr::getCast(InV, RetTy),
528 PN->getIncomingBlock(i));
529 }
530 }
531 return ReplaceInstUsesWith(I, NewPN);
532}
533
Chris Lattner183b3362004-04-09 19:05:30 +0000534// FoldBinOpIntoSelect - Given an instruction with a select as one operand and a
535// constant as the other operand, try to fold the binary operator into the
536// select arguments.
537static Instruction *FoldBinOpIntoSelect(Instruction &BI, SelectInst *SI,
538 InstCombiner *IC) {
539 // Don't modify shared select instructions
540 if (!SI->hasOneUse()) return 0;
541 Value *TV = SI->getOperand(1);
542 Value *FV = SI->getOperand(2);
543
544 if (isa<Constant>(TV) || isa<Constant>(FV)) {
545 Value *SelectTrueVal = FoldOperationIntoSelectOperand(BI, TV, IC);
546 Value *SelectFalseVal = FoldOperationIntoSelectOperand(BI, FV, IC);
547
548 return new SelectInst(SI->getCondition(), SelectTrueVal,
549 SelectFalseVal);
550 }
551 return 0;
552}
Chris Lattnerb8b97502003-08-13 19:01:45 +0000553
Chris Lattner113f4f42002-06-25 16:13:24 +0000554Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000555 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +0000556 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
Chris Lattner9fa53de2002-05-06 16:49:18 +0000557
Chris Lattnercf4a9962004-04-10 22:01:55 +0000558 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
559 // X + 0 --> X
560 if (!I.getType()->isFloatingPoint() && // -0 + +0 = +0, so it's not a noop
561 RHSC->isNullValue())
562 return ReplaceInstUsesWith(I, LHS);
563
564 // X + (signbit) --> X ^ signbit
565 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
566 unsigned NumBits = CI->getType()->getPrimitiveSize()*8;
567 uint64_t Val = CI->getRawValue() & (1ULL << NumBits)-1;
568 if (Val == (1ULL << NumBits-1))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000569 return BinaryOperator::createXor(LHS, RHS);
Chris Lattnercf4a9962004-04-10 22:01:55 +0000570 }
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000571
572 if (isa<PHINode>(LHS))
573 if (Instruction *NV = FoldOpIntoPhi(I))
574 return NV;
Chris Lattnercf4a9962004-04-10 22:01:55 +0000575 }
Chris Lattner9fa53de2002-05-06 16:49:18 +0000576
Chris Lattnerb8b97502003-08-13 19:01:45 +0000577 // X + X --> X << 1
Robert Bocchino7b5b86c2004-07-27 21:02:21 +0000578 if (I.getType()->isInteger()) {
Chris Lattnerb8b97502003-08-13 19:01:45 +0000579 if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS))) return Result;
Robert Bocchino7b5b86c2004-07-27 21:02:21 +0000580 }
Chris Lattnerede3fe02003-08-13 04:18:28 +0000581
Chris Lattner147e9752002-05-08 22:46:53 +0000582 // -A + B --> B - A
Chris Lattnerbb74e222003-03-10 23:06:50 +0000583 if (Value *V = dyn_castNegVal(LHS))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000584 return BinaryOperator::createSub(RHS, V);
Chris Lattner9fa53de2002-05-06 16:49:18 +0000585
586 // A + -B --> A - B
Chris Lattnerbb74e222003-03-10 23:06:50 +0000587 if (!isa<Constant>(RHS))
588 if (Value *V = dyn_castNegVal(RHS))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000589 return BinaryOperator::createSub(LHS, V);
Chris Lattner260ab202002-04-18 17:39:14 +0000590
Chris Lattner57c8d992003-02-18 19:57:07 +0000591 // X*C + X --> X * (C+1)
592 if (dyn_castFoldableMul(LHS) == RHS) {
Chris Lattner34428442003-05-27 16:40:51 +0000593 Constant *CP1 =
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000594 ConstantExpr::getAdd(
Chris Lattner34428442003-05-27 16:40:51 +0000595 cast<Constant>(cast<Instruction>(LHS)->getOperand(1)),
596 ConstantInt::get(I.getType(), 1));
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000597 return BinaryOperator::createMul(RHS, CP1);
Chris Lattner57c8d992003-02-18 19:57:07 +0000598 }
599
600 // X + X*C --> X * (C+1)
601 if (dyn_castFoldableMul(RHS) == LHS) {
Chris Lattner34428442003-05-27 16:40:51 +0000602 Constant *CP1 =
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000603 ConstantExpr::getAdd(
Chris Lattner34428442003-05-27 16:40:51 +0000604 cast<Constant>(cast<Instruction>(RHS)->getOperand(1)),
605 ConstantInt::get(I.getType(), 1));
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000606 return BinaryOperator::createMul(LHS, CP1);
Chris Lattner57c8d992003-02-18 19:57:07 +0000607 }
608
Chris Lattnerb8b97502003-08-13 19:01:45 +0000609 // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
Chris Lattnerd4252a72004-07-30 07:50:03 +0000610 ConstantInt *C2;
611 if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
Chris Lattnerb8b97502003-08-13 19:01:45 +0000612 if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2))) return R;
Chris Lattner7fb29e12003-03-11 00:12:48 +0000613
Chris Lattnerb9cde762003-10-02 15:11:26 +0000614 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
Chris Lattnerd4252a72004-07-30 07:50:03 +0000615 Value *X;
616 if (match(LHS, m_Not(m_Value(X)))) { // ~X + C --> (C-1) - X
617 Constant *C= ConstantExpr::getSub(CRHS, ConstantInt::get(I.getType(), 1));
618 return BinaryOperator::createSub(C, X);
Chris Lattnerb9cde762003-10-02 15:11:26 +0000619 }
Chris Lattnerd4252a72004-07-30 07:50:03 +0000620
621 // Try to fold constant add into select arguments.
622 if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
623 if (Instruction *R = FoldBinOpIntoSelect(I, SI, this))
624 return R;
Chris Lattnerb9cde762003-10-02 15:11:26 +0000625 }
626
Chris Lattner113f4f42002-06-25 16:13:24 +0000627 return Changed ? &I : 0;
Chris Lattner260ab202002-04-18 17:39:14 +0000628}
629
Chris Lattnerbdb0ce02003-07-22 21:46:59 +0000630// isSignBit - Return true if the value represented by the constant only has the
631// highest order bit set.
632static bool isSignBit(ConstantInt *CI) {
633 unsigned NumBits = CI->getType()->getPrimitiveSize()*8;
634 return (CI->getRawValue() & ~(-1LL << NumBits)) == (1ULL << (NumBits-1));
635}
636
Chris Lattnerdfae8be2003-07-24 17:35:25 +0000637static unsigned getTypeSizeInBits(const Type *Ty) {
638 return Ty == Type::BoolTy ? 1 : Ty->getPrimitiveSize()*8;
639}
640
Chris Lattner022167f2004-03-13 00:11:49 +0000641/// RemoveNoopCast - Strip off nonconverting casts from the value.
642///
643static Value *RemoveNoopCast(Value *V) {
644 if (CastInst *CI = dyn_cast<CastInst>(V)) {
645 const Type *CTy = CI->getType();
646 const Type *OpTy = CI->getOperand(0)->getType();
647 if (CTy->isInteger() && OpTy->isInteger()) {
648 if (CTy->getPrimitiveSize() == OpTy->getPrimitiveSize())
649 return RemoveNoopCast(CI->getOperand(0));
650 } else if (isa<PointerType>(CTy) && isa<PointerType>(OpTy))
651 return RemoveNoopCast(CI->getOperand(0));
652 }
653 return V;
654}
655
Chris Lattner113f4f42002-06-25 16:13:24 +0000656Instruction *InstCombiner::visitSub(BinaryOperator &I) {
Chris Lattner113f4f42002-06-25 16:13:24 +0000657 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000658
Chris Lattnere6794492002-08-12 21:17:25 +0000659 if (Op0 == Op1) // sub X, X -> 0
660 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner260ab202002-04-18 17:39:14 +0000661
Chris Lattnere6794492002-08-12 21:17:25 +0000662 // If this is a 'B = x-(-A)', change to B = x+A...
Chris Lattnerbb74e222003-03-10 23:06:50 +0000663 if (Value *V = dyn_castNegVal(Op1))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000664 return BinaryOperator::createAdd(Op0, V);
Chris Lattner9fa53de2002-05-06 16:49:18 +0000665
Chris Lattner8f2f5982003-11-05 01:06:05 +0000666 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
667 // Replace (-1 - A) with (~A)...
Chris Lattner3082c5a2003-02-18 19:28:33 +0000668 if (C->isAllOnesValue())
669 return BinaryOperator::createNot(Op1);
Chris Lattnerad3c4952002-05-09 01:29:19 +0000670
Chris Lattner8f2f5982003-11-05 01:06:05 +0000671 // C - ~X == X + (1+C)
Chris Lattnerd4252a72004-07-30 07:50:03 +0000672 Value *X;
673 if (match(Op1, m_Not(m_Value(X))))
674 return BinaryOperator::createAdd(X,
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000675 ConstantExpr::getAdd(C, ConstantInt::get(I.getType(), 1)));
Chris Lattner92295c52004-03-12 23:53:13 +0000676 // -((uint)X >> 31) -> ((int)X >> 31)
677 // -((int)X >> 31) -> ((uint)X >> 31)
Chris Lattner022167f2004-03-13 00:11:49 +0000678 if (C->isNullValue()) {
679 Value *NoopCastedRHS = RemoveNoopCast(Op1);
680 if (ShiftInst *SI = dyn_cast<ShiftInst>(NoopCastedRHS))
Chris Lattner92295c52004-03-12 23:53:13 +0000681 if (SI->getOpcode() == Instruction::Shr)
682 if (ConstantUInt *CU = dyn_cast<ConstantUInt>(SI->getOperand(1))) {
683 const Type *NewTy;
Chris Lattner022167f2004-03-13 00:11:49 +0000684 if (SI->getType()->isSigned())
Chris Lattner97bfcea2004-06-17 18:16:02 +0000685 NewTy = SI->getType()->getUnsignedVersion();
Chris Lattner92295c52004-03-12 23:53:13 +0000686 else
Chris Lattner97bfcea2004-06-17 18:16:02 +0000687 NewTy = SI->getType()->getSignedVersion();
Chris Lattner92295c52004-03-12 23:53:13 +0000688 // Check to see if we are shifting out everything but the sign bit.
Chris Lattner022167f2004-03-13 00:11:49 +0000689 if (CU->getValue() == SI->getType()->getPrimitiveSize()*8-1) {
Chris Lattner92295c52004-03-12 23:53:13 +0000690 // Ok, the transformation is safe. Insert a cast of the incoming
691 // value, then the new shift, then the new cast.
692 Instruction *FirstCast = new CastInst(SI->getOperand(0), NewTy,
693 SI->getOperand(0)->getName());
694 Value *InV = InsertNewInstBefore(FirstCast, I);
695 Instruction *NewShift = new ShiftInst(Instruction::Shr, FirstCast,
696 CU, SI->getName());
Chris Lattner022167f2004-03-13 00:11:49 +0000697 if (NewShift->getType() == I.getType())
698 return NewShift;
699 else {
700 InV = InsertNewInstBefore(NewShift, I);
701 return new CastInst(NewShift, I.getType());
702 }
Chris Lattner92295c52004-03-12 23:53:13 +0000703 }
704 }
Chris Lattner022167f2004-03-13 00:11:49 +0000705 }
Chris Lattner183b3362004-04-09 19:05:30 +0000706
707 // Try to fold constant sub into select arguments.
708 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
709 if (Instruction *R = FoldBinOpIntoSelect(I, SI, this))
710 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000711
712 if (isa<PHINode>(Op0))
713 if (Instruction *NV = FoldOpIntoPhi(I))
714 return NV;
Chris Lattner8f2f5982003-11-05 01:06:05 +0000715 }
716
Chris Lattner3082c5a2003-02-18 19:28:33 +0000717 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1))
Chris Lattnerf95d9b92003-10-15 16:48:29 +0000718 if (Op1I->hasOneUse()) {
Chris Lattner3082c5a2003-02-18 19:28:33 +0000719 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
720 // is not used by anyone else...
721 //
Chris Lattnerc2f0aa52004-02-02 20:09:56 +0000722 if (Op1I->getOpcode() == Instruction::Sub &&
723 !Op1I->getType()->isFloatingPoint()) {
Chris Lattner3082c5a2003-02-18 19:28:33 +0000724 // Swap the two operands of the subexpr...
725 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
726 Op1I->setOperand(0, IIOp1);
727 Op1I->setOperand(1, IIOp0);
728
729 // Create the new top level add instruction...
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000730 return BinaryOperator::createAdd(Op0, Op1);
Chris Lattner3082c5a2003-02-18 19:28:33 +0000731 }
732
733 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
734 //
735 if (Op1I->getOpcode() == Instruction::And &&
736 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
737 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
738
Chris Lattner396dbfe2004-06-09 05:08:07 +0000739 Value *NewNot =
740 InsertNewInstBefore(BinaryOperator::createNot(OtherOp, "B.not"), I);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000741 return BinaryOperator::createAnd(Op0, NewNot);
Chris Lattner3082c5a2003-02-18 19:28:33 +0000742 }
Chris Lattner57c8d992003-02-18 19:57:07 +0000743
744 // X - X*C --> X * (1-C)
745 if (dyn_castFoldableMul(Op1I) == Op0) {
Chris Lattner34428442003-05-27 16:40:51 +0000746 Constant *CP1 =
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000747 ConstantExpr::getSub(ConstantInt::get(I.getType(), 1),
Chris Lattner34428442003-05-27 16:40:51 +0000748 cast<Constant>(cast<Instruction>(Op1)->getOperand(1)));
Chris Lattner57c8d992003-02-18 19:57:07 +0000749 assert(CP1 && "Couldn't constant fold 1-C?");
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000750 return BinaryOperator::createMul(Op0, CP1);
Chris Lattner57c8d992003-02-18 19:57:07 +0000751 }
Chris Lattnerad3c4952002-05-09 01:29:19 +0000752 }
Chris Lattner3082c5a2003-02-18 19:28:33 +0000753
Chris Lattner57c8d992003-02-18 19:57:07 +0000754 // X*C - X --> X * (C-1)
755 if (dyn_castFoldableMul(Op0) == Op1) {
Chris Lattner34428442003-05-27 16:40:51 +0000756 Constant *CP1 =
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000757 ConstantExpr::getSub(cast<Constant>(cast<Instruction>(Op0)->getOperand(1)),
Chris Lattner34428442003-05-27 16:40:51 +0000758 ConstantInt::get(I.getType(), 1));
Chris Lattner57c8d992003-02-18 19:57:07 +0000759 assert(CP1 && "Couldn't constant fold C - 1?");
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000760 return BinaryOperator::createMul(Op1, CP1);
Chris Lattner57c8d992003-02-18 19:57:07 +0000761 }
762
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000763 return 0;
Chris Lattner260ab202002-04-18 17:39:14 +0000764}
765
Chris Lattnere79e8542004-02-23 06:38:22 +0000766/// isSignBitCheck - Given an exploded setcc instruction, return true if it is
767/// really just returns true if the most significant (sign) bit is set.
768static bool isSignBitCheck(unsigned Opcode, Value *LHS, ConstantInt *RHS) {
769 if (RHS->getType()->isSigned()) {
770 // True if source is LHS < 0 or LHS <= -1
771 return Opcode == Instruction::SetLT && RHS->isNullValue() ||
772 Opcode == Instruction::SetLE && RHS->isAllOnesValue();
773 } else {
774 ConstantUInt *RHSC = cast<ConstantUInt>(RHS);
775 // True if source is LHS > 127 or LHS >= 128, where the constants depend on
776 // the size of the integer type.
777 if (Opcode == Instruction::SetGE)
778 return RHSC->getValue() == 1ULL<<(RHS->getType()->getPrimitiveSize()*8-1);
779 if (Opcode == Instruction::SetGT)
780 return RHSC->getValue() ==
781 (1ULL << (RHS->getType()->getPrimitiveSize()*8-1))-1;
782 }
783 return false;
784}
785
Chris Lattner113f4f42002-06-25 16:13:24 +0000786Instruction *InstCombiner::visitMul(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000787 bool Changed = SimplifyCommutative(I);
Chris Lattner3082c5a2003-02-18 19:28:33 +0000788 Value *Op0 = I.getOperand(0);
Chris Lattner260ab202002-04-18 17:39:14 +0000789
Chris Lattnere6794492002-08-12 21:17:25 +0000790 // Simplify mul instructions with a constant RHS...
Chris Lattner3082c5a2003-02-18 19:28:33 +0000791 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
792 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnerede3fe02003-08-13 04:18:28 +0000793
794 // ((X << C1)*C2) == (X * (C2 << C1))
795 if (ShiftInst *SI = dyn_cast<ShiftInst>(Op0))
796 if (SI->getOpcode() == Instruction::Shl)
797 if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000798 return BinaryOperator::createMul(SI->getOperand(0),
799 ConstantExpr::getShl(CI, ShOp));
Chris Lattnerc1e7cc02004-01-12 19:35:11 +0000800
Chris Lattnercce81be2003-09-11 22:24:54 +0000801 if (CI->isNullValue())
802 return ReplaceInstUsesWith(I, Op1); // X * 0 == 0
803 if (CI->equalsInt(1)) // X * 1 == X
804 return ReplaceInstUsesWith(I, Op0);
805 if (CI->isAllOnesValue()) // X * -1 == 0 - X
Chris Lattner35236d82003-06-25 17:09:20 +0000806 return BinaryOperator::createNeg(Op0, I.getName());
Chris Lattner31ba1292002-04-29 22:24:47 +0000807
Chris Lattnercce81be2003-09-11 22:24:54 +0000808 int64_t Val = (int64_t)cast<ConstantInt>(CI)->getRawValue();
Chris Lattner3082c5a2003-02-18 19:28:33 +0000809 if (uint64_t C = Log2(Val)) // Replace X*(2^C) with X << C
810 return new ShiftInst(Instruction::Shl, Op0,
811 ConstantUInt::get(Type::UByteTy, C));
Robert Bocchino7b5b86c2004-07-27 21:02:21 +0000812 } else if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
Chris Lattner3082c5a2003-02-18 19:28:33 +0000813 if (Op1F->isNullValue())
814 return ReplaceInstUsesWith(I, Op1);
Chris Lattner31ba1292002-04-29 22:24:47 +0000815
Chris Lattner3082c5a2003-02-18 19:28:33 +0000816 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
817 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
818 if (Op1F->getValue() == 1.0)
819 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0'
820 }
Chris Lattner183b3362004-04-09 19:05:30 +0000821
822 // Try to fold constant mul into select arguments.
823 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
824 if (Instruction *R = FoldBinOpIntoSelect(I, SI, this))
825 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000826
827 if (isa<PHINode>(Op0))
828 if (Instruction *NV = FoldOpIntoPhi(I))
829 return NV;
Chris Lattner260ab202002-04-18 17:39:14 +0000830 }
831
Chris Lattner934a64cf2003-03-10 23:23:04 +0000832 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
833 if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000834 return BinaryOperator::createMul(Op0v, Op1v);
Chris Lattner934a64cf2003-03-10 23:23:04 +0000835
Chris Lattner2635b522004-02-23 05:39:21 +0000836 // If one of the operands of the multiply is a cast from a boolean value, then
837 // we know the bool is either zero or one, so this is a 'masking' multiply.
838 // See if we can simplify things based on how the boolean was originally
839 // formed.
840 CastInst *BoolCast = 0;
841 if (CastInst *CI = dyn_cast<CastInst>(I.getOperand(0)))
842 if (CI->getOperand(0)->getType() == Type::BoolTy)
843 BoolCast = CI;
844 if (!BoolCast)
845 if (CastInst *CI = dyn_cast<CastInst>(I.getOperand(1)))
846 if (CI->getOperand(0)->getType() == Type::BoolTy)
847 BoolCast = CI;
848 if (BoolCast) {
849 if (SetCondInst *SCI = dyn_cast<SetCondInst>(BoolCast->getOperand(0))) {
850 Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
851 const Type *SCOpTy = SCIOp0->getType();
852
Chris Lattnere79e8542004-02-23 06:38:22 +0000853 // If the setcc is true iff the sign bit of X is set, then convert this
854 // multiply into a shift/and combination.
855 if (isa<ConstantInt>(SCIOp1) &&
856 isSignBitCheck(SCI->getOpcode(), SCIOp0, cast<ConstantInt>(SCIOp1))) {
Chris Lattner2635b522004-02-23 05:39:21 +0000857 // Shift the X value right to turn it into "all signbits".
858 Constant *Amt = ConstantUInt::get(Type::UByteTy,
859 SCOpTy->getPrimitiveSize()*8-1);
Chris Lattnere79e8542004-02-23 06:38:22 +0000860 if (SCIOp0->getType()->isUnsigned()) {
Chris Lattner97bfcea2004-06-17 18:16:02 +0000861 const Type *NewTy = SCIOp0->getType()->getSignedVersion();
Chris Lattnere79e8542004-02-23 06:38:22 +0000862 SCIOp0 = InsertNewInstBefore(new CastInst(SCIOp0, NewTy,
863 SCIOp0->getName()), I);
864 }
865
866 Value *V =
867 InsertNewInstBefore(new ShiftInst(Instruction::Shr, SCIOp0, Amt,
868 BoolCast->getOperand(0)->getName()+
869 ".mask"), I);
Chris Lattner2635b522004-02-23 05:39:21 +0000870
871 // If the multiply type is not the same as the source type, sign extend
872 // or truncate to the multiply type.
873 if (I.getType() != V->getType())
Chris Lattnere79e8542004-02-23 06:38:22 +0000874 V = InsertNewInstBefore(new CastInst(V, I.getType(), V->getName()),I);
Chris Lattner2635b522004-02-23 05:39:21 +0000875
876 Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000877 return BinaryOperator::createAnd(V, OtherOp);
Chris Lattner2635b522004-02-23 05:39:21 +0000878 }
879 }
880 }
881
Chris Lattner113f4f42002-06-25 16:13:24 +0000882 return Changed ? &I : 0;
Chris Lattner260ab202002-04-18 17:39:14 +0000883}
884
Chris Lattner113f4f42002-06-25 16:13:24 +0000885Instruction *InstCombiner::visitDiv(BinaryOperator &I) {
Chris Lattner3082c5a2003-02-18 19:28:33 +0000886 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I.getOperand(1))) {
Chris Lattnere20c3342004-04-26 14:01:59 +0000887 // div X, 1 == X
Chris Lattnere6794492002-08-12 21:17:25 +0000888 if (RHS->equalsInt(1))
889 return ReplaceInstUsesWith(I, I.getOperand(0));
Chris Lattner3082c5a2003-02-18 19:28:33 +0000890
Chris Lattnere20c3342004-04-26 14:01:59 +0000891 // div X, -1 == -X
892 if (RHS->isAllOnesValue())
893 return BinaryOperator::createNeg(I.getOperand(0));
894
Chris Lattner272d5ca2004-09-28 18:22:15 +0000895 if (Instruction *LHS = dyn_cast<Instruction>(I.getOperand(0)))
896 if (LHS->getOpcode() == Instruction::Div)
897 if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
Chris Lattner272d5ca2004-09-28 18:22:15 +0000898 // (X / C1) / C2 -> X / (C1*C2)
899 return BinaryOperator::createDiv(LHS->getOperand(0),
900 ConstantExpr::getMul(RHS, LHSRHS));
901 }
902
Chris Lattner3082c5a2003-02-18 19:28:33 +0000903 // Check to see if this is an unsigned division with an exact power of 2,
904 // if so, convert to a right shift.
905 if (ConstantUInt *C = dyn_cast<ConstantUInt>(RHS))
906 if (uint64_t Val = C->getValue()) // Don't break X / 0
907 if (uint64_t C = Log2(Val))
908 return new ShiftInst(Instruction::Shr, I.getOperand(0),
909 ConstantUInt::get(Type::UByteTy, C));
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000910
911 if (isa<PHINode>(I.getOperand(0)) && !RHS->isNullValue())
912 if (Instruction *NV = FoldOpIntoPhi(I))
913 return NV;
Chris Lattner3082c5a2003-02-18 19:28:33 +0000914 }
915
916 // 0 / X == 0, we don't need to preserve faults!
917 if (ConstantInt *LHS = dyn_cast<ConstantInt>(I.getOperand(0)))
918 if (LHS->equalsInt(0))
919 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
920
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000921 return 0;
922}
923
924
Chris Lattner113f4f42002-06-25 16:13:24 +0000925Instruction *InstCombiner::visitRem(BinaryOperator &I) {
Chris Lattner7fd5f072004-07-06 07:01:22 +0000926 if (I.getType()->isSigned())
927 if (Value *RHSNeg = dyn_castNegVal(I.getOperand(1)))
Chris Lattner98c6bdf2004-07-06 07:11:42 +0000928 if (!isa<ConstantSInt>(RHSNeg) ||
Chris Lattner8e726062004-08-09 21:05:48 +0000929 cast<ConstantSInt>(RHSNeg)->getValue() > 0) {
Chris Lattner7fd5f072004-07-06 07:01:22 +0000930 // X % -Y -> X % Y
931 AddUsesToWorkList(I);
932 I.setOperand(1, RHSNeg);
933 return &I;
934 }
935
Chris Lattner3082c5a2003-02-18 19:28:33 +0000936 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I.getOperand(1))) {
937 if (RHS->equalsInt(1)) // X % 1 == 0
938 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
939
940 // Check to see if this is an unsigned remainder with an exact power of 2,
941 // if so, convert to a bitwise and.
942 if (ConstantUInt *C = dyn_cast<ConstantUInt>(RHS))
943 if (uint64_t Val = C->getValue()) // Don't break X % 0 (divide by zero)
Chris Lattnerd9e58132004-05-07 15:35:56 +0000944 if (!(Val & (Val-1))) // Power of 2
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000945 return BinaryOperator::createAnd(I.getOperand(0),
Chris Lattner3082c5a2003-02-18 19:28:33 +0000946 ConstantUInt::get(I.getType(), Val-1));
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000947 if (isa<PHINode>(I.getOperand(0)) && !RHS->isNullValue())
948 if (Instruction *NV = FoldOpIntoPhi(I))
949 return NV;
Chris Lattner3082c5a2003-02-18 19:28:33 +0000950 }
951
952 // 0 % X == 0, we don't need to preserve faults!
953 if (ConstantInt *LHS = dyn_cast<ConstantInt>(I.getOperand(0)))
954 if (LHS->equalsInt(0))
Chris Lattnere6794492002-08-12 21:17:25 +0000955 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
956
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000957 return 0;
958}
959
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000960// isMaxValueMinusOne - return true if this is Max-1
Chris Lattnere6794492002-08-12 21:17:25 +0000961static bool isMaxValueMinusOne(const ConstantInt *C) {
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000962 if (const ConstantUInt *CU = dyn_cast<ConstantUInt>(C)) {
963 // Calculate -1 casted to the right type...
964 unsigned TypeBits = C->getType()->getPrimitiveSize()*8;
965 uint64_t Val = ~0ULL; // All ones
966 Val >>= 64-TypeBits; // Shift out unwanted 1 bits...
967 return CU->getValue() == Val-1;
968 }
969
970 const ConstantSInt *CS = cast<ConstantSInt>(C);
971
972 // Calculate 0111111111..11111
973 unsigned TypeBits = C->getType()->getPrimitiveSize()*8;
974 int64_t Val = INT64_MAX; // All ones
975 Val >>= 64-TypeBits; // Shift out unwanted 1 bits...
976 return CS->getValue() == Val-1;
977}
978
979// isMinValuePlusOne - return true if this is Min+1
Chris Lattnere6794492002-08-12 21:17:25 +0000980static bool isMinValuePlusOne(const ConstantInt *C) {
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000981 if (const ConstantUInt *CU = dyn_cast<ConstantUInt>(C))
982 return CU->getValue() == 1;
983
984 const ConstantSInt *CS = cast<ConstantSInt>(C);
985
986 // Calculate 1111111111000000000000
987 unsigned TypeBits = C->getType()->getPrimitiveSize()*8;
988 int64_t Val = -1; // All ones
989 Val <<= TypeBits-1; // Shift over to the right spot
990 return CS->getValue() == Val+1;
991}
992
Chris Lattner35167c32004-06-09 07:59:58 +0000993// isOneBitSet - Return true if there is exactly one bit set in the specified
994// constant.
995static bool isOneBitSet(const ConstantInt *CI) {
996 uint64_t V = CI->getRawValue();
997 return V && (V & (V-1)) == 0;
998}
999
Chris Lattner8fc5af42004-09-23 21:46:38 +00001000#if 0 // Currently unused
1001// isLowOnes - Return true if the constant is of the form 0+1+.
1002static bool isLowOnes(const ConstantInt *CI) {
1003 uint64_t V = CI->getRawValue();
1004
1005 // There won't be bits set in parts that the type doesn't contain.
1006 V &= ConstantInt::getAllOnesValue(CI->getType())->getRawValue();
1007
1008 uint64_t U = V+1; // If it is low ones, this should be a power of two.
1009 return U && V && (U & V) == 0;
1010}
1011#endif
1012
1013// isHighOnes - Return true if the constant is of the form 1+0+.
1014// This is the same as lowones(~X).
1015static bool isHighOnes(const ConstantInt *CI) {
1016 uint64_t V = ~CI->getRawValue();
1017
1018 // There won't be bits set in parts that the type doesn't contain.
1019 V &= ConstantInt::getAllOnesValue(CI->getType())->getRawValue();
1020
1021 uint64_t U = V+1; // If it is low ones, this should be a power of two.
1022 return U && V && (U & V) == 0;
1023}
1024
1025
Chris Lattner3ac7c262003-08-13 20:16:26 +00001026/// getSetCondCode - Encode a setcc opcode into a three bit mask. These bits
1027/// are carefully arranged to allow folding of expressions such as:
1028///
1029/// (A < B) | (A > B) --> (A != B)
1030///
1031/// Bit value '4' represents that the comparison is true if A > B, bit value '2'
1032/// represents that the comparison is true if A == B, and bit value '1' is true
1033/// if A < B.
1034///
1035static unsigned getSetCondCode(const SetCondInst *SCI) {
1036 switch (SCI->getOpcode()) {
1037 // False -> 0
1038 case Instruction::SetGT: return 1;
1039 case Instruction::SetEQ: return 2;
1040 case Instruction::SetGE: return 3;
1041 case Instruction::SetLT: return 4;
1042 case Instruction::SetNE: return 5;
1043 case Instruction::SetLE: return 6;
1044 // True -> 7
1045 default:
1046 assert(0 && "Invalid SetCC opcode!");
1047 return 0;
1048 }
1049}
1050
1051/// getSetCCValue - This is the complement of getSetCondCode, which turns an
1052/// opcode and two operands into either a constant true or false, or a brand new
1053/// SetCC instruction.
1054static Value *getSetCCValue(unsigned Opcode, Value *LHS, Value *RHS) {
1055 switch (Opcode) {
1056 case 0: return ConstantBool::False;
1057 case 1: return new SetCondInst(Instruction::SetGT, LHS, RHS);
1058 case 2: return new SetCondInst(Instruction::SetEQ, LHS, RHS);
1059 case 3: return new SetCondInst(Instruction::SetGE, LHS, RHS);
1060 case 4: return new SetCondInst(Instruction::SetLT, LHS, RHS);
1061 case 5: return new SetCondInst(Instruction::SetNE, LHS, RHS);
1062 case 6: return new SetCondInst(Instruction::SetLE, LHS, RHS);
1063 case 7: return ConstantBool::True;
1064 default: assert(0 && "Illegal SetCCCode!"); return 0;
1065 }
1066}
1067
1068// FoldSetCCLogical - Implements (setcc1 A, B) & (setcc2 A, B) --> (setcc3 A, B)
1069struct FoldSetCCLogical {
1070 InstCombiner &IC;
1071 Value *LHS, *RHS;
1072 FoldSetCCLogical(InstCombiner &ic, SetCondInst *SCI)
1073 : IC(ic), LHS(SCI->getOperand(0)), RHS(SCI->getOperand(1)) {}
1074 bool shouldApply(Value *V) const {
1075 if (SetCondInst *SCI = dyn_cast<SetCondInst>(V))
1076 return (SCI->getOperand(0) == LHS && SCI->getOperand(1) == RHS ||
1077 SCI->getOperand(0) == RHS && SCI->getOperand(1) == LHS);
1078 return false;
1079 }
1080 Instruction *apply(BinaryOperator &Log) const {
1081 SetCondInst *SCI = cast<SetCondInst>(Log.getOperand(0));
1082 if (SCI->getOperand(0) != LHS) {
1083 assert(SCI->getOperand(1) == LHS);
1084 SCI->swapOperands(); // Swap the LHS and RHS of the SetCC
1085 }
1086
1087 unsigned LHSCode = getSetCondCode(SCI);
1088 unsigned RHSCode = getSetCondCode(cast<SetCondInst>(Log.getOperand(1)));
1089 unsigned Code;
1090 switch (Log.getOpcode()) {
1091 case Instruction::And: Code = LHSCode & RHSCode; break;
1092 case Instruction::Or: Code = LHSCode | RHSCode; break;
1093 case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
Chris Lattner2caaaba2003-09-22 20:33:34 +00001094 default: assert(0 && "Illegal logical opcode!"); return 0;
Chris Lattner3ac7c262003-08-13 20:16:26 +00001095 }
1096
1097 Value *RV = getSetCCValue(Code, LHS, RHS);
1098 if (Instruction *I = dyn_cast<Instruction>(RV))
1099 return I;
1100 // Otherwise, it's a constant boolean value...
1101 return IC.ReplaceInstUsesWith(Log, RV);
1102 }
1103};
1104
1105
Chris Lattnerba1cb382003-09-19 17:17:26 +00001106// OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
1107// the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
1108// guaranteed to be either a shift instruction or a binary operator.
1109Instruction *InstCombiner::OptAndOp(Instruction *Op,
1110 ConstantIntegral *OpRHS,
1111 ConstantIntegral *AndRHS,
1112 BinaryOperator &TheAnd) {
1113 Value *X = Op->getOperand(0);
Chris Lattnerfcf21a72004-01-12 19:47:05 +00001114 Constant *Together = 0;
1115 if (!isa<ShiftInst>(Op))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001116 Together = ConstantExpr::getAnd(AndRHS, OpRHS);
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00001117
Chris Lattnerba1cb382003-09-19 17:17:26 +00001118 switch (Op->getOpcode()) {
1119 case Instruction::Xor:
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00001120 if (Together->isNullValue()) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00001121 // (X ^ C1) & C2 --> (X & C2) iff (C1&C2) == 0
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001122 return BinaryOperator::createAnd(X, AndRHS);
Chris Lattnerf95d9b92003-10-15 16:48:29 +00001123 } else if (Op->hasOneUse()) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00001124 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
1125 std::string OpName = Op->getName(); Op->setName("");
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001126 Instruction *And = BinaryOperator::createAnd(X, AndRHS, OpName);
Chris Lattnerba1cb382003-09-19 17:17:26 +00001127 InsertNewInstBefore(And, TheAnd);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001128 return BinaryOperator::createXor(And, Together);
Chris Lattnerba1cb382003-09-19 17:17:26 +00001129 }
1130 break;
1131 case Instruction::Or:
1132 // (X | C1) & C2 --> X & C2 iff C1 & C1 == 0
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00001133 if (Together->isNullValue())
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001134 return BinaryOperator::createAnd(X, AndRHS);
Chris Lattnerba1cb382003-09-19 17:17:26 +00001135 else {
Chris Lattnerba1cb382003-09-19 17:17:26 +00001136 if (Together == AndRHS) // (X | C) & C --> C
1137 return ReplaceInstUsesWith(TheAnd, AndRHS);
1138
Chris Lattnerf95d9b92003-10-15 16:48:29 +00001139 if (Op->hasOneUse() && Together != OpRHS) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00001140 // (X | C1) & C2 --> (X | (C1&C2)) & C2
1141 std::string Op0Name = Op->getName(); Op->setName("");
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001142 Instruction *Or = BinaryOperator::createOr(X, Together, Op0Name);
Chris Lattnerba1cb382003-09-19 17:17:26 +00001143 InsertNewInstBefore(Or, TheAnd);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001144 return BinaryOperator::createAnd(Or, AndRHS);
Chris Lattnerba1cb382003-09-19 17:17:26 +00001145 }
1146 }
1147 break;
1148 case Instruction::Add:
Chris Lattnerf95d9b92003-10-15 16:48:29 +00001149 if (Op->hasOneUse()) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00001150 // Adding a one to a single bit bit-field should be turned into an XOR
1151 // of the bit. First thing to check is to see if this AND is with a
1152 // single bit constant.
Chris Lattner35167c32004-06-09 07:59:58 +00001153 uint64_t AndRHSV = cast<ConstantInt>(AndRHS)->getRawValue();
Chris Lattnerba1cb382003-09-19 17:17:26 +00001154
1155 // Clear bits that are not part of the constant.
1156 AndRHSV &= (1ULL << AndRHS->getType()->getPrimitiveSize()*8)-1;
1157
1158 // If there is only one bit set...
Chris Lattner35167c32004-06-09 07:59:58 +00001159 if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00001160 // Ok, at this point, we know that we are masking the result of the
1161 // ADD down to exactly one bit. If the constant we are adding has
1162 // no bits set below this bit, then we can eliminate the ADD.
Chris Lattner35167c32004-06-09 07:59:58 +00001163 uint64_t AddRHS = cast<ConstantInt>(OpRHS)->getRawValue();
Chris Lattnerba1cb382003-09-19 17:17:26 +00001164
1165 // Check to see if any bits below the one bit set in AndRHSV are set.
1166 if ((AddRHS & (AndRHSV-1)) == 0) {
1167 // If not, the only thing that can effect the output of the AND is
1168 // the bit specified by AndRHSV. If that bit is set, the effect of
1169 // the XOR is to toggle the bit. If it is clear, then the ADD has
1170 // no effect.
1171 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
1172 TheAnd.setOperand(0, X);
1173 return &TheAnd;
1174 } else {
1175 std::string Name = Op->getName(); Op->setName("");
1176 // Pull the XOR out of the AND.
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001177 Instruction *NewAnd = BinaryOperator::createAnd(X, AndRHS, Name);
Chris Lattnerba1cb382003-09-19 17:17:26 +00001178 InsertNewInstBefore(NewAnd, TheAnd);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001179 return BinaryOperator::createXor(NewAnd, AndRHS);
Chris Lattnerba1cb382003-09-19 17:17:26 +00001180 }
1181 }
1182 }
1183 }
1184 break;
Chris Lattner2da29172003-09-19 19:05:02 +00001185
1186 case Instruction::Shl: {
1187 // We know that the AND will not produce any of the bits shifted in, so if
1188 // the anded constant includes them, clear them now!
1189 //
1190 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
Chris Lattner7e794272004-09-24 15:21:34 +00001191 Constant *ShlMask = ConstantExpr::getShl(AllOne, OpRHS);
1192 Constant *CI = ConstantExpr::getAnd(AndRHS, ShlMask);
1193
1194 if (CI == ShlMask) { // Masking out bits that the shift already masks
1195 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
1196 } else if (CI != AndRHS) { // Reducing bits set in and.
Chris Lattner2da29172003-09-19 19:05:02 +00001197 TheAnd.setOperand(1, CI);
1198 return &TheAnd;
1199 }
1200 break;
1201 }
1202 case Instruction::Shr:
1203 // We know that the AND will not produce any of the bits shifted in, so if
1204 // the anded constant includes them, clear them now! This only applies to
1205 // unsigned shifts, because a signed shr may bring in set bits!
1206 //
1207 if (AndRHS->getType()->isUnsigned()) {
1208 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
Chris Lattner7e794272004-09-24 15:21:34 +00001209 Constant *ShrMask = ConstantExpr::getShr(AllOne, OpRHS);
1210 Constant *CI = ConstantExpr::getAnd(AndRHS, ShrMask);
1211
1212 if (CI == ShrMask) { // Masking out bits that the shift already masks.
1213 return ReplaceInstUsesWith(TheAnd, Op);
1214 } else if (CI != AndRHS) {
1215 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
Chris Lattner2da29172003-09-19 19:05:02 +00001216 return &TheAnd;
1217 }
Chris Lattner7e794272004-09-24 15:21:34 +00001218 } else { // Signed shr.
1219 // See if this is shifting in some sign extension, then masking it out
1220 // with an and.
1221 if (Op->hasOneUse()) {
1222 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
1223 Constant *ShrMask = ConstantExpr::getUShr(AllOne, OpRHS);
1224 Constant *CI = ConstantExpr::getAnd(AndRHS, ShrMask);
1225 if (CI == ShrMask) { // Masking out bits shifted in.
1226 // Make the argument unsigned.
1227 Value *ShVal = Op->getOperand(0);
1228 ShVal = InsertCastBefore(ShVal,
1229 ShVal->getType()->getUnsignedVersion(),
1230 TheAnd);
1231 ShVal = InsertNewInstBefore(new ShiftInst(Instruction::Shr, ShVal,
1232 OpRHS, Op->getName()),
1233 TheAnd);
1234 return new CastInst(ShVal, Op->getType());
1235 }
1236 }
Chris Lattner2da29172003-09-19 19:05:02 +00001237 }
1238 break;
Chris Lattnerba1cb382003-09-19 17:17:26 +00001239 }
1240 return 0;
1241}
1242
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001243
Chris Lattner113f4f42002-06-25 16:13:24 +00001244Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00001245 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00001246 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001247
1248 // and X, X = X and X, 0 == 0
Chris Lattnere6794492002-08-12 21:17:25 +00001249 if (Op0 == Op1 || Op1 == Constant::getNullValue(I.getType()))
1250 return ReplaceInstUsesWith(I, Op1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001251
1252 // and X, -1 == X
Chris Lattner49b47ae2003-07-23 17:57:01 +00001253 if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
Chris Lattnere6794492002-08-12 21:17:25 +00001254 if (RHS->isAllOnesValue())
1255 return ReplaceInstUsesWith(I, Op0);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001256
Chris Lattnerba1cb382003-09-19 17:17:26 +00001257 // Optimize a variety of ((val OP C1) & C2) combinations...
1258 if (isa<BinaryOperator>(Op0) || isa<ShiftInst>(Op0)) {
1259 Instruction *Op0I = cast<Instruction>(Op0);
Chris Lattner33217db2003-07-23 19:36:21 +00001260 Value *X = Op0I->getOperand(0);
Chris Lattner16464b32003-07-23 19:25:52 +00001261 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattnerba1cb382003-09-19 17:17:26 +00001262 if (Instruction *Res = OptAndOp(Op0I, Op0CI, RHS, I))
1263 return Res;
Chris Lattner33217db2003-07-23 19:36:21 +00001264 }
Chris Lattner183b3362004-04-09 19:05:30 +00001265
1266 // Try to fold constant and into select arguments.
1267 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
1268 if (Instruction *R = FoldBinOpIntoSelect(I, SI, this))
1269 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001270 if (isa<PHINode>(Op0))
1271 if (Instruction *NV = FoldOpIntoPhi(I))
1272 return NV;
Chris Lattner49b47ae2003-07-23 17:57:01 +00001273 }
1274
Chris Lattnerbb74e222003-03-10 23:06:50 +00001275 Value *Op0NotVal = dyn_castNotVal(Op0);
1276 Value *Op1NotVal = dyn_castNotVal(Op1);
Chris Lattner3082c5a2003-02-18 19:28:33 +00001277
Chris Lattner023a4832004-06-18 06:07:51 +00001278 if (Op0NotVal == Op1 || Op1NotVal == Op0) // A & ~A == ~A & A == 0
1279 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1280
Misha Brukman9c003d82004-07-30 12:50:08 +00001281 // (~A & ~B) == (~(A | B)) - De Morgan's Law
Chris Lattnerbb74e222003-03-10 23:06:50 +00001282 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001283 Instruction *Or = BinaryOperator::createOr(Op0NotVal, Op1NotVal,
1284 I.getName()+".demorgan");
Chris Lattner49b47ae2003-07-23 17:57:01 +00001285 InsertNewInstBefore(Or, I);
Chris Lattner3082c5a2003-02-18 19:28:33 +00001286 return BinaryOperator::createNot(Or);
1287 }
1288
Chris Lattner623826c2004-09-28 21:48:02 +00001289 if (SetCondInst *RHS = dyn_cast<SetCondInst>(Op1)) {
1290 // (setcc1 A, B) & (setcc2 A, B) --> (setcc3 A, B)
Chris Lattner3ac7c262003-08-13 20:16:26 +00001291 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
1292 return R;
1293
Chris Lattner623826c2004-09-28 21:48:02 +00001294 Value *LHSVal, *RHSVal;
1295 ConstantInt *LHSCst, *RHSCst;
1296 Instruction::BinaryOps LHSCC, RHSCC;
1297 if (match(Op0, m_SetCond(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
1298 if (match(RHS, m_SetCond(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
1299 if (LHSVal == RHSVal && // Found (X setcc C1) & (X setcc C2)
1300 // Set[GL]E X, CST is folded to Set[GL]T elsewhere.
1301 LHSCC != Instruction::SetGE && LHSCC != Instruction::SetLE &&
1302 RHSCC != Instruction::SetGE && RHSCC != Instruction::SetLE) {
1303 // Ensure that the larger constant is on the RHS.
1304 Constant *Cmp = ConstantExpr::getSetGT(LHSCst, RHSCst);
1305 SetCondInst *LHS = cast<SetCondInst>(Op0);
1306 if (cast<ConstantBool>(Cmp)->getValue()) {
1307 std::swap(LHS, RHS);
1308 std::swap(LHSCst, RHSCst);
1309 std::swap(LHSCC, RHSCC);
1310 }
1311
1312 // At this point, we know we have have two setcc instructions
1313 // comparing a value against two constants and and'ing the result
1314 // together. Because of the above check, we know that we only have
1315 // SetEQ, SetNE, SetLT, and SetGT here. We also know (from the
1316 // FoldSetCCLogical check above), that the two constants are not
1317 // equal.
1318 assert(LHSCst != RHSCst && "Compares not folded above?");
1319
1320 switch (LHSCC) {
1321 default: assert(0 && "Unknown integer condition code!");
1322 case Instruction::SetEQ:
1323 switch (RHSCC) {
1324 default: assert(0 && "Unknown integer condition code!");
1325 case Instruction::SetEQ: // (X == 13 & X == 15) -> false
1326 case Instruction::SetGT: // (X == 13 & X > 15) -> false
1327 return ReplaceInstUsesWith(I, ConstantBool::False);
1328 case Instruction::SetNE: // (X == 13 & X != 15) -> X == 13
1329 case Instruction::SetLT: // (X == 13 & X < 15) -> X == 13
1330 return ReplaceInstUsesWith(I, LHS);
1331 }
1332 case Instruction::SetNE:
1333 switch (RHSCC) {
1334 default: assert(0 && "Unknown integer condition code!");
1335 case Instruction::SetLT:
1336 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X < 14) -> X < 13
1337 return new SetCondInst(Instruction::SetLT, LHSVal, LHSCst);
1338 break; // (X != 13 & X < 15) -> no change
1339 case Instruction::SetEQ: // (X != 13 & X == 15) -> X == 15
1340 case Instruction::SetGT: // (X != 13 & X > 15) -> X > 15
1341 return ReplaceInstUsesWith(I, RHS);
1342 case Instruction::SetNE:
1343 if (LHSCst == SubOne(RHSCst)) {// (X != 13 & X != 14) -> X-13 >u 1
1344 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
1345 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
1346 LHSVal->getName()+".off");
1347 InsertNewInstBefore(Add, I);
1348 const Type *UnsType = Add->getType()->getUnsignedVersion();
1349 Value *OffsetVal = InsertCastBefore(Add, UnsType, I);
1350 AddCST = ConstantExpr::getSub(RHSCst, LHSCst);
1351 AddCST = ConstantExpr::getCast(AddCST, UnsType);
1352 return new SetCondInst(Instruction::SetGT, OffsetVal, AddCST);
1353 }
1354 break; // (X != 13 & X != 15) -> no change
1355 }
1356 break;
1357 case Instruction::SetLT:
1358 switch (RHSCC) {
1359 default: assert(0 && "Unknown integer condition code!");
1360 case Instruction::SetEQ: // (X < 13 & X == 15) -> false
1361 case Instruction::SetGT: // (X < 13 & X > 15) -> false
1362 return ReplaceInstUsesWith(I, ConstantBool::False);
1363 case Instruction::SetNE: // (X < 13 & X != 15) -> X < 13
1364 case Instruction::SetLT: // (X < 13 & X < 15) -> X < 13
1365 return ReplaceInstUsesWith(I, LHS);
1366 }
1367 case Instruction::SetGT:
1368 switch (RHSCC) {
1369 default: assert(0 && "Unknown integer condition code!");
1370 case Instruction::SetEQ: // (X > 13 & X == 15) -> X > 13
1371 return ReplaceInstUsesWith(I, LHS);
1372 case Instruction::SetGT: // (X > 13 & X > 15) -> X > 15
1373 return ReplaceInstUsesWith(I, RHS);
1374 case Instruction::SetNE:
1375 if (RHSCst == AddOne(LHSCst)) // (X > 13 & X != 14) -> X > 14
1376 return new SetCondInst(Instruction::SetGT, LHSVal, RHSCst);
1377 break; // (X > 13 & X != 15) -> no change
1378 case Instruction::SetLT: { // (X > 13 & X < 15) -> (X-14) <u 1
1379 Constant *AddCST = ConstantExpr::getNeg(AddOne(LHSCst));
1380 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
1381 LHSVal->getName()+".off");
1382 InsertNewInstBefore(Add, I);
1383 // Convert to unsigned for the comparison.
1384 const Type *UnsType = Add->getType()->getUnsignedVersion();
1385 Value *OffsetVal = InsertCastBefore(Add, UnsType, I);
1386 AddCST = ConstantExpr::getAdd(AddCST, RHSCst);
1387 AddCST = ConstantExpr::getCast(AddCST, UnsType);
1388 return new SetCondInst(Instruction::SetLT, OffsetVal, AddCST);
1389 }
1390 break;
1391 }
1392 }
1393 }
1394 }
1395
Chris Lattner113f4f42002-06-25 16:13:24 +00001396 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001397}
1398
1399
1400
Chris Lattner113f4f42002-06-25 16:13:24 +00001401Instruction *InstCombiner::visitOr(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00001402 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00001403 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001404
1405 // or X, X = X or X, 0 == X
Chris Lattnere6794492002-08-12 21:17:25 +00001406 if (Op0 == Op1 || Op1 == Constant::getNullValue(I.getType()))
1407 return ReplaceInstUsesWith(I, Op0);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001408
1409 // or X, -1 == -1
Chris Lattner8f0d1562003-07-23 18:29:44 +00001410 if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
Chris Lattnere6794492002-08-12 21:17:25 +00001411 if (RHS->isAllOnesValue())
1412 return ReplaceInstUsesWith(I, Op1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001413
Chris Lattnerd4252a72004-07-30 07:50:03 +00001414 ConstantInt *C1; Value *X;
1415 // (X & C1) | C2 --> (X | C2) & (C1|C2)
1416 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
1417 std::string Op0Name = Op0->getName(); Op0->setName("");
1418 Instruction *Or = BinaryOperator::createOr(X, RHS, Op0Name);
1419 InsertNewInstBefore(Or, I);
1420 return BinaryOperator::createAnd(Or, ConstantExpr::getOr(RHS, C1));
1421 }
Chris Lattner8f0d1562003-07-23 18:29:44 +00001422
Chris Lattnerd4252a72004-07-30 07:50:03 +00001423 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
1424 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
1425 std::string Op0Name = Op0->getName(); Op0->setName("");
1426 Instruction *Or = BinaryOperator::createOr(X, RHS, Op0Name);
1427 InsertNewInstBefore(Or, I);
1428 return BinaryOperator::createXor(Or,
1429 ConstantExpr::getAnd(C1, ConstantExpr::getNot(RHS)));
Chris Lattner8f0d1562003-07-23 18:29:44 +00001430 }
Chris Lattner183b3362004-04-09 19:05:30 +00001431
1432 // Try to fold constant and into select arguments.
1433 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
1434 if (Instruction *R = FoldBinOpIntoSelect(I, SI, this))
1435 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001436 if (isa<PHINode>(Op0))
1437 if (Instruction *NV = FoldOpIntoPhi(I))
1438 return NV;
Chris Lattner8f0d1562003-07-23 18:29:44 +00001439 }
1440
Chris Lattner812aab72003-08-12 19:11:07 +00001441 // (A & C1)|(A & C2) == A & (C1|C2)
Chris Lattnerd4252a72004-07-30 07:50:03 +00001442 Value *A, *B; ConstantInt *C1, *C2;
1443 if (match(Op0, m_And(m_Value(A), m_ConstantInt(C1))) &&
1444 match(Op1, m_And(m_Value(B), m_ConstantInt(C2))) && A == B)
1445 return BinaryOperator::createAnd(A, ConstantExpr::getOr(C1, C2));
Chris Lattner812aab72003-08-12 19:11:07 +00001446
Chris Lattnerd4252a72004-07-30 07:50:03 +00001447 if (match(Op0, m_Not(m_Value(A)))) { // ~A | Op1
1448 if (A == Op1) // ~A | A == -1
1449 return ReplaceInstUsesWith(I,
1450 ConstantIntegral::getAllOnesValue(I.getType()));
1451 } else {
1452 A = 0;
1453 }
Chris Lattner3082c5a2003-02-18 19:28:33 +00001454
Chris Lattnerd4252a72004-07-30 07:50:03 +00001455 if (match(Op1, m_Not(m_Value(B)))) { // Op0 | ~B
1456 if (Op0 == B)
1457 return ReplaceInstUsesWith(I,
1458 ConstantIntegral::getAllOnesValue(I.getType()));
Chris Lattner3e327a42003-03-10 23:13:59 +00001459
Misha Brukman9c003d82004-07-30 12:50:08 +00001460 // (~A | ~B) == (~(A & B)) - De Morgan's Law
Chris Lattnerd4252a72004-07-30 07:50:03 +00001461 if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
1462 Value *And = InsertNewInstBefore(BinaryOperator::createAnd(A, B,
1463 I.getName()+".demorgan"), I);
1464 return BinaryOperator::createNot(And);
1465 }
Chris Lattner3e327a42003-03-10 23:13:59 +00001466 }
Chris Lattner3082c5a2003-02-18 19:28:33 +00001467
Chris Lattner3ac7c262003-08-13 20:16:26 +00001468 // (setcc1 A, B) | (setcc2 A, B) --> (setcc3 A, B)
Chris Lattnerdcf756e2004-09-28 22:33:08 +00001469 if (SetCondInst *RHS = dyn_cast<SetCondInst>(I.getOperand(1))) {
Chris Lattner3ac7c262003-08-13 20:16:26 +00001470 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
1471 return R;
1472
Chris Lattnerdcf756e2004-09-28 22:33:08 +00001473 Value *LHSVal, *RHSVal;
1474 ConstantInt *LHSCst, *RHSCst;
1475 Instruction::BinaryOps LHSCC, RHSCC;
1476 if (match(Op0, m_SetCond(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
1477 if (match(RHS, m_SetCond(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
1478 if (LHSVal == RHSVal && // Found (X setcc C1) | (X setcc C2)
1479 // Set[GL]E X, CST is folded to Set[GL]T elsewhere.
1480 LHSCC != Instruction::SetGE && LHSCC != Instruction::SetLE &&
1481 RHSCC != Instruction::SetGE && RHSCC != Instruction::SetLE) {
1482 // Ensure that the larger constant is on the RHS.
1483 Constant *Cmp = ConstantExpr::getSetGT(LHSCst, RHSCst);
1484 SetCondInst *LHS = cast<SetCondInst>(Op0);
1485 if (cast<ConstantBool>(Cmp)->getValue()) {
1486 std::swap(LHS, RHS);
1487 std::swap(LHSCst, RHSCst);
1488 std::swap(LHSCC, RHSCC);
1489 }
1490
1491 // At this point, we know we have have two setcc instructions
1492 // comparing a value against two constants and or'ing the result
1493 // together. Because of the above check, we know that we only have
1494 // SetEQ, SetNE, SetLT, and SetGT here. We also know (from the
1495 // FoldSetCCLogical check above), that the two constants are not
1496 // equal.
1497 assert(LHSCst != RHSCst && "Compares not folded above?");
1498
1499 switch (LHSCC) {
1500 default: assert(0 && "Unknown integer condition code!");
1501 case Instruction::SetEQ:
1502 switch (RHSCC) {
1503 default: assert(0 && "Unknown integer condition code!");
1504 case Instruction::SetEQ:
1505 if (LHSCst == SubOne(RHSCst)) {// (X == 13 | X == 14) -> X-13 <u 2
1506 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
1507 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
1508 LHSVal->getName()+".off");
1509 InsertNewInstBefore(Add, I);
1510 const Type *UnsType = Add->getType()->getUnsignedVersion();
1511 Value *OffsetVal = InsertCastBefore(Add, UnsType, I);
1512 AddCST = ConstantExpr::getSub(AddOne(RHSCst), LHSCst);
1513 AddCST = ConstantExpr::getCast(AddCST, UnsType);
1514 return new SetCondInst(Instruction::SetLT, OffsetVal, AddCST);
1515 }
1516 break; // (X == 13 | X == 15) -> no change
1517
1518 case Instruction::SetGT:
1519 if (LHSCst == SubOne(RHSCst)) // (X == 13 | X > 14) -> X > 13
1520 return new SetCondInst(Instruction::SetGT, LHSVal, LHSCst);
1521 break; // (X == 13 | X > 15) -> no change
1522 case Instruction::SetNE: // (X == 13 | X != 15) -> X != 15
1523 case Instruction::SetLT: // (X == 13 | X < 15) -> X < 15
1524 return ReplaceInstUsesWith(I, RHS);
1525 }
1526 break;
1527 case Instruction::SetNE:
1528 switch (RHSCC) {
1529 default: assert(0 && "Unknown integer condition code!");
1530 case Instruction::SetLT: // (X != 13 | X < 15) -> X < 15
1531 return ReplaceInstUsesWith(I, RHS);
1532 case Instruction::SetEQ: // (X != 13 | X == 15) -> X != 13
1533 case Instruction::SetGT: // (X != 13 | X > 15) -> X != 13
1534 return ReplaceInstUsesWith(I, LHS);
1535 case Instruction::SetNE: // (X != 13 | X != 15) -> true
1536 return ReplaceInstUsesWith(I, ConstantBool::True);
1537 }
1538 break;
1539 case Instruction::SetLT:
1540 switch (RHSCC) {
1541 default: assert(0 && "Unknown integer condition code!");
1542 case Instruction::SetEQ: // (X < 13 | X == 14) -> no change
1543 break;
1544 case Instruction::SetGT: {// (X < 13 | X > 15) -> (X-13) > 2
1545 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
1546 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
1547 LHSVal->getName()+".off");
1548 InsertNewInstBefore(Add, I);
1549 // Convert to unsigned for the comparison.
1550 const Type *UnsType = Add->getType()->getUnsignedVersion();
1551 Value *OffsetVal = InsertCastBefore(Add, UnsType, I);
1552 AddCST = ConstantExpr::getAdd(AddCST, RHSCst);
1553 AddCST = ConstantExpr::getCast(AddCST, UnsType);
1554 return new SetCondInst(Instruction::SetGT, OffsetVal, AddCST);
1555 }
1556 case Instruction::SetNE: // (X < 13 | X != 15) -> X != 15
1557 case Instruction::SetLT: // (X < 13 | X < 15) -> X < 15
1558 return ReplaceInstUsesWith(I, RHS);
1559 }
1560 break;
1561 case Instruction::SetGT:
1562 switch (RHSCC) {
1563 default: assert(0 && "Unknown integer condition code!");
1564 case Instruction::SetEQ: // (X > 13 | X == 15) -> X > 13
1565 case Instruction::SetGT: // (X > 13 | X > 15) -> X > 13
1566 return ReplaceInstUsesWith(I, LHS);
1567 case Instruction::SetNE: // (X > 13 | X != 15) -> true
1568 case Instruction::SetLT: // (X > 13 | X < 15) -> true
1569 return ReplaceInstUsesWith(I, ConstantBool::True);
1570 }
1571 }
1572 }
1573 }
Chris Lattner113f4f42002-06-25 16:13:24 +00001574 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001575}
1576
Chris Lattnerc2076352004-02-16 01:20:27 +00001577// XorSelf - Implements: X ^ X --> 0
1578struct XorSelf {
1579 Value *RHS;
1580 XorSelf(Value *rhs) : RHS(rhs) {}
1581 bool shouldApply(Value *LHS) const { return LHS == RHS; }
1582 Instruction *apply(BinaryOperator &Xor) const {
1583 return &Xor;
1584 }
1585};
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001586
1587
Chris Lattner113f4f42002-06-25 16:13:24 +00001588Instruction *InstCombiner::visitXor(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00001589 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00001590 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001591
Chris Lattnerc2076352004-02-16 01:20:27 +00001592 // xor X, X = 0, even if X is nested in a sequence of Xor's.
1593 if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
1594 assert(Result == &I && "AssociativeOpt didn't work?");
Chris Lattnere6794492002-08-12 21:17:25 +00001595 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerc2076352004-02-16 01:20:27 +00001596 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001597
Chris Lattner97638592003-07-23 21:37:07 +00001598 if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001599 // xor X, 0 == X
Chris Lattner97638592003-07-23 21:37:07 +00001600 if (RHS->isNullValue())
Chris Lattnere6794492002-08-12 21:17:25 +00001601 return ReplaceInstUsesWith(I, Op0);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001602
Chris Lattner97638592003-07-23 21:37:07 +00001603 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Chris Lattnerb8d6e402002-08-20 18:24:26 +00001604 // xor (setcc A, B), true = not (setcc A, B) = setncc A, B
Chris Lattner97638592003-07-23 21:37:07 +00001605 if (SetCondInst *SCI = dyn_cast<SetCondInst>(Op0I))
Chris Lattnerf95d9b92003-10-15 16:48:29 +00001606 if (RHS == ConstantBool::True && SCI->hasOneUse())
Chris Lattnerb8d6e402002-08-20 18:24:26 +00001607 return new SetCondInst(SCI->getInverseCondition(),
1608 SCI->getOperand(0), SCI->getOperand(1));
Chris Lattnere5806662003-11-04 23:50:51 +00001609
Chris Lattner8f2f5982003-11-05 01:06:05 +00001610 // ~(c-X) == X-c-1 == X+(-c-1)
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00001611 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
1612 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001613 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
1614 Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00001615 ConstantInt::get(I.getType(), 1));
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001616 return BinaryOperator::createAdd(Op0I->getOperand(1), ConstantRHS);
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00001617 }
Chris Lattner023a4832004-06-18 06:07:51 +00001618
1619 // ~(~X & Y) --> (X | ~Y)
1620 if (Op0I->getOpcode() == Instruction::And && RHS->isAllOnesValue()) {
1621 if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
1622 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
1623 Instruction *NotY =
1624 BinaryOperator::createNot(Op0I->getOperand(1),
1625 Op0I->getOperand(1)->getName()+".not");
1626 InsertNewInstBefore(NotY, I);
1627 return BinaryOperator::createOr(Op0NotVal, NotY);
1628 }
1629 }
Chris Lattner97638592003-07-23 21:37:07 +00001630
1631 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattnere5806662003-11-04 23:50:51 +00001632 switch (Op0I->getOpcode()) {
1633 case Instruction::Add:
Chris Lattner0f68fa62003-11-04 23:37:10 +00001634 // ~(X-c) --> (-c-1)-X
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00001635 if (RHS->isAllOnesValue()) {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001636 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
1637 return BinaryOperator::createSub(
1638 ConstantExpr::getSub(NegOp0CI,
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00001639 ConstantInt::get(I.getType(), 1)),
Chris Lattner0f68fa62003-11-04 23:37:10 +00001640 Op0I->getOperand(0));
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00001641 }
Chris Lattnere5806662003-11-04 23:50:51 +00001642 break;
1643 case Instruction::And:
Chris Lattner97638592003-07-23 21:37:07 +00001644 // (X & C1) ^ C2 --> (X & C1) | C2 iff (C1&C2) == 0
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001645 if (ConstantExpr::getAnd(RHS, Op0CI)->isNullValue())
1646 return BinaryOperator::createOr(Op0, RHS);
Chris Lattnere5806662003-11-04 23:50:51 +00001647 break;
1648 case Instruction::Or:
Chris Lattner97638592003-07-23 21:37:07 +00001649 // (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001650 if (ConstantExpr::getAnd(RHS, Op0CI) == RHS)
Chris Lattnerc8e7e292004-06-10 02:12:35 +00001651 return BinaryOperator::createAnd(Op0, ConstantExpr::getNot(RHS));
Chris Lattnere5806662003-11-04 23:50:51 +00001652 break;
1653 default: break;
Chris Lattner97638592003-07-23 21:37:07 +00001654 }
Chris Lattnerb8d6e402002-08-20 18:24:26 +00001655 }
Chris Lattner183b3362004-04-09 19:05:30 +00001656
1657 // Try to fold constant and into select arguments.
1658 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
1659 if (Instruction *R = FoldBinOpIntoSelect(I, SI, this))
1660 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001661 if (isa<PHINode>(Op0))
1662 if (Instruction *NV = FoldOpIntoPhi(I))
1663 return NV;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001664 }
1665
Chris Lattnerbb74e222003-03-10 23:06:50 +00001666 if (Value *X = dyn_castNotVal(Op0)) // ~A ^ A == -1
Chris Lattner3082c5a2003-02-18 19:28:33 +00001667 if (X == Op1)
1668 return ReplaceInstUsesWith(I,
1669 ConstantIntegral::getAllOnesValue(I.getType()));
1670
Chris Lattnerbb74e222003-03-10 23:06:50 +00001671 if (Value *X = dyn_castNotVal(Op1)) // A ^ ~A == -1
Chris Lattner3082c5a2003-02-18 19:28:33 +00001672 if (X == Op0)
1673 return ReplaceInstUsesWith(I,
1674 ConstantIntegral::getAllOnesValue(I.getType()));
1675
Chris Lattner1bbb7b62003-03-10 18:24:17 +00001676 if (Instruction *Op1I = dyn_cast<Instruction>(Op1))
Chris Lattnerb36d9082004-02-16 03:54:20 +00001677 if (Op1I->getOpcode() == Instruction::Or) {
Chris Lattner1bbb7b62003-03-10 18:24:17 +00001678 if (Op1I->getOperand(0) == Op0) { // B^(B|A) == (A|B)^B
1679 cast<BinaryOperator>(Op1I)->swapOperands();
1680 I.swapOperands();
1681 std::swap(Op0, Op1);
1682 } else if (Op1I->getOperand(1) == Op0) { // B^(A|B) == (A|B)^B
1683 I.swapOperands();
1684 std::swap(Op0, Op1);
Chris Lattnerb36d9082004-02-16 03:54:20 +00001685 }
1686 } else if (Op1I->getOpcode() == Instruction::Xor) {
1687 if (Op0 == Op1I->getOperand(0)) // A^(A^B) == B
1688 return ReplaceInstUsesWith(I, Op1I->getOperand(1));
1689 else if (Op0 == Op1I->getOperand(1)) // A^(B^A) == B
1690 return ReplaceInstUsesWith(I, Op1I->getOperand(0));
1691 }
Chris Lattner1bbb7b62003-03-10 18:24:17 +00001692
1693 if (Instruction *Op0I = dyn_cast<Instruction>(Op0))
Chris Lattnerf95d9b92003-10-15 16:48:29 +00001694 if (Op0I->getOpcode() == Instruction::Or && Op0I->hasOneUse()) {
Chris Lattner1bbb7b62003-03-10 18:24:17 +00001695 if (Op0I->getOperand(0) == Op1) // (B|A)^B == (A|B)^B
1696 cast<BinaryOperator>(Op0I)->swapOperands();
Chris Lattnerdcf240a2003-03-10 21:43:22 +00001697 if (Op0I->getOperand(1) == Op1) { // (A|B)^B == A & ~B
Chris Lattner396dbfe2004-06-09 05:08:07 +00001698 Value *NotB = InsertNewInstBefore(BinaryOperator::createNot(Op1,
1699 Op1->getName()+".not"), I);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001700 return BinaryOperator::createAnd(Op0I->getOperand(0), NotB);
Chris Lattner1bbb7b62003-03-10 18:24:17 +00001701 }
Chris Lattnerb36d9082004-02-16 03:54:20 +00001702 } else if (Op0I->getOpcode() == Instruction::Xor) {
1703 if (Op1 == Op0I->getOperand(0)) // (A^B)^A == B
1704 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
1705 else if (Op1 == Op0I->getOperand(1)) // (B^A)^A == B
1706 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
Chris Lattner1bbb7b62003-03-10 18:24:17 +00001707 }
1708
Chris Lattner7aa2d472004-08-01 19:42:59 +00001709 // (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
Chris Lattnerd4252a72004-07-30 07:50:03 +00001710 Value *A, *B; ConstantInt *C1, *C2;
1711 if (match(Op0, m_And(m_Value(A), m_ConstantInt(C1))) &&
1712 match(Op1, m_And(m_Value(B), m_ConstantInt(C2))) &&
Chris Lattner7aa2d472004-08-01 19:42:59 +00001713 ConstantExpr::getAnd(C1, C2)->isNullValue())
Chris Lattnerd4252a72004-07-30 07:50:03 +00001714 return BinaryOperator::createOr(Op0, Op1);
Chris Lattner7fb29e12003-03-11 00:12:48 +00001715
Chris Lattner3ac7c262003-08-13 20:16:26 +00001716 // (setcc1 A, B) ^ (setcc2 A, B) --> (setcc3 A, B)
1717 if (SetCondInst *RHS = dyn_cast<SetCondInst>(I.getOperand(1)))
1718 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
1719 return R;
1720
Chris Lattner113f4f42002-06-25 16:13:24 +00001721 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001722}
1723
Chris Lattner113f4f42002-06-25 16:13:24 +00001724Instruction *InstCombiner::visitSetCondInst(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00001725 bool Changed = SimplifyCommutative(I);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001726 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1727 const Type *Ty = Op0->getType();
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001728
1729 // setcc X, X
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001730 if (Op0 == Op1)
1731 return ReplaceInstUsesWith(I, ConstantBool::get(isTrueWhenEqual(I)));
Chris Lattner1fc23f32002-05-09 20:11:54 +00001732
Chris Lattnerd07283a2003-08-13 05:38:46 +00001733 // setcc <global/alloca*>, 0 - Global/Stack value addresses are never null!
1734 if (isa<ConstantPointerNull>(Op1) &&
1735 (isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0)))
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001736 return ReplaceInstUsesWith(I, ConstantBool::get(!isTrueWhenEqual(I)));
1737
Chris Lattnerd07283a2003-08-13 05:38:46 +00001738
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001739 // setcc's with boolean values can always be turned into bitwise operations
1740 if (Ty == Type::BoolTy) {
Chris Lattner4456da62004-08-11 00:50:51 +00001741 switch (I.getOpcode()) {
1742 default: assert(0 && "Invalid setcc instruction!");
1743 case Instruction::SetEQ: { // seteq bool %A, %B -> ~(A^B)
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001744 Instruction *Xor = BinaryOperator::createXor(Op0, Op1, I.getName()+"tmp");
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001745 InsertNewInstBefore(Xor, I);
Chris Lattner16930792003-11-03 04:25:02 +00001746 return BinaryOperator::createNot(Xor);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001747 }
Chris Lattner4456da62004-08-11 00:50:51 +00001748 case Instruction::SetNE:
1749 return BinaryOperator::createXor(Op0, Op1);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001750
Chris Lattner4456da62004-08-11 00:50:51 +00001751 case Instruction::SetGT:
1752 std::swap(Op0, Op1); // Change setgt -> setlt
1753 // FALL THROUGH
1754 case Instruction::SetLT: { // setlt bool A, B -> ~X & Y
1755 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
1756 InsertNewInstBefore(Not, I);
1757 return BinaryOperator::createAnd(Not, Op1);
1758 }
1759 case Instruction::SetGE:
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001760 std::swap(Op0, Op1); // Change setge -> setle
Chris Lattner4456da62004-08-11 00:50:51 +00001761 // FALL THROUGH
1762 case Instruction::SetLE: { // setle bool %A, %B -> ~A | B
1763 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
1764 InsertNewInstBefore(Not, I);
1765 return BinaryOperator::createOr(Not, Op1);
1766 }
1767 }
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001768 }
1769
Chris Lattner2dd01742004-06-09 04:24:29 +00001770 // See if we are doing a comparison between a constant and an instruction that
1771 // can be folded into the comparison.
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001772 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnere1e10e12004-05-25 06:32:08 +00001773 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00001774 switch (LHSI->getOpcode()) {
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001775 case Instruction::PHI:
1776 if (Instruction *NV = FoldOpIntoPhi(I))
1777 return NV;
1778 break;
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00001779 case Instruction::And:
1780 if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
1781 LHSI->getOperand(0)->hasOneUse()) {
1782 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
1783 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
1784 // happens a LOT in code produced by the C front-end, for bitfield
1785 // access.
1786 ShiftInst *Shift = dyn_cast<ShiftInst>(LHSI->getOperand(0));
1787 ConstantUInt *ShAmt;
1788 ShAmt = Shift ? dyn_cast<ConstantUInt>(Shift->getOperand(1)) : 0;
1789 ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
1790 const Type *Ty = LHSI->getType();
1791
1792 // We can fold this as long as we can't shift unknown bits
1793 // into the mask. This can only happen with signed shift
1794 // rights, as they sign-extend.
1795 if (ShAmt) {
1796 bool CanFold = Shift->getOpcode() != Instruction::Shr ||
Chris Lattner6afc02f2004-09-28 17:54:07 +00001797 Shift->getType()->isUnsigned();
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00001798 if (!CanFold) {
1799 // To test for the bad case of the signed shr, see if any
1800 // of the bits shifted in could be tested after the mask.
1801 Constant *OShAmt = ConstantUInt::get(Type::UByteTy,
Chris Lattnerd8f5e2c2004-07-21 20:14:10 +00001802 Ty->getPrimitiveSize()*8-ShAmt->getValue());
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00001803 Constant *ShVal =
1804 ConstantExpr::getShl(ConstantInt::getAllOnesValue(Ty), OShAmt);
1805 if (ConstantExpr::getAnd(ShVal, AndCST)->isNullValue())
1806 CanFold = true;
1807 }
1808
1809 if (CanFold) {
Chris Lattner6afc02f2004-09-28 17:54:07 +00001810 Constant *NewCst;
1811 if (Shift->getOpcode() == Instruction::Shl)
1812 NewCst = ConstantExpr::getUShr(CI, ShAmt);
1813 else
1814 NewCst = ConstantExpr::getShl(CI, ShAmt);
Chris Lattnerbfff18a2004-09-27 19:29:18 +00001815
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00001816 // Check to see if we are shifting out any of the bits being
1817 // compared.
1818 if (ConstantExpr::get(Shift->getOpcode(), NewCst, ShAmt) != CI){
1819 // If we shifted bits out, the fold is not going to work out.
1820 // As a special case, check to see if this means that the
1821 // result is always true or false now.
1822 if (I.getOpcode() == Instruction::SetEQ)
1823 return ReplaceInstUsesWith(I, ConstantBool::False);
1824 if (I.getOpcode() == Instruction::SetNE)
1825 return ReplaceInstUsesWith(I, ConstantBool::True);
1826 } else {
1827 I.setOperand(1, NewCst);
Chris Lattner6afc02f2004-09-28 17:54:07 +00001828 Constant *NewAndCST;
1829 if (Shift->getOpcode() == Instruction::Shl)
1830 NewAndCST = ConstantExpr::getUShr(AndCST, ShAmt);
1831 else
1832 NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
1833 LHSI->setOperand(1, NewAndCST);
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00001834 LHSI->setOperand(0, Shift->getOperand(0));
1835 WorkList.push_back(Shift); // Shift is dead.
1836 AddUsesToWorkList(I);
1837 return &I;
Chris Lattner1638de42004-07-21 19:50:44 +00001838 }
1839 }
Chris Lattner35167c32004-06-09 07:59:58 +00001840 }
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00001841 }
1842 break;
Chris Lattnerbfff18a2004-09-27 19:29:18 +00001843
Chris Lattnerbe7a69e2004-09-29 03:09:18 +00001844 case Instruction::Cast: { // (setcc (cast X to larger), CI)
1845 const Type *SrcTy = LHSI->getOperand(0)->getType();
1846 if (SrcTy->isIntegral() && LHSI->getType()->isIntegral()) {
Chris Lattnerc9491282004-09-29 03:16:24 +00001847 unsigned SrcBits = SrcTy->getPrimitiveSize()*8;
Chris Lattnerbe7a69e2004-09-29 03:09:18 +00001848 if (SrcTy == Type::BoolTy) SrcBits = 1;
Chris Lattnerc9491282004-09-29 03:16:24 +00001849 unsigned DestBits = LHSI->getType()->getPrimitiveSize()*8;
Chris Lattnerbe7a69e2004-09-29 03:09:18 +00001850 if (LHSI->getType() == Type::BoolTy) DestBits = 1;
1851 if (SrcBits < DestBits) {
1852 // Check to see if the comparison is always true or false.
1853 Constant *NewCst = ConstantExpr::getCast(CI, SrcTy);
1854 if (ConstantExpr::getCast(NewCst, LHSI->getType()) != CI) {
1855 Constant *Min = ConstantIntegral::getMinValue(SrcTy);
1856 Constant *Max = ConstantIntegral::getMaxValue(SrcTy);
1857 Min = ConstantExpr::getCast(Min, LHSI->getType());
1858 Max = ConstantExpr::getCast(Max, LHSI->getType());
1859 switch (I.getOpcode()) {
1860 default: assert(0 && "unknown integer comparison");
1861 case Instruction::SetEQ:
1862 return ReplaceInstUsesWith(I, ConstantBool::False);
1863 case Instruction::SetNE:
1864 return ReplaceInstUsesWith(I, ConstantBool::True);
1865 case Instruction::SetLT:
1866 return ReplaceInstUsesWith(I, ConstantExpr::getSetLT(Max, CI));
1867 case Instruction::SetLE:
1868 return ReplaceInstUsesWith(I, ConstantExpr::getSetLE(Max, CI));
1869 case Instruction::SetGT:
1870 return ReplaceInstUsesWith(I, ConstantExpr::getSetGT(Min, CI));
1871 case Instruction::SetGE:
1872 return ReplaceInstUsesWith(I, ConstantExpr::getSetGE(Min, CI));
1873 }
1874 }
1875
1876 return new SetCondInst(I.getOpcode(), LHSI->getOperand(0),
1877 ConstantExpr::getCast(CI, SrcTy));
1878 }
1879 }
1880 break;
1881 }
Chris Lattner272d5ca2004-09-28 18:22:15 +00001882 case Instruction::Shl: // (setcc (shl X, ShAmt), CI)
1883 if (ConstantUInt *ShAmt = dyn_cast<ConstantUInt>(LHSI->getOperand(1))) {
1884 switch (I.getOpcode()) {
1885 default: break;
1886 case Instruction::SetEQ:
1887 case Instruction::SetNE: {
1888 // If we are comparing against bits always shifted out, the
1889 // comparison cannot succeed.
1890 Constant *Comp =
1891 ConstantExpr::getShl(ConstantExpr::getShr(CI, ShAmt), ShAmt);
1892 if (Comp != CI) {// Comparing against a bit that we know is zero.
1893 bool IsSetNE = I.getOpcode() == Instruction::SetNE;
1894 Constant *Cst = ConstantBool::get(IsSetNE);
1895 return ReplaceInstUsesWith(I, Cst);
1896 }
1897
1898 if (LHSI->hasOneUse()) {
1899 // Otherwise strength reduce the shift into an and.
1900 unsigned ShAmtVal = ShAmt->getValue();
1901 unsigned TypeBits = CI->getType()->getPrimitiveSize()*8;
1902 uint64_t Val = (1ULL << (TypeBits-ShAmtVal))-1;
1903
1904 Constant *Mask;
1905 if (CI->getType()->isUnsigned()) {
1906 Mask = ConstantUInt::get(CI->getType(), Val);
1907 } else if (ShAmtVal != 0) {
1908 Mask = ConstantSInt::get(CI->getType(), Val);
1909 } else {
1910 Mask = ConstantInt::getAllOnesValue(CI->getType());
1911 }
1912
1913 Instruction *AndI =
1914 BinaryOperator::createAnd(LHSI->getOperand(0),
1915 Mask, LHSI->getName()+".mask");
1916 Value *And = InsertNewInstBefore(AndI, I);
1917 return new SetCondInst(I.getOpcode(), And,
1918 ConstantExpr::getUShr(CI, ShAmt));
1919 }
1920 }
1921 }
1922 }
1923 break;
1924
Chris Lattnerbfff18a2004-09-27 19:29:18 +00001925 case Instruction::Shr: // (setcc (shr X, ShAmt), CI)
Chris Lattner1023b872004-09-27 16:18:50 +00001926 if (ConstantUInt *ShAmt = dyn_cast<ConstantUInt>(LHSI->getOperand(1))) {
Chris Lattner1023b872004-09-27 16:18:50 +00001927 switch (I.getOpcode()) {
1928 default: break;
1929 case Instruction::SetEQ:
1930 case Instruction::SetNE: {
1931 // If we are comparing against bits always shifted out, the
1932 // comparison cannot succeed.
1933 Constant *Comp =
1934 ConstantExpr::getShr(ConstantExpr::getShl(CI, ShAmt), ShAmt);
1935
1936 if (Comp != CI) {// Comparing against a bit that we know is zero.
1937 bool IsSetNE = I.getOpcode() == Instruction::SetNE;
1938 Constant *Cst = ConstantBool::get(IsSetNE);
1939 return ReplaceInstUsesWith(I, Cst);
1940 }
1941
1942 if (LHSI->hasOneUse() || CI->isNullValue()) {
Chris Lattner272d5ca2004-09-28 18:22:15 +00001943 unsigned ShAmtVal = ShAmt->getValue();
1944
Chris Lattner1023b872004-09-27 16:18:50 +00001945 // Otherwise strength reduce the shift into an and.
1946 uint64_t Val = ~0ULL; // All ones.
1947 Val <<= ShAmtVal; // Shift over to the right spot.
1948
1949 Constant *Mask;
1950 if (CI->getType()->isUnsigned()) {
1951 unsigned TypeBits = CI->getType()->getPrimitiveSize()*8;
1952 Val &= (1ULL << TypeBits)-1;
1953 Mask = ConstantUInt::get(CI->getType(), Val);
1954 } else {
1955 Mask = ConstantSInt::get(CI->getType(), Val);
1956 }
1957
1958 Instruction *AndI =
1959 BinaryOperator::createAnd(LHSI->getOperand(0),
1960 Mask, LHSI->getName()+".mask");
1961 Value *And = InsertNewInstBefore(AndI, I);
1962 return new SetCondInst(I.getOpcode(), And,
1963 ConstantExpr::getShl(CI, ShAmt));
1964 }
1965 break;
1966 }
1967 }
1968 }
1969 break;
Chris Lattner7e794272004-09-24 15:21:34 +00001970
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00001971 case Instruction::Select:
1972 // If either operand of the select is a constant, we can fold the
1973 // comparison into the select arms, which will cause one to be
1974 // constant folded and the select turned into a bitwise or.
1975 Value *Op1 = 0, *Op2 = 0;
1976 if (LHSI->hasOneUse()) {
Chris Lattner35167c32004-06-09 07:59:58 +00001977 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
Chris Lattner2dd01742004-06-09 04:24:29 +00001978 // Fold the known value into the constant operand.
1979 Op1 = ConstantExpr::get(I.getOpcode(), C, CI);
1980 // Insert a new SetCC of the other select operand.
1981 Op2 = InsertNewInstBefore(new SetCondInst(I.getOpcode(),
Chris Lattner35167c32004-06-09 07:59:58 +00001982 LHSI->getOperand(2), CI,
Chris Lattner2dd01742004-06-09 04:24:29 +00001983 I.getName()), I);
Chris Lattner35167c32004-06-09 07:59:58 +00001984 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
Chris Lattner2dd01742004-06-09 04:24:29 +00001985 // Fold the known value into the constant operand.
1986 Op2 = ConstantExpr::get(I.getOpcode(), C, CI);
1987 // Insert a new SetCC of the other select operand.
1988 Op1 = InsertNewInstBefore(new SetCondInst(I.getOpcode(),
Chris Lattner35167c32004-06-09 07:59:58 +00001989 LHSI->getOperand(1), CI,
Chris Lattner2dd01742004-06-09 04:24:29 +00001990 I.getName()), I);
1991 }
Chris Lattner2dd01742004-06-09 04:24:29 +00001992 }
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00001993
1994 if (Op1)
1995 return new SelectInst(LHSI->getOperand(0), Op1, Op2);
1996 break;
1997 }
1998
Chris Lattnerd492a0b2003-07-23 17:02:11 +00001999 // Simplify seteq and setne instructions...
2000 if (I.getOpcode() == Instruction::SetEQ ||
2001 I.getOpcode() == Instruction::SetNE) {
2002 bool isSetNE = I.getOpcode() == Instruction::SetNE;
2003
Chris Lattnercfbce7c2003-07-23 17:26:36 +00002004 // If the first operand is (and|or|xor) with a constant, and the second
Chris Lattnerd492a0b2003-07-23 17:02:11 +00002005 // operand is a constant, simplify a bit.
Chris Lattnerc992add2003-08-13 05:33:12 +00002006 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0)) {
2007 switch (BO->getOpcode()) {
Chris Lattner23b47b62004-07-06 07:38:18 +00002008 case Instruction::Rem:
2009 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
2010 if (CI->isNullValue() && isa<ConstantSInt>(BO->getOperand(1)) &&
2011 BO->hasOneUse() &&
2012 cast<ConstantSInt>(BO->getOperand(1))->getValue() > 1)
2013 if (unsigned L2 =
2014 Log2(cast<ConstantSInt>(BO->getOperand(1))->getValue())) {
2015 const Type *UTy = BO->getType()->getUnsignedVersion();
2016 Value *NewX = InsertNewInstBefore(new CastInst(BO->getOperand(0),
2017 UTy, "tmp"), I);
2018 Constant *RHSCst = ConstantUInt::get(UTy, 1ULL << L2);
2019 Value *NewRem =InsertNewInstBefore(BinaryOperator::createRem(NewX,
2020 RHSCst, BO->getName()), I);
2021 return BinaryOperator::create(I.getOpcode(), NewRem,
2022 Constant::getNullValue(UTy));
2023 }
2024 break;
2025
Chris Lattnerc992add2003-08-13 05:33:12 +00002026 case Instruction::Add:
Chris Lattner6e079362004-06-27 22:51:36 +00002027 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
2028 if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
Chris Lattnerb121ae12004-09-21 21:35:23 +00002029 if (BO->hasOneUse())
2030 return new SetCondInst(I.getOpcode(), BO->getOperand(0),
2031 ConstantExpr::getSub(CI, BOp1C));
Chris Lattner6e079362004-06-27 22:51:36 +00002032 } else if (CI->isNullValue()) {
Chris Lattnerc992add2003-08-13 05:33:12 +00002033 // Replace ((add A, B) != 0) with (A != -B) if A or B is
2034 // efficiently invertible, or if the add has just this one use.
2035 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
Chris Lattner6e079362004-06-27 22:51:36 +00002036
Chris Lattnerc992add2003-08-13 05:33:12 +00002037 if (Value *NegVal = dyn_castNegVal(BOp1))
2038 return new SetCondInst(I.getOpcode(), BOp0, NegVal);
2039 else if (Value *NegVal = dyn_castNegVal(BOp0))
2040 return new SetCondInst(I.getOpcode(), NegVal, BOp1);
Chris Lattnerf95d9b92003-10-15 16:48:29 +00002041 else if (BO->hasOneUse()) {
Chris Lattnerc992add2003-08-13 05:33:12 +00002042 Instruction *Neg = BinaryOperator::createNeg(BOp1, BO->getName());
2043 BO->setName("");
2044 InsertNewInstBefore(Neg, I);
2045 return new SetCondInst(I.getOpcode(), BOp0, Neg);
2046 }
2047 }
2048 break;
2049 case Instruction::Xor:
2050 // For the xor case, we can xor two constants together, eliminating
2051 // the explicit xor.
2052 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
2053 return BinaryOperator::create(I.getOpcode(), BO->getOperand(0),
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002054 ConstantExpr::getXor(CI, BOC));
Chris Lattnerc992add2003-08-13 05:33:12 +00002055
2056 // FALLTHROUGH
2057 case Instruction::Sub:
2058 // Replace (([sub|xor] A, B) != 0) with (A != B)
2059 if (CI->isNullValue())
2060 return new SetCondInst(I.getOpcode(), BO->getOperand(0),
2061 BO->getOperand(1));
2062 break;
2063
2064 case Instruction::Or:
2065 // If bits are being or'd in that are not present in the constant we
2066 // are comparing against, then the comparison could never succeed!
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00002067 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
Chris Lattnerc8e7e292004-06-10 02:12:35 +00002068 Constant *NotCI = ConstantExpr::getNot(CI);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002069 if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
Chris Lattnerd492a0b2003-07-23 17:02:11 +00002070 return ReplaceInstUsesWith(I, ConstantBool::get(isSetNE));
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00002071 }
Chris Lattnerc992add2003-08-13 05:33:12 +00002072 break;
2073
2074 case Instruction::And:
2075 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
Chris Lattnerd492a0b2003-07-23 17:02:11 +00002076 // If bits are being compared against that are and'd out, then the
2077 // comparison can never succeed!
Chris Lattnerc8e7e292004-06-10 02:12:35 +00002078 if (!ConstantExpr::getAnd(CI,
2079 ConstantExpr::getNot(BOC))->isNullValue())
Chris Lattnerd492a0b2003-07-23 17:02:11 +00002080 return ReplaceInstUsesWith(I, ConstantBool::get(isSetNE));
Chris Lattnerc992add2003-08-13 05:33:12 +00002081
Chris Lattner35167c32004-06-09 07:59:58 +00002082 // If we have ((X & C) == C), turn it into ((X & C) != 0).
Chris Lattneree59d4b2004-06-10 02:33:20 +00002083 if (CI == BOC && isOneBitSet(CI))
Chris Lattner35167c32004-06-09 07:59:58 +00002084 return new SetCondInst(isSetNE ? Instruction::SetEQ :
2085 Instruction::SetNE, Op0,
2086 Constant::getNullValue(CI->getType()));
Chris Lattner35167c32004-06-09 07:59:58 +00002087
Chris Lattnerc992add2003-08-13 05:33:12 +00002088 // Replace (and X, (1 << size(X)-1) != 0) with x < 0, converting X
2089 // to be a signed value as appropriate.
2090 if (isSignBit(BOC)) {
2091 Value *X = BO->getOperand(0);
2092 // If 'X' is not signed, insert a cast now...
2093 if (!BOC->getType()->isSigned()) {
Chris Lattner97bfcea2004-06-17 18:16:02 +00002094 const Type *DestTy = BOC->getType()->getSignedVersion();
Chris Lattnerbfff18a2004-09-27 19:29:18 +00002095 X = InsertCastBefore(X, DestTy, I);
Chris Lattnerc992add2003-08-13 05:33:12 +00002096 }
2097 return new SetCondInst(isSetNE ? Instruction::SetLT :
2098 Instruction::SetGE, X,
2099 Constant::getNullValue(X->getType()));
2100 }
Chris Lattner8fc5af42004-09-23 21:46:38 +00002101
Chris Lattnerbfff18a2004-09-27 19:29:18 +00002102 // ((X & ~7) == 0) --> X < 8
Chris Lattner8fc5af42004-09-23 21:46:38 +00002103 if (CI->isNullValue() && isHighOnes(BOC)) {
2104 Value *X = BO->getOperand(0);
Chris Lattnerbfff18a2004-09-27 19:29:18 +00002105 Constant *NegX = ConstantExpr::getNeg(BOC);
Chris Lattner8fc5af42004-09-23 21:46:38 +00002106
2107 // If 'X' is signed, insert a cast now.
Chris Lattnerbfff18a2004-09-27 19:29:18 +00002108 if (NegX->getType()->isSigned()) {
2109 const Type *DestTy = NegX->getType()->getUnsignedVersion();
2110 X = InsertCastBefore(X, DestTy, I);
2111 NegX = ConstantExpr::getCast(NegX, DestTy);
Chris Lattner8fc5af42004-09-23 21:46:38 +00002112 }
2113
2114 return new SetCondInst(isSetNE ? Instruction::SetGE :
Chris Lattnerbfff18a2004-09-27 19:29:18 +00002115 Instruction::SetLT, X, NegX);
Chris Lattner8fc5af42004-09-23 21:46:38 +00002116 }
2117
Chris Lattnerd492a0b2003-07-23 17:02:11 +00002118 }
Chris Lattnerc992add2003-08-13 05:33:12 +00002119 default: break;
2120 }
2121 }
Chris Lattner2b55ea32004-02-23 07:16:20 +00002122 } else { // Not a SetEQ/SetNE
2123 // If the LHS is a cast from an integral value of the same size,
2124 if (CastInst *Cast = dyn_cast<CastInst>(Op0)) {
2125 Value *CastOp = Cast->getOperand(0);
2126 const Type *SrcTy = CastOp->getType();
2127 unsigned SrcTySize = SrcTy->getPrimitiveSize();
2128 if (SrcTy != Cast->getType() && SrcTy->isInteger() &&
2129 SrcTySize == Cast->getType()->getPrimitiveSize()) {
2130 assert((SrcTy->isSigned() ^ Cast->getType()->isSigned()) &&
2131 "Source and destination signednesses should differ!");
2132 if (Cast->getType()->isSigned()) {
2133 // If this is a signed comparison, check for comparisons in the
2134 // vicinity of zero.
2135 if (I.getOpcode() == Instruction::SetLT && CI->isNullValue())
2136 // X < 0 => x > 127
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002137 return BinaryOperator::createSetGT(CastOp,
Chris Lattner2b55ea32004-02-23 07:16:20 +00002138 ConstantUInt::get(SrcTy, (1ULL << (SrcTySize*8-1))-1));
2139 else if (I.getOpcode() == Instruction::SetGT &&
2140 cast<ConstantSInt>(CI)->getValue() == -1)
2141 // X > -1 => x < 128
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002142 return BinaryOperator::createSetLT(CastOp,
Chris Lattner2b55ea32004-02-23 07:16:20 +00002143 ConstantUInt::get(SrcTy, 1ULL << (SrcTySize*8-1)));
2144 } else {
2145 ConstantUInt *CUI = cast<ConstantUInt>(CI);
2146 if (I.getOpcode() == Instruction::SetLT &&
2147 CUI->getValue() == 1ULL << (SrcTySize*8-1))
2148 // X < 128 => X > -1
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002149 return BinaryOperator::createSetGT(CastOp,
2150 ConstantSInt::get(SrcTy, -1));
Chris Lattner2b55ea32004-02-23 07:16:20 +00002151 else if (I.getOpcode() == Instruction::SetGT &&
2152 CUI->getValue() == (1ULL << (SrcTySize*8-1))-1)
2153 // X > 127 => X < 0
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002154 return BinaryOperator::createSetLT(CastOp,
2155 Constant::getNullValue(SrcTy));
Chris Lattner2b55ea32004-02-23 07:16:20 +00002156 }
2157 }
2158 }
Chris Lattnere967b342003-06-04 05:10:11 +00002159 }
Chris Lattner791ac1a2003-06-01 03:35:25 +00002160
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002161 // Check to see if we are comparing against the minimum or maximum value...
Chris Lattnere6794492002-08-12 21:17:25 +00002162 if (CI->isMinValue()) {
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002163 if (I.getOpcode() == Instruction::SetLT) // A < MIN -> FALSE
2164 return ReplaceInstUsesWith(I, ConstantBool::False);
2165 if (I.getOpcode() == Instruction::SetGE) // A >= MIN -> TRUE
2166 return ReplaceInstUsesWith(I, ConstantBool::True);
2167 if (I.getOpcode() == Instruction::SetLE) // A <= MIN -> A == MIN
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002168 return BinaryOperator::createSetEQ(Op0, Op1);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002169 if (I.getOpcode() == Instruction::SetGT) // A > MIN -> A != MIN
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002170 return BinaryOperator::createSetNE(Op0, Op1);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002171
Chris Lattnere6794492002-08-12 21:17:25 +00002172 } else if (CI->isMaxValue()) {
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002173 if (I.getOpcode() == Instruction::SetGT) // A > MAX -> FALSE
2174 return ReplaceInstUsesWith(I, ConstantBool::False);
2175 if (I.getOpcode() == Instruction::SetLE) // A <= MAX -> TRUE
2176 return ReplaceInstUsesWith(I, ConstantBool::True);
2177 if (I.getOpcode() == Instruction::SetGE) // A >= MAX -> A == MAX
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002178 return BinaryOperator::createSetEQ(Op0, Op1);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002179 if (I.getOpcode() == Instruction::SetLT) // A < MAX -> A != MAX
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002180 return BinaryOperator::createSetNE(Op0, Op1);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002181
2182 // Comparing against a value really close to min or max?
2183 } else if (isMinValuePlusOne(CI)) {
2184 if (I.getOpcode() == Instruction::SetLT) // A < MIN+1 -> A == MIN
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002185 return BinaryOperator::createSetEQ(Op0, SubOne(CI));
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002186 if (I.getOpcode() == Instruction::SetGE) // A >= MIN-1 -> A != MIN
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002187 return BinaryOperator::createSetNE(Op0, SubOne(CI));
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002188
2189 } else if (isMaxValueMinusOne(CI)) {
2190 if (I.getOpcode() == Instruction::SetGT) // A > MAX-1 -> A == MAX
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002191 return BinaryOperator::createSetEQ(Op0, AddOne(CI));
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002192 if (I.getOpcode() == Instruction::SetLE) // A <= MAX-1 -> A != MAX
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002193 return BinaryOperator::createSetNE(Op0, AddOne(CI));
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002194 }
Chris Lattner59611142004-02-23 05:47:48 +00002195
2196 // If we still have a setle or setge instruction, turn it into the
2197 // appropriate setlt or setgt instruction. Since the border cases have
2198 // already been handled above, this requires little checking.
2199 //
2200 if (I.getOpcode() == Instruction::SetLE)
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002201 return BinaryOperator::createSetLT(Op0, AddOne(CI));
Chris Lattner59611142004-02-23 05:47:48 +00002202 if (I.getOpcode() == Instruction::SetGE)
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002203 return BinaryOperator::createSetGT(Op0, SubOne(CI));
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002204 }
2205
Chris Lattner16930792003-11-03 04:25:02 +00002206 // Test to see if the operands of the setcc are casted versions of other
2207 // values. If the cast can be stripped off both arguments, we do so now.
Chris Lattner6444c372003-11-03 05:17:03 +00002208 if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
2209 Value *CastOp0 = CI->getOperand(0);
2210 if (CastOp0->getType()->isLosslesslyConvertibleTo(CI->getType()) &&
Chris Lattner7d2a5392004-03-13 23:54:27 +00002211 (isa<Constant>(Op1) || isa<CastInst>(Op1)) &&
Chris Lattner16930792003-11-03 04:25:02 +00002212 (I.getOpcode() == Instruction::SetEQ ||
2213 I.getOpcode() == Instruction::SetNE)) {
2214 // We keep moving the cast from the left operand over to the right
2215 // operand, where it can often be eliminated completely.
Chris Lattner6444c372003-11-03 05:17:03 +00002216 Op0 = CastOp0;
Chris Lattner16930792003-11-03 04:25:02 +00002217
2218 // If operand #1 is a cast instruction, see if we can eliminate it as
2219 // well.
Chris Lattner6444c372003-11-03 05:17:03 +00002220 if (CastInst *CI2 = dyn_cast<CastInst>(Op1))
2221 if (CI2->getOperand(0)->getType()->isLosslesslyConvertibleTo(
Chris Lattner16930792003-11-03 04:25:02 +00002222 Op0->getType()))
Chris Lattner6444c372003-11-03 05:17:03 +00002223 Op1 = CI2->getOperand(0);
Chris Lattner16930792003-11-03 04:25:02 +00002224
2225 // If Op1 is a constant, we can fold the cast into the constant.
2226 if (Op1->getType() != Op0->getType())
2227 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
2228 Op1 = ConstantExpr::getCast(Op1C, Op0->getType());
2229 } else {
2230 // Otherwise, cast the RHS right before the setcc
2231 Op1 = new CastInst(Op1, Op0->getType(), Op1->getName());
2232 InsertNewInstBefore(cast<Instruction>(Op1), I);
2233 }
2234 return BinaryOperator::create(I.getOpcode(), Op0, Op1);
2235 }
2236
Chris Lattner6444c372003-11-03 05:17:03 +00002237 // Handle the special case of: setcc (cast bool to X), <cst>
2238 // This comes up when you have code like
2239 // int X = A < B;
2240 // if (X) ...
2241 // For generality, we handle any zero-extension of any operand comparison
2242 // with a constant.
2243 if (ConstantInt *ConstantRHS = dyn_cast<ConstantInt>(Op1)) {
2244 const Type *SrcTy = CastOp0->getType();
2245 const Type *DestTy = Op0->getType();
2246 if (SrcTy->getPrimitiveSize() < DestTy->getPrimitiveSize() &&
2247 (SrcTy->isUnsigned() || SrcTy == Type::BoolTy)) {
2248 // Ok, we have an expansion of operand 0 into a new type. Get the
2249 // constant value, masink off bits which are not set in the RHS. These
2250 // could be set if the destination value is signed.
2251 uint64_t ConstVal = ConstantRHS->getRawValue();
2252 ConstVal &= (1ULL << DestTy->getPrimitiveSize()*8)-1;
2253
2254 // If the constant we are comparing it with has high bits set, which
2255 // don't exist in the original value, the values could never be equal,
2256 // because the source would be zero extended.
2257 unsigned SrcBits =
2258 SrcTy == Type::BoolTy ? 1 : SrcTy->getPrimitiveSize()*8;
Chris Lattner7c94d112003-11-05 17:31:36 +00002259 bool HasSignBit = ConstVal & (1ULL << (DestTy->getPrimitiveSize()*8-1));
2260 if (ConstVal & ~((1ULL << SrcBits)-1)) {
Chris Lattner6444c372003-11-03 05:17:03 +00002261 switch (I.getOpcode()) {
2262 default: assert(0 && "Unknown comparison type!");
2263 case Instruction::SetEQ:
2264 return ReplaceInstUsesWith(I, ConstantBool::False);
2265 case Instruction::SetNE:
2266 return ReplaceInstUsesWith(I, ConstantBool::True);
2267 case Instruction::SetLT:
2268 case Instruction::SetLE:
2269 if (DestTy->isSigned() && HasSignBit)
2270 return ReplaceInstUsesWith(I, ConstantBool::False);
2271 return ReplaceInstUsesWith(I, ConstantBool::True);
2272 case Instruction::SetGT:
2273 case Instruction::SetGE:
2274 if (DestTy->isSigned() && HasSignBit)
2275 return ReplaceInstUsesWith(I, ConstantBool::True);
2276 return ReplaceInstUsesWith(I, ConstantBool::False);
2277 }
2278 }
2279
2280 // Otherwise, we can replace the setcc with a setcc of the smaller
2281 // operand value.
2282 Op1 = ConstantExpr::getCast(cast<Constant>(Op1), SrcTy);
2283 return BinaryOperator::create(I.getOpcode(), CastOp0, Op1);
2284 }
2285 }
2286 }
Chris Lattner113f4f42002-06-25 16:13:24 +00002287 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002288}
2289
2290
2291
Chris Lattnere8d6c602003-03-10 19:16:08 +00002292Instruction *InstCombiner::visitShiftInst(ShiftInst &I) {
Chris Lattner113f4f42002-06-25 16:13:24 +00002293 assert(I.getOperand(1)->getType() == Type::UByteTy);
2294 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00002295 bool isLeftShift = I.getOpcode() == Instruction::Shl;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002296
2297 // shl X, 0 == X and shr X, 0 == X
2298 // shl 0, X == 0 and shr 0, X == 0
2299 if (Op1 == Constant::getNullValue(Type::UByteTy) ||
Chris Lattnere6794492002-08-12 21:17:25 +00002300 Op0 == Constant::getNullValue(Op0->getType()))
2301 return ReplaceInstUsesWith(I, Op0);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002302
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00002303 // shr int -1, X = -1 (for any arithmetic shift rights of ~0)
2304 if (!isLeftShift)
2305 if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(Op0))
2306 if (CSI->isAllOnesValue())
2307 return ReplaceInstUsesWith(I, CSI);
2308
Chris Lattner183b3362004-04-09 19:05:30 +00002309 // Try to fold constant and into select arguments.
2310 if (isa<Constant>(Op0))
2311 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
2312 if (Instruction *R = FoldBinOpIntoSelect(I, SI, this))
2313 return R;
2314
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002315 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(Op1)) {
Chris Lattner3204d4e2003-07-24 17:52:58 +00002316 // shl uint X, 32 = 0 and shr ubyte Y, 9 = 0, ... just don't eliminate shr
2317 // of a signed value.
2318 //
Chris Lattnere8d6c602003-03-10 19:16:08 +00002319 unsigned TypeBits = Op0->getType()->getPrimitiveSize()*8;
Chris Lattnerf5ce2542004-02-23 20:30:06 +00002320 if (CUI->getValue() >= TypeBits) {
2321 if (!Op0->getType()->isSigned() || isLeftShift)
2322 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
2323 else {
2324 I.setOperand(1, ConstantUInt::get(Type::UByteTy, TypeBits-1));
2325 return &I;
2326 }
2327 }
Chris Lattner55f3d942002-09-10 23:04:09 +00002328
Chris Lattnerede3fe02003-08-13 04:18:28 +00002329 // ((X*C1) << C2) == (X * (C1 << C2))
2330 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
2331 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
2332 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002333 return BinaryOperator::createMul(BO->getOperand(0),
2334 ConstantExpr::getShl(BOOp, CUI));
Chris Lattnerede3fe02003-08-13 04:18:28 +00002335
Chris Lattner183b3362004-04-09 19:05:30 +00002336 // Try to fold constant and into select arguments.
2337 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2338 if (Instruction *R = FoldBinOpIntoSelect(I, SI, this))
2339 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00002340 if (isa<PHINode>(Op0))
2341 if (Instruction *NV = FoldOpIntoPhi(I))
2342 return NV;
Chris Lattnerede3fe02003-08-13 04:18:28 +00002343
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00002344 // If the operand is an bitwise operator with a constant RHS, and the
2345 // shift is the only use, we can pull it out of the shift.
Chris Lattnerf95d9b92003-10-15 16:48:29 +00002346 if (Op0->hasOneUse())
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00002347 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0))
2348 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
2349 bool isValid = true; // Valid only for And, Or, Xor
2350 bool highBitSet = false; // Transform if high bit of constant set?
2351
2352 switch (Op0BO->getOpcode()) {
2353 default: isValid = false; break; // Do not perform transform!
2354 case Instruction::Or:
2355 case Instruction::Xor:
2356 highBitSet = false;
2357 break;
2358 case Instruction::And:
2359 highBitSet = true;
2360 break;
2361 }
2362
2363 // If this is a signed shift right, and the high bit is modified
2364 // by the logical operation, do not perform the transformation.
2365 // The highBitSet boolean indicates the value of the high bit of
2366 // the constant which would cause it to be modified for this
2367 // operation.
2368 //
2369 if (isValid && !isLeftShift && !I.getType()->isUnsigned()) {
2370 uint64_t Val = Op0C->getRawValue();
2371 isValid = ((Val & (1 << (TypeBits-1))) != 0) == highBitSet;
2372 }
2373
2374 if (isValid) {
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00002375 Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, CUI);
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00002376
2377 Instruction *NewShift =
2378 new ShiftInst(I.getOpcode(), Op0BO->getOperand(0), CUI,
2379 Op0BO->getName());
2380 Op0BO->setName("");
2381 InsertNewInstBefore(NewShift, I);
2382
2383 return BinaryOperator::create(Op0BO->getOpcode(), NewShift,
2384 NewRHS);
2385 }
2386 }
2387
Chris Lattner3204d4e2003-07-24 17:52:58 +00002388 // If this is a shift of a shift, see if we can fold the two together...
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00002389 if (ShiftInst *Op0SI = dyn_cast<ShiftInst>(Op0))
Chris Lattnerab780df2003-07-24 18:38:56 +00002390 if (ConstantUInt *ShiftAmt1C =
2391 dyn_cast<ConstantUInt>(Op0SI->getOperand(1))) {
Chris Lattner3204d4e2003-07-24 17:52:58 +00002392 unsigned ShiftAmt1 = ShiftAmt1C->getValue();
2393 unsigned ShiftAmt2 = CUI->getValue();
2394
2395 // Check for (A << c1) << c2 and (A >> c1) >> c2
2396 if (I.getOpcode() == Op0SI->getOpcode()) {
2397 unsigned Amt = ShiftAmt1+ShiftAmt2; // Fold into one big shift...
Chris Lattnerf5ce2542004-02-23 20:30:06 +00002398 if (Op0->getType()->getPrimitiveSize()*8 < Amt)
2399 Amt = Op0->getType()->getPrimitiveSize()*8;
Chris Lattner3204d4e2003-07-24 17:52:58 +00002400 return new ShiftInst(I.getOpcode(), Op0SI->getOperand(0),
2401 ConstantUInt::get(Type::UByteTy, Amt));
2402 }
2403
Chris Lattnerab780df2003-07-24 18:38:56 +00002404 // Check for (A << c1) >> c2 or visaversa. If we are dealing with
2405 // signed types, we can only support the (A >> c1) << c2 configuration,
2406 // because it can not turn an arbitrary bit of A into a sign bit.
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00002407 if (I.getType()->isUnsigned() || isLeftShift) {
Chris Lattner3204d4e2003-07-24 17:52:58 +00002408 // Calculate bitmask for what gets shifted off the edge...
2409 Constant *C = ConstantIntegral::getAllOnesValue(I.getType());
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00002410 if (isLeftShift)
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002411 C = ConstantExpr::getShl(C, ShiftAmt1C);
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00002412 else
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002413 C = ConstantExpr::getShr(C, ShiftAmt1C);
Chris Lattner3204d4e2003-07-24 17:52:58 +00002414
2415 Instruction *Mask =
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002416 BinaryOperator::createAnd(Op0SI->getOperand(0), C,
2417 Op0SI->getOperand(0)->getName()+".mask");
Chris Lattner3204d4e2003-07-24 17:52:58 +00002418 InsertNewInstBefore(Mask, I);
2419
2420 // Figure out what flavor of shift we should use...
2421 if (ShiftAmt1 == ShiftAmt2)
2422 return ReplaceInstUsesWith(I, Mask); // (A << c) >> c === A & c2
2423 else if (ShiftAmt1 < ShiftAmt2) {
2424 return new ShiftInst(I.getOpcode(), Mask,
2425 ConstantUInt::get(Type::UByteTy, ShiftAmt2-ShiftAmt1));
2426 } else {
2427 return new ShiftInst(Op0SI->getOpcode(), Mask,
2428 ConstantUInt::get(Type::UByteTy, ShiftAmt1-ShiftAmt2));
2429 }
2430 }
2431 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002432 }
Chris Lattner2e0fb392002-10-08 16:16:40 +00002433
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002434 return 0;
2435}
2436
Chris Lattner4e2dbc62004-07-20 00:59:32 +00002437enum CastType {
2438 Noop = 0,
2439 Truncate = 1,
2440 Signext = 2,
2441 Zeroext = 3
2442};
2443
2444/// getCastType - In the future, we will split the cast instruction into these
2445/// various types. Until then, we have to do the analysis here.
2446static CastType getCastType(const Type *Src, const Type *Dest) {
2447 assert(Src->isIntegral() && Dest->isIntegral() &&
2448 "Only works on integral types!");
2449 unsigned SrcSize = Src->getPrimitiveSize()*8;
2450 if (Src == Type::BoolTy) SrcSize = 1;
2451 unsigned DestSize = Dest->getPrimitiveSize()*8;
2452 if (Dest == Type::BoolTy) DestSize = 1;
2453
2454 if (SrcSize == DestSize) return Noop;
2455 if (SrcSize > DestSize) return Truncate;
2456 if (Src->isSigned()) return Signext;
2457 return Zeroext;
2458}
2459
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002460
Chris Lattner48a44f72002-05-02 17:06:02 +00002461// isEliminableCastOfCast - Return true if it is valid to eliminate the CI
2462// instruction.
2463//
Chris Lattnerdfae8be2003-07-24 17:35:25 +00002464static inline bool isEliminableCastOfCast(const Type *SrcTy, const Type *MidTy,
Chris Lattner11ffd592004-07-20 05:21:00 +00002465 const Type *DstTy, TargetData *TD) {
Chris Lattner48a44f72002-05-02 17:06:02 +00002466
Chris Lattner650b6da2002-08-02 20:00:25 +00002467 // It is legal to eliminate the instruction if casting A->B->A if the sizes
2468 // are identical and the bits don't get reinterpreted (for example
Chris Lattner1638de42004-07-21 19:50:44 +00002469 // int->float->int would not be allowed).
Misha Brukmane5838c42003-05-20 18:45:36 +00002470 if (SrcTy == DstTy && SrcTy->isLosslesslyConvertibleTo(MidTy))
Chris Lattner650b6da2002-08-02 20:00:25 +00002471 return true;
Chris Lattner48a44f72002-05-02 17:06:02 +00002472
Chris Lattner4fbad962004-07-21 04:27:24 +00002473 // If we are casting between pointer and integer types, treat pointers as
2474 // integers of the appropriate size for the code below.
2475 if (isa<PointerType>(SrcTy)) SrcTy = TD->getIntPtrType();
2476 if (isa<PointerType>(MidTy)) MidTy = TD->getIntPtrType();
2477 if (isa<PointerType>(DstTy)) DstTy = TD->getIntPtrType();
Chris Lattner11ffd592004-07-20 05:21:00 +00002478
Chris Lattner48a44f72002-05-02 17:06:02 +00002479 // Allow free casting and conversion of sizes as long as the sign doesn't
2480 // change...
Chris Lattnerb0b412e2002-09-03 01:08:28 +00002481 if (SrcTy->isIntegral() && MidTy->isIntegral() && DstTy->isIntegral()) {
Chris Lattner4e2dbc62004-07-20 00:59:32 +00002482 CastType FirstCast = getCastType(SrcTy, MidTy);
2483 CastType SecondCast = getCastType(MidTy, DstTy);
Chris Lattner650b6da2002-08-02 20:00:25 +00002484
Chris Lattner4e2dbc62004-07-20 00:59:32 +00002485 // Capture the effect of these two casts. If the result is a legal cast,
2486 // the CastType is stored here, otherwise a special code is used.
2487 static const unsigned CastResult[] = {
2488 // First cast is noop
2489 0, 1, 2, 3,
2490 // First cast is a truncate
2491 1, 1, 4, 4, // trunc->extend is not safe to eliminate
2492 // First cast is a sign ext
Chris Lattner1638de42004-07-21 19:50:44 +00002493 2, 5, 2, 4, // signext->zeroext never ok
Chris Lattner4e2dbc62004-07-20 00:59:32 +00002494 // First cast is a zero ext
Chris Lattner1638de42004-07-21 19:50:44 +00002495 3, 5, 3, 3,
Chris Lattner4e2dbc62004-07-20 00:59:32 +00002496 };
2497
2498 unsigned Result = CastResult[FirstCast*4+SecondCast];
2499 switch (Result) {
2500 default: assert(0 && "Illegal table value!");
2501 case 0:
2502 case 1:
2503 case 2:
2504 case 3:
2505 // FIXME: in the future, when LLVM has explicit sign/zeroextends and
2506 // truncates, we could eliminate more casts.
2507 return (unsigned)getCastType(SrcTy, DstTy) == Result;
2508 case 4:
2509 return false; // Not possible to eliminate this here.
2510 case 5:
Chris Lattner1638de42004-07-21 19:50:44 +00002511 // Sign or zero extend followed by truncate is always ok if the result
2512 // is a truncate or noop.
2513 CastType ResultCast = getCastType(SrcTy, DstTy);
2514 if (ResultCast == Noop || ResultCast == Truncate)
2515 return true;
2516 // Otherwise we are still growing the value, we are only safe if the
2517 // result will match the sign/zeroextendness of the result.
2518 return ResultCast == FirstCast;
Chris Lattner3732aca2002-08-15 16:15:25 +00002519 }
Chris Lattner650b6da2002-08-02 20:00:25 +00002520 }
Chris Lattner48a44f72002-05-02 17:06:02 +00002521 return false;
2522}
2523
Chris Lattner11ffd592004-07-20 05:21:00 +00002524static bool ValueRequiresCast(const Value *V, const Type *Ty, TargetData *TD) {
Chris Lattnerdfae8be2003-07-24 17:35:25 +00002525 if (V->getType() == Ty || isa<Constant>(V)) return false;
2526 if (const CastInst *CI = dyn_cast<CastInst>(V))
Chris Lattner11ffd592004-07-20 05:21:00 +00002527 if (isEliminableCastOfCast(CI->getOperand(0)->getType(), CI->getType(), Ty,
2528 TD))
Chris Lattnerdfae8be2003-07-24 17:35:25 +00002529 return false;
2530 return true;
2531}
2532
2533/// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
2534/// InsertBefore instruction. This is specialized a bit to avoid inserting
2535/// casts that are known to not do anything...
2536///
2537Value *InstCombiner::InsertOperandCastBefore(Value *V, const Type *DestTy,
2538 Instruction *InsertBefore) {
2539 if (V->getType() == DestTy) return V;
2540 if (Constant *C = dyn_cast<Constant>(V))
2541 return ConstantExpr::getCast(C, DestTy);
2542
2543 CastInst *CI = new CastInst(V, DestTy, V->getName());
2544 InsertNewInstBefore(CI, *InsertBefore);
2545 return CI;
2546}
Chris Lattner48a44f72002-05-02 17:06:02 +00002547
2548// CastInst simplification
Chris Lattner260ab202002-04-18 17:39:14 +00002549//
Chris Lattner113f4f42002-06-25 16:13:24 +00002550Instruction *InstCombiner::visitCastInst(CastInst &CI) {
Chris Lattner55d4bda2003-06-23 21:59:52 +00002551 Value *Src = CI.getOperand(0);
2552
Chris Lattner48a44f72002-05-02 17:06:02 +00002553 // If the user is casting a value to the same type, eliminate this cast
2554 // instruction...
Chris Lattner55d4bda2003-06-23 21:59:52 +00002555 if (CI.getType() == Src->getType())
2556 return ReplaceInstUsesWith(CI, Src);
Chris Lattner48a44f72002-05-02 17:06:02 +00002557
Chris Lattner48a44f72002-05-02 17:06:02 +00002558 // If casting the result of another cast instruction, try to eliminate this
2559 // one!
2560 //
Chris Lattner55d4bda2003-06-23 21:59:52 +00002561 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) {
Chris Lattnerdfae8be2003-07-24 17:35:25 +00002562 if (isEliminableCastOfCast(CSrc->getOperand(0)->getType(),
Chris Lattner11ffd592004-07-20 05:21:00 +00002563 CSrc->getType(), CI.getType(), TD)) {
Chris Lattner48a44f72002-05-02 17:06:02 +00002564 // This instruction now refers directly to the cast's src operand. This
2565 // has a good chance of making CSrc dead.
Chris Lattner113f4f42002-06-25 16:13:24 +00002566 CI.setOperand(0, CSrc->getOperand(0));
2567 return &CI;
Chris Lattner48a44f72002-05-02 17:06:02 +00002568 }
2569
Chris Lattner650b6da2002-08-02 20:00:25 +00002570 // If this is an A->B->A cast, and we are dealing with integral types, try
2571 // to convert this into a logical 'and' instruction.
2572 //
2573 if (CSrc->getOperand(0)->getType() == CI.getType() &&
Chris Lattnerb0b412e2002-09-03 01:08:28 +00002574 CI.getType()->isInteger() && CSrc->getType()->isInteger() &&
Chris Lattner650b6da2002-08-02 20:00:25 +00002575 CI.getType()->isUnsigned() && CSrc->getType()->isUnsigned() &&
2576 CSrc->getType()->getPrimitiveSize() < CI.getType()->getPrimitiveSize()){
2577 assert(CSrc->getType() != Type::ULongTy &&
2578 "Cannot have type bigger than ulong!");
Chris Lattner196897c2003-05-26 23:41:32 +00002579 uint64_t AndValue = (1ULL << CSrc->getType()->getPrimitiveSize()*8)-1;
Chris Lattner650b6da2002-08-02 20:00:25 +00002580 Constant *AndOp = ConstantUInt::get(CI.getType(), AndValue);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002581 return BinaryOperator::createAnd(CSrc->getOperand(0), AndOp);
Chris Lattner650b6da2002-08-02 20:00:25 +00002582 }
2583 }
2584
Chris Lattner03841652004-05-25 04:29:21 +00002585 // If this is a cast to bool, turn it into the appropriate setne instruction.
2586 if (CI.getType() == Type::BoolTy)
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002587 return BinaryOperator::createSetNE(CI.getOperand(0),
Chris Lattner03841652004-05-25 04:29:21 +00002588 Constant::getNullValue(CI.getOperand(0)->getType()));
2589
Chris Lattnerd0d51602003-06-21 23:12:02 +00002590 // If casting the result of a getelementptr instruction with no offset, turn
2591 // this into a cast of the original pointer!
2592 //
Chris Lattner55d4bda2003-06-23 21:59:52 +00002593 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
Chris Lattnerd0d51602003-06-21 23:12:02 +00002594 bool AllZeroOperands = true;
2595 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i)
2596 if (!isa<Constant>(GEP->getOperand(i)) ||
2597 !cast<Constant>(GEP->getOperand(i))->isNullValue()) {
2598 AllZeroOperands = false;
2599 break;
2600 }
2601 if (AllZeroOperands) {
2602 CI.setOperand(0, GEP->getOperand(0));
2603 return &CI;
2604 }
2605 }
2606
Chris Lattnerf4ad1652003-11-02 05:57:39 +00002607 // If we are casting a malloc or alloca to a pointer to a type of the same
2608 // size, rewrite the allocation instruction to allocate the "right" type.
2609 //
2610 if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
Chris Lattnerd4d987d2003-11-02 06:54:48 +00002611 if (AI->hasOneUse() && !AI->isArrayAllocation())
Chris Lattnerf4ad1652003-11-02 05:57:39 +00002612 if (const PointerType *PTy = dyn_cast<PointerType>(CI.getType())) {
2613 // Get the type really allocated and the type casted to...
2614 const Type *AllocElTy = AI->getAllocatedType();
Chris Lattnerf4ad1652003-11-02 05:57:39 +00002615 const Type *CastElTy = PTy->getElementType();
Chris Lattner9eb9ccd2004-07-06 19:28:42 +00002616 if (AllocElTy->isSized() && CastElTy->isSized()) {
2617 unsigned AllocElTySize = TD->getTypeSize(AllocElTy);
2618 unsigned CastElTySize = TD->getTypeSize(CastElTy);
Chris Lattner7c94d112003-11-05 17:31:36 +00002619
Chris Lattner9eb9ccd2004-07-06 19:28:42 +00002620 // If the allocation is for an even multiple of the cast type size
2621 if (CastElTySize && (AllocElTySize % CastElTySize == 0)) {
2622 Value *Amt = ConstantUInt::get(Type::UIntTy,
Chris Lattnerf4ad1652003-11-02 05:57:39 +00002623 AllocElTySize/CastElTySize);
Chris Lattner9eb9ccd2004-07-06 19:28:42 +00002624 std::string Name = AI->getName(); AI->setName("");
2625 AllocationInst *New;
2626 if (isa<MallocInst>(AI))
2627 New = new MallocInst(CastElTy, Amt, Name);
2628 else
2629 New = new AllocaInst(CastElTy, Amt, Name);
2630 InsertNewInstBefore(New, *AI);
2631 return ReplaceInstUsesWith(CI, New);
2632 }
Chris Lattnerf4ad1652003-11-02 05:57:39 +00002633 }
2634 }
2635
Chris Lattner6a4adcd2004-09-29 05:07:12 +00002636 if (isa<PHINode>(Src))
2637 if (Instruction *NV = FoldOpIntoPhi(CI))
2638 return NV;
2639
Chris Lattnerdfae8be2003-07-24 17:35:25 +00002640 // If the source value is an instruction with only this use, we can attempt to
2641 // propagate the cast into the instruction. Also, only handle integral types
2642 // for now.
2643 if (Instruction *SrcI = dyn_cast<Instruction>(Src))
Chris Lattnerf95d9b92003-10-15 16:48:29 +00002644 if (SrcI->hasOneUse() && Src->getType()->isIntegral() &&
Chris Lattnerdfae8be2003-07-24 17:35:25 +00002645 CI.getType()->isInteger()) { // Don't mess with casts to bool here
2646 const Type *DestTy = CI.getType();
2647 unsigned SrcBitSize = getTypeSizeInBits(Src->getType());
2648 unsigned DestBitSize = getTypeSizeInBits(DestTy);
2649
2650 Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
2651 Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
2652
2653 switch (SrcI->getOpcode()) {
2654 case Instruction::Add:
2655 case Instruction::Mul:
2656 case Instruction::And:
2657 case Instruction::Or:
2658 case Instruction::Xor:
2659 // If we are discarding information, or just changing the sign, rewrite.
2660 if (DestBitSize <= SrcBitSize && DestBitSize != 1) {
2661 // Don't insert two casts if they cannot be eliminated. We allow two
2662 // casts to be inserted if the sizes are the same. This could only be
2663 // converting signedness, which is a noop.
Chris Lattner11ffd592004-07-20 05:21:00 +00002664 if (DestBitSize == SrcBitSize || !ValueRequiresCast(Op1, DestTy,TD) ||
2665 !ValueRequiresCast(Op0, DestTy, TD)) {
Chris Lattnerdfae8be2003-07-24 17:35:25 +00002666 Value *Op0c = InsertOperandCastBefore(Op0, DestTy, SrcI);
2667 Value *Op1c = InsertOperandCastBefore(Op1, DestTy, SrcI);
2668 return BinaryOperator::create(cast<BinaryOperator>(SrcI)
2669 ->getOpcode(), Op0c, Op1c);
2670 }
2671 }
2672 break;
2673 case Instruction::Shl:
2674 // Allow changing the sign of the source operand. Do not allow changing
2675 // the size of the shift, UNLESS the shift amount is a constant. We
2676 // mush not change variable sized shifts to a smaller size, because it
2677 // is undefined to shift more bits out than exist in the value.
2678 if (DestBitSize == SrcBitSize ||
2679 (DestBitSize < SrcBitSize && isa<Constant>(Op1))) {
2680 Value *Op0c = InsertOperandCastBefore(Op0, DestTy, SrcI);
2681 return new ShiftInst(Instruction::Shl, Op0c, Op1);
2682 }
2683 break;
2684 }
2685 }
2686
Chris Lattner260ab202002-04-18 17:39:14 +00002687 return 0;
Chris Lattnerca081252001-12-14 16:52:21 +00002688}
2689
Chris Lattner56e4d3d2004-04-09 23:46:01 +00002690/// GetSelectFoldableOperands - We want to turn code that looks like this:
2691/// %C = or %A, %B
2692/// %D = select %cond, %C, %A
2693/// into:
2694/// %C = select %cond, %B, 0
2695/// %D = or %A, %C
2696///
2697/// Assuming that the specified instruction is an operand to the select, return
2698/// a bitmask indicating which operands of this instruction are foldable if they
2699/// equal the other incoming value of the select.
2700///
2701static unsigned GetSelectFoldableOperands(Instruction *I) {
2702 switch (I->getOpcode()) {
2703 case Instruction::Add:
2704 case Instruction::Mul:
2705 case Instruction::And:
2706 case Instruction::Or:
2707 case Instruction::Xor:
2708 return 3; // Can fold through either operand.
2709 case Instruction::Sub: // Can only fold on the amount subtracted.
2710 case Instruction::Shl: // Can only fold on the shift amount.
2711 case Instruction::Shr:
2712 return 1;
2713 default:
2714 return 0; // Cannot fold
2715 }
2716}
2717
2718/// GetSelectFoldableConstant - For the same transformation as the previous
2719/// function, return the identity constant that goes into the select.
2720static Constant *GetSelectFoldableConstant(Instruction *I) {
2721 switch (I->getOpcode()) {
2722 default: assert(0 && "This cannot happen!"); abort();
2723 case Instruction::Add:
2724 case Instruction::Sub:
2725 case Instruction::Or:
2726 case Instruction::Xor:
2727 return Constant::getNullValue(I->getType());
2728 case Instruction::Shl:
2729 case Instruction::Shr:
2730 return Constant::getNullValue(Type::UByteTy);
2731 case Instruction::And:
2732 return ConstantInt::getAllOnesValue(I->getType());
2733 case Instruction::Mul:
2734 return ConstantInt::get(I->getType(), 1);
2735 }
2736}
2737
Chris Lattnerb909e8b2004-03-12 05:52:32 +00002738Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
Chris Lattner533bc492004-03-30 19:37:13 +00002739 Value *CondVal = SI.getCondition();
2740 Value *TrueVal = SI.getTrueValue();
2741 Value *FalseVal = SI.getFalseValue();
2742
2743 // select true, X, Y -> X
2744 // select false, X, Y -> Y
2745 if (ConstantBool *C = dyn_cast<ConstantBool>(CondVal))
Chris Lattnerb909e8b2004-03-12 05:52:32 +00002746 if (C == ConstantBool::True)
Chris Lattner533bc492004-03-30 19:37:13 +00002747 return ReplaceInstUsesWith(SI, TrueVal);
Chris Lattnerb909e8b2004-03-12 05:52:32 +00002748 else {
2749 assert(C == ConstantBool::False);
Chris Lattner533bc492004-03-30 19:37:13 +00002750 return ReplaceInstUsesWith(SI, FalseVal);
Chris Lattnerb909e8b2004-03-12 05:52:32 +00002751 }
Chris Lattner533bc492004-03-30 19:37:13 +00002752
2753 // select C, X, X -> X
2754 if (TrueVal == FalseVal)
2755 return ReplaceInstUsesWith(SI, TrueVal);
2756
Chris Lattner1c631e82004-04-08 04:43:23 +00002757 if (SI.getType() == Type::BoolTy)
2758 if (ConstantBool *C = dyn_cast<ConstantBool>(TrueVal)) {
2759 if (C == ConstantBool::True) {
2760 // Change: A = select B, true, C --> A = or B, C
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002761 return BinaryOperator::createOr(CondVal, FalseVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00002762 } else {
2763 // Change: A = select B, false, C --> A = and !B, C
2764 Value *NotCond =
2765 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
2766 "not."+CondVal->getName()), SI);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002767 return BinaryOperator::createAnd(NotCond, FalseVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00002768 }
2769 } else if (ConstantBool *C = dyn_cast<ConstantBool>(FalseVal)) {
2770 if (C == ConstantBool::False) {
2771 // Change: A = select B, C, false --> A = and B, C
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002772 return BinaryOperator::createAnd(CondVal, TrueVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00002773 } else {
2774 // Change: A = select B, C, true --> A = or !B, C
2775 Value *NotCond =
2776 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
2777 "not."+CondVal->getName()), SI);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002778 return BinaryOperator::createOr(NotCond, TrueVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00002779 }
2780 }
2781
Chris Lattner183b3362004-04-09 19:05:30 +00002782 // Selecting between two integer constants?
2783 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
2784 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
2785 // select C, 1, 0 -> cast C to int
2786 if (FalseValC->isNullValue() && TrueValC->getRawValue() == 1) {
2787 return new CastInst(CondVal, SI.getType());
2788 } else if (TrueValC->isNullValue() && FalseValC->getRawValue() == 1) {
2789 // select C, 0, 1 -> cast !C to int
2790 Value *NotCond =
2791 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
Chris Lattnercf7baf32004-04-09 18:19:44 +00002792 "not."+CondVal->getName()), SI);
Chris Lattner183b3362004-04-09 19:05:30 +00002793 return new CastInst(NotCond, SI.getType());
Chris Lattnercf7baf32004-04-09 18:19:44 +00002794 }
Chris Lattner35167c32004-06-09 07:59:58 +00002795
2796 // If one of the constants is zero (we know they can't both be) and we
2797 // have a setcc instruction with zero, and we have an 'and' with the
2798 // non-constant value, eliminate this whole mess. This corresponds to
2799 // cases like this: ((X & 27) ? 27 : 0)
2800 if (TrueValC->isNullValue() || FalseValC->isNullValue())
2801 if (Instruction *IC = dyn_cast<Instruction>(SI.getCondition()))
2802 if ((IC->getOpcode() == Instruction::SetEQ ||
2803 IC->getOpcode() == Instruction::SetNE) &&
2804 isa<ConstantInt>(IC->getOperand(1)) &&
2805 cast<Constant>(IC->getOperand(1))->isNullValue())
2806 if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
2807 if (ICA->getOpcode() == Instruction::And &&
2808 isa<ConstantInt>(ICA->getOperand(1)) &&
2809 (ICA->getOperand(1) == TrueValC ||
2810 ICA->getOperand(1) == FalseValC) &&
2811 isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
2812 // Okay, now we know that everything is set up, we just don't
2813 // know whether we have a setne or seteq and whether the true or
2814 // false val is the zero.
2815 bool ShouldNotVal = !TrueValC->isNullValue();
2816 ShouldNotVal ^= IC->getOpcode() == Instruction::SetNE;
2817 Value *V = ICA;
2818 if (ShouldNotVal)
2819 V = InsertNewInstBefore(BinaryOperator::create(
2820 Instruction::Xor, V, ICA->getOperand(1)), SI);
2821 return ReplaceInstUsesWith(SI, V);
2822 }
Chris Lattner533bc492004-03-30 19:37:13 +00002823 }
Chris Lattner623fba12004-04-10 22:21:27 +00002824
2825 // See if we are selecting two values based on a comparison of the two values.
2826 if (SetCondInst *SCI = dyn_cast<SetCondInst>(CondVal)) {
2827 if (SCI->getOperand(0) == TrueVal && SCI->getOperand(1) == FalseVal) {
2828 // Transform (X == Y) ? X : Y -> Y
2829 if (SCI->getOpcode() == Instruction::SetEQ)
2830 return ReplaceInstUsesWith(SI, FalseVal);
2831 // Transform (X != Y) ? X : Y -> X
2832 if (SCI->getOpcode() == Instruction::SetNE)
2833 return ReplaceInstUsesWith(SI, TrueVal);
2834 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
2835
2836 } else if (SCI->getOperand(0) == FalseVal && SCI->getOperand(1) == TrueVal){
2837 // Transform (X == Y) ? Y : X -> X
2838 if (SCI->getOpcode() == Instruction::SetEQ)
Chris Lattner24cf0202004-04-11 01:39:19 +00002839 return ReplaceInstUsesWith(SI, FalseVal);
Chris Lattner623fba12004-04-10 22:21:27 +00002840 // Transform (X != Y) ? Y : X -> Y
2841 if (SCI->getOpcode() == Instruction::SetNE)
Chris Lattner24cf0202004-04-11 01:39:19 +00002842 return ReplaceInstUsesWith(SI, TrueVal);
Chris Lattner623fba12004-04-10 22:21:27 +00002843 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
2844 }
2845 }
Chris Lattner1c631e82004-04-08 04:43:23 +00002846
Chris Lattner56e4d3d2004-04-09 23:46:01 +00002847 // See if we can fold the select into one of our operands.
2848 if (SI.getType()->isInteger()) {
2849 // See the comment above GetSelectFoldableOperands for a description of the
2850 // transformation we are doing here.
2851 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal))
2852 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
2853 !isa<Constant>(FalseVal))
2854 if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
2855 unsigned OpToFold = 0;
2856 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
2857 OpToFold = 1;
2858 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
2859 OpToFold = 2;
2860 }
2861
2862 if (OpToFold) {
2863 Constant *C = GetSelectFoldableConstant(TVI);
2864 std::string Name = TVI->getName(); TVI->setName("");
2865 Instruction *NewSel =
2866 new SelectInst(SI.getCondition(), TVI->getOperand(2-OpToFold), C,
2867 Name);
2868 InsertNewInstBefore(NewSel, SI);
2869 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
2870 return BinaryOperator::create(BO->getOpcode(), FalseVal, NewSel);
2871 else if (ShiftInst *SI = dyn_cast<ShiftInst>(TVI))
2872 return new ShiftInst(SI->getOpcode(), FalseVal, NewSel);
2873 else {
2874 assert(0 && "Unknown instruction!!");
2875 }
2876 }
2877 }
2878
2879 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal))
2880 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
2881 !isa<Constant>(TrueVal))
2882 if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
2883 unsigned OpToFold = 0;
2884 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
2885 OpToFold = 1;
2886 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
2887 OpToFold = 2;
2888 }
2889
2890 if (OpToFold) {
2891 Constant *C = GetSelectFoldableConstant(FVI);
2892 std::string Name = FVI->getName(); FVI->setName("");
2893 Instruction *NewSel =
2894 new SelectInst(SI.getCondition(), C, FVI->getOperand(2-OpToFold),
2895 Name);
2896 InsertNewInstBefore(NewSel, SI);
2897 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
2898 return BinaryOperator::create(BO->getOpcode(), TrueVal, NewSel);
2899 else if (ShiftInst *SI = dyn_cast<ShiftInst>(FVI))
2900 return new ShiftInst(SI->getOpcode(), TrueVal, NewSel);
2901 else {
2902 assert(0 && "Unknown instruction!!");
2903 }
2904 }
2905 }
2906 }
Chris Lattnerb909e8b2004-03-12 05:52:32 +00002907 return 0;
2908}
2909
2910
Chris Lattner970c33a2003-06-19 17:00:31 +00002911// CallInst simplification
2912//
2913Instruction *InstCombiner::visitCallInst(CallInst &CI) {
Chris Lattner51ea1272004-02-28 05:22:00 +00002914 // Intrinsics cannot occur in an invoke, so handle them here instead of in
2915 // visitCallSite.
2916 if (Function *F = CI.getCalledFunction())
2917 switch (F->getIntrinsicID()) {
2918 case Intrinsic::memmove:
2919 case Intrinsic::memcpy:
2920 case Intrinsic::memset:
2921 // memmove/cpy/set of zero bytes is a noop.
2922 if (Constant *NumBytes = dyn_cast<Constant>(CI.getOperand(3))) {
2923 if (NumBytes->isNullValue())
2924 return EraseInstFromFunction(CI);
2925 }
2926 break;
2927 default:
2928 break;
2929 }
2930
Chris Lattneraec3d942003-10-07 22:32:43 +00002931 return visitCallSite(&CI);
Chris Lattner970c33a2003-06-19 17:00:31 +00002932}
2933
2934// InvokeInst simplification
2935//
2936Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
Chris Lattneraec3d942003-10-07 22:32:43 +00002937 return visitCallSite(&II);
Chris Lattner970c33a2003-06-19 17:00:31 +00002938}
2939
Chris Lattneraec3d942003-10-07 22:32:43 +00002940// visitCallSite - Improvements for call and invoke instructions.
2941//
2942Instruction *InstCombiner::visitCallSite(CallSite CS) {
Chris Lattner75b4d1d2003-10-07 22:54:13 +00002943 bool Changed = false;
2944
2945 // If the callee is a constexpr cast of a function, attempt to move the cast
2946 // to the arguments of the call/invoke.
Chris Lattneraec3d942003-10-07 22:32:43 +00002947 if (transformConstExprCastCall(CS)) return 0;
2948
Chris Lattner75b4d1d2003-10-07 22:54:13 +00002949 Value *Callee = CS.getCalledValue();
2950 const PointerType *PTy = cast<PointerType>(Callee->getType());
2951 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
2952 if (FTy->isVarArg()) {
2953 // See if we can optimize any arguments passed through the varargs area of
2954 // the call.
2955 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
2956 E = CS.arg_end(); I != E; ++I)
2957 if (CastInst *CI = dyn_cast<CastInst>(*I)) {
2958 // If this cast does not effect the value passed through the varargs
2959 // area, we can eliminate the use of the cast.
2960 Value *Op = CI->getOperand(0);
2961 if (CI->getType()->isLosslesslyConvertibleTo(Op->getType())) {
2962 *I = Op;
2963 Changed = true;
2964 }
2965 }
2966 }
Chris Lattneraec3d942003-10-07 22:32:43 +00002967
Chris Lattner75b4d1d2003-10-07 22:54:13 +00002968 return Changed ? CS.getInstruction() : 0;
Chris Lattneraec3d942003-10-07 22:32:43 +00002969}
2970
Chris Lattner970c33a2003-06-19 17:00:31 +00002971// transformConstExprCastCall - If the callee is a constexpr cast of a function,
2972// attempt to move the cast to the arguments of the call/invoke.
2973//
2974bool InstCombiner::transformConstExprCastCall(CallSite CS) {
2975 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
2976 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
Chris Lattnerf3edc492004-07-18 18:59:44 +00002977 if (CE->getOpcode() != Instruction::Cast || !isa<Function>(CE->getOperand(0)))
Chris Lattner970c33a2003-06-19 17:00:31 +00002978 return false;
Reid Spencer87436872004-07-18 00:38:32 +00002979 Function *Callee = cast<Function>(CE->getOperand(0));
Chris Lattner970c33a2003-06-19 17:00:31 +00002980 Instruction *Caller = CS.getInstruction();
2981
2982 // Okay, this is a cast from a function to a different type. Unless doing so
2983 // would cause a type conversion of one of our arguments, change this call to
2984 // be a direct call with arguments casted to the appropriate types.
2985 //
2986 const FunctionType *FT = Callee->getFunctionType();
2987 const Type *OldRetTy = Caller->getType();
2988
Chris Lattner1f7942f2004-01-14 06:06:08 +00002989 // Check to see if we are changing the return type...
2990 if (OldRetTy != FT->getReturnType()) {
2991 if (Callee->isExternal() &&
2992 !OldRetTy->isLosslesslyConvertibleTo(FT->getReturnType()) &&
2993 !Caller->use_empty())
2994 return false; // Cannot transform this return value...
2995
2996 // If the callsite is an invoke instruction, and the return value is used by
2997 // a PHI node in a successor, we cannot change the return type of the call
2998 // because there is no place to put the cast instruction (without breaking
2999 // the critical edge). Bail out in this case.
3000 if (!Caller->use_empty())
3001 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
3002 for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
3003 UI != E; ++UI)
3004 if (PHINode *PN = dyn_cast<PHINode>(*UI))
3005 if (PN->getParent() == II->getNormalDest() ||
Chris Lattnerfae8ab32004-02-08 21:44:31 +00003006 PN->getParent() == II->getUnwindDest())
Chris Lattner1f7942f2004-01-14 06:06:08 +00003007 return false;
3008 }
Chris Lattner970c33a2003-06-19 17:00:31 +00003009
3010 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
3011 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
3012
3013 CallSite::arg_iterator AI = CS.arg_begin();
3014 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
3015 const Type *ParamTy = FT->getParamType(i);
3016 bool isConvertible = (*AI)->getType()->isLosslesslyConvertibleTo(ParamTy);
3017 if (Callee->isExternal() && !isConvertible) return false;
3018 }
3019
3020 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
3021 Callee->isExternal())
3022 return false; // Do not delete arguments unless we have a function body...
3023
3024 // Okay, we decided that this is a safe thing to do: go ahead and start
3025 // inserting cast instructions as necessary...
3026 std::vector<Value*> Args;
3027 Args.reserve(NumActualArgs);
3028
3029 AI = CS.arg_begin();
3030 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
3031 const Type *ParamTy = FT->getParamType(i);
3032 if ((*AI)->getType() == ParamTy) {
3033 Args.push_back(*AI);
3034 } else {
Chris Lattner1c631e82004-04-08 04:43:23 +00003035 Args.push_back(InsertNewInstBefore(new CastInst(*AI, ParamTy, "tmp"),
3036 *Caller));
Chris Lattner970c33a2003-06-19 17:00:31 +00003037 }
3038 }
3039
3040 // If the function takes more arguments than the call was taking, add them
3041 // now...
3042 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
3043 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
3044
3045 // If we are removing arguments to the function, emit an obnoxious warning...
3046 if (FT->getNumParams() < NumActualArgs)
3047 if (!FT->isVarArg()) {
3048 std::cerr << "WARNING: While resolving call to function '"
3049 << Callee->getName() << "' arguments were dropped!\n";
3050 } else {
3051 // Add all of the arguments in their promoted form to the arg list...
3052 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
3053 const Type *PTy = getPromotedType((*AI)->getType());
3054 if (PTy != (*AI)->getType()) {
3055 // Must promote to pass through va_arg area!
3056 Instruction *Cast = new CastInst(*AI, PTy, "tmp");
3057 InsertNewInstBefore(Cast, *Caller);
3058 Args.push_back(Cast);
3059 } else {
3060 Args.push_back(*AI);
3061 }
3062 }
3063 }
3064
3065 if (FT->getReturnType() == Type::VoidTy)
3066 Caller->setName(""); // Void type should not have a name...
3067
3068 Instruction *NC;
3069 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Chris Lattnerfae8ab32004-02-08 21:44:31 +00003070 NC = new InvokeInst(Callee, II->getNormalDest(), II->getUnwindDest(),
Chris Lattner970c33a2003-06-19 17:00:31 +00003071 Args, Caller->getName(), Caller);
3072 } else {
3073 NC = new CallInst(Callee, Args, Caller->getName(), Caller);
3074 }
3075
3076 // Insert a cast of the return type as necessary...
3077 Value *NV = NC;
3078 if (Caller->getType() != NV->getType() && !Caller->use_empty()) {
3079 if (NV->getType() != Type::VoidTy) {
3080 NV = NC = new CastInst(NC, Caller->getType(), "tmp");
Chris Lattner686767f2003-10-30 00:46:41 +00003081
3082 // If this is an invoke instruction, we should insert it after the first
3083 // non-phi, instruction in the normal successor block.
3084 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
3085 BasicBlock::iterator I = II->getNormalDest()->begin();
3086 while (isa<PHINode>(I)) ++I;
3087 InsertNewInstBefore(NC, *I);
3088 } else {
3089 // Otherwise, it's a call, just insert cast right after the call instr
3090 InsertNewInstBefore(NC, *Caller);
3091 }
Chris Lattner51ea1272004-02-28 05:22:00 +00003092 AddUsersToWorkList(*Caller);
Chris Lattner970c33a2003-06-19 17:00:31 +00003093 } else {
3094 NV = Constant::getNullValue(Caller->getType());
3095 }
3096 }
3097
3098 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
3099 Caller->replaceAllUsesWith(NV);
3100 Caller->getParent()->getInstList().erase(Caller);
3101 removeFromWorkList(Caller);
3102 return true;
3103}
3104
3105
Chris Lattner48a44f72002-05-02 17:06:02 +00003106
Chris Lattnerbbbdd852002-05-06 18:06:38 +00003107// PHINode simplification
3108//
Chris Lattner113f4f42002-06-25 16:13:24 +00003109Instruction *InstCombiner::visitPHINode(PHINode &PN) {
Chris Lattner91daeb52003-12-19 05:58:40 +00003110 if (Value *V = hasConstantValue(&PN))
3111 return ReplaceInstUsesWith(PN, V);
Chris Lattner4db2d222004-02-16 05:07:08 +00003112
3113 // If the only user of this instruction is a cast instruction, and all of the
3114 // incoming values are constants, change this PHI to merge together the casted
3115 // constants.
3116 if (PN.hasOneUse())
3117 if (CastInst *CI = dyn_cast<CastInst>(PN.use_back()))
3118 if (CI->getType() != PN.getType()) { // noop casts will be folded
3119 bool AllConstant = true;
3120 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
3121 if (!isa<Constant>(PN.getIncomingValue(i))) {
3122 AllConstant = false;
3123 break;
3124 }
3125 if (AllConstant) {
3126 // Make a new PHI with all casted values.
3127 PHINode *New = new PHINode(CI->getType(), PN.getName(), &PN);
3128 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
3129 Constant *OldArg = cast<Constant>(PN.getIncomingValue(i));
3130 New->addIncoming(ConstantExpr::getCast(OldArg, New->getType()),
3131 PN.getIncomingBlock(i));
3132 }
3133
3134 // Update the cast instruction.
3135 CI->setOperand(0, New);
3136 WorkList.push_back(CI); // revisit the cast instruction to fold.
3137 WorkList.push_back(New); // Make sure to revisit the new Phi
3138 return &PN; // PN is now dead!
3139 }
3140 }
Chris Lattner91daeb52003-12-19 05:58:40 +00003141 return 0;
Chris Lattnerbbbdd852002-05-06 18:06:38 +00003142}
3143
Chris Lattner69193f92004-04-05 01:30:19 +00003144static Value *InsertSignExtendToPtrTy(Value *V, const Type *DTy,
3145 Instruction *InsertPoint,
3146 InstCombiner *IC) {
3147 unsigned PS = IC->getTargetData().getPointerSize();
3148 const Type *VTy = V->getType();
3149 Instruction *Cast;
3150 if (!VTy->isSigned() && VTy->getPrimitiveSize() < PS)
3151 // We must insert a cast to ensure we sign-extend.
3152 V = IC->InsertNewInstBefore(new CastInst(V, VTy->getSignedVersion(),
3153 V->getName()), *InsertPoint);
3154 return IC->InsertNewInstBefore(new CastInst(V, DTy, V->getName()),
3155 *InsertPoint);
3156}
3157
Chris Lattner48a44f72002-05-02 17:06:02 +00003158
Chris Lattner113f4f42002-06-25 16:13:24 +00003159Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
Chris Lattner5f667a62004-05-07 22:09:22 +00003160 Value *PtrOp = GEP.getOperand(0);
Chris Lattner471bd762003-05-22 19:07:21 +00003161 // Is it 'getelementptr %P, long 0' or 'getelementptr %P'
Chris Lattner113f4f42002-06-25 16:13:24 +00003162 // If so, eliminate the noop.
Chris Lattner8d0bacb2004-02-22 05:25:17 +00003163 if (GEP.getNumOperands() == 1)
Chris Lattner5f667a62004-05-07 22:09:22 +00003164 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattner8d0bacb2004-02-22 05:25:17 +00003165
3166 bool HasZeroPointerIndex = false;
3167 if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
3168 HasZeroPointerIndex = C->isNullValue();
3169
3170 if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
Chris Lattner5f667a62004-05-07 22:09:22 +00003171 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattner48a44f72002-05-02 17:06:02 +00003172
Chris Lattner69193f92004-04-05 01:30:19 +00003173 // Eliminate unneeded casts for indices.
3174 bool MadeChange = false;
Chris Lattner2b2412d2004-04-07 18:38:20 +00003175 gep_type_iterator GTI = gep_type_begin(GEP);
3176 for (unsigned i = 1, e = GEP.getNumOperands(); i != e; ++i, ++GTI)
3177 if (isa<SequentialType>(*GTI)) {
3178 if (CastInst *CI = dyn_cast<CastInst>(GEP.getOperand(i))) {
3179 Value *Src = CI->getOperand(0);
3180 const Type *SrcTy = Src->getType();
3181 const Type *DestTy = CI->getType();
3182 if (Src->getType()->isInteger()) {
3183 if (SrcTy->getPrimitiveSize() == DestTy->getPrimitiveSize()) {
3184 // We can always eliminate a cast from ulong or long to the other.
3185 // We can always eliminate a cast from uint to int or the other on
3186 // 32-bit pointer platforms.
3187 if (DestTy->getPrimitiveSize() >= TD->getPointerSize()) {
3188 MadeChange = true;
3189 GEP.setOperand(i, Src);
3190 }
3191 } else if (SrcTy->getPrimitiveSize() < DestTy->getPrimitiveSize() &&
3192 SrcTy->getPrimitiveSize() == 4) {
3193 // We can always eliminate a cast from int to [u]long. We can
3194 // eliminate a cast from uint to [u]long iff the target is a 32-bit
3195 // pointer target.
3196 if (SrcTy->isSigned() ||
3197 SrcTy->getPrimitiveSize() >= TD->getPointerSize()) {
3198 MadeChange = true;
3199 GEP.setOperand(i, Src);
3200 }
Chris Lattner69193f92004-04-05 01:30:19 +00003201 }
3202 }
3203 }
Chris Lattner2b2412d2004-04-07 18:38:20 +00003204 // If we are using a wider index than needed for this platform, shrink it
3205 // to what we need. If the incoming value needs a cast instruction,
3206 // insert it. This explicit cast can make subsequent optimizations more
3207 // obvious.
3208 Value *Op = GEP.getOperand(i);
3209 if (Op->getType()->getPrimitiveSize() > TD->getPointerSize())
Chris Lattner1e9ac1a2004-04-17 18:16:10 +00003210 if (Constant *C = dyn_cast<Constant>(Op)) {
Chris Lattner44d0b952004-07-20 01:48:15 +00003211 GEP.setOperand(i, ConstantExpr::getCast(C,
3212 TD->getIntPtrType()->getSignedVersion()));
Chris Lattner1e9ac1a2004-04-17 18:16:10 +00003213 MadeChange = true;
3214 } else {
Chris Lattner2b2412d2004-04-07 18:38:20 +00003215 Op = InsertNewInstBefore(new CastInst(Op, TD->getIntPtrType(),
3216 Op->getName()), GEP);
3217 GEP.setOperand(i, Op);
3218 MadeChange = true;
3219 }
Chris Lattner44d0b952004-07-20 01:48:15 +00003220
3221 // If this is a constant idx, make sure to canonicalize it to be a signed
3222 // operand, otherwise CSE and other optimizations are pessimized.
3223 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(Op)) {
3224 GEP.setOperand(i, ConstantExpr::getCast(CUI,
3225 CUI->getType()->getSignedVersion()));
3226 MadeChange = true;
3227 }
Chris Lattner69193f92004-04-05 01:30:19 +00003228 }
3229 if (MadeChange) return &GEP;
3230
Chris Lattnerae7a0d32002-08-02 19:29:35 +00003231 // Combine Indices - If the source pointer to this getelementptr instruction
3232 // is a getelementptr instruction, combine the indices of the two
3233 // getelementptr instructions into a single instruction.
3234 //
Chris Lattner57c67b02004-03-25 22:59:29 +00003235 std::vector<Value*> SrcGEPOperands;
Chris Lattner5f667a62004-05-07 22:09:22 +00003236 if (GetElementPtrInst *Src = dyn_cast<GetElementPtrInst>(PtrOp)) {
Chris Lattner57c67b02004-03-25 22:59:29 +00003237 SrcGEPOperands.assign(Src->op_begin(), Src->op_end());
Chris Lattner5f667a62004-05-07 22:09:22 +00003238 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(PtrOp)) {
Chris Lattner57c67b02004-03-25 22:59:29 +00003239 if (CE->getOpcode() == Instruction::GetElementPtr)
3240 SrcGEPOperands.assign(CE->op_begin(), CE->op_end());
3241 }
3242
3243 if (!SrcGEPOperands.empty()) {
Chris Lattner5f667a62004-05-07 22:09:22 +00003244 // Note that if our source is a gep chain itself that we wait for that
3245 // chain to be resolved before we perform this transformation. This
3246 // avoids us creating a TON of code in some cases.
3247 //
3248 if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
3249 cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
3250 return 0; // Wait until our source is folded to completion.
3251
Chris Lattnerae7a0d32002-08-02 19:29:35 +00003252 std::vector<Value *> Indices;
Chris Lattner5f667a62004-05-07 22:09:22 +00003253
3254 // Find out whether the last index in the source GEP is a sequential idx.
3255 bool EndsWithSequential = false;
3256 for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
3257 E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
Chris Lattner8ec5f882004-05-08 22:41:42 +00003258 EndsWithSequential = !isa<StructType>(*I);
Chris Lattnerca081252001-12-14 16:52:21 +00003259
Chris Lattnerae7a0d32002-08-02 19:29:35 +00003260 // Can we combine the two pointer arithmetics offsets?
Chris Lattner5f667a62004-05-07 22:09:22 +00003261 if (EndsWithSequential) {
Chris Lattner235af562003-03-05 22:33:14 +00003262 // Replace: gep (gep %P, long B), long A, ...
3263 // With: T = long A+B; gep %P, T, ...
3264 //
Chris Lattner5f667a62004-05-07 22:09:22 +00003265 Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
Chris Lattner69193f92004-04-05 01:30:19 +00003266 if (SO1 == Constant::getNullValue(SO1->getType())) {
3267 Sum = GO1;
3268 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
3269 Sum = SO1;
3270 } else {
3271 // If they aren't the same type, convert both to an integer of the
3272 // target's pointer size.
3273 if (SO1->getType() != GO1->getType()) {
3274 if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
3275 SO1 = ConstantExpr::getCast(SO1C, GO1->getType());
3276 } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
3277 GO1 = ConstantExpr::getCast(GO1C, SO1->getType());
3278 } else {
3279 unsigned PS = TD->getPointerSize();
3280 Instruction *Cast;
3281 if (SO1->getType()->getPrimitiveSize() == PS) {
3282 // Convert GO1 to SO1's type.
3283 GO1 = InsertSignExtendToPtrTy(GO1, SO1->getType(), &GEP, this);
3284
3285 } else if (GO1->getType()->getPrimitiveSize() == PS) {
3286 // Convert SO1 to GO1's type.
3287 SO1 = InsertSignExtendToPtrTy(SO1, GO1->getType(), &GEP, this);
3288 } else {
3289 const Type *PT = TD->getIntPtrType();
3290 SO1 = InsertSignExtendToPtrTy(SO1, PT, &GEP, this);
3291 GO1 = InsertSignExtendToPtrTy(GO1, PT, &GEP, this);
3292 }
3293 }
3294 }
Chris Lattner5f667a62004-05-07 22:09:22 +00003295 if (isa<Constant>(SO1) && isa<Constant>(GO1))
3296 Sum = ConstantExpr::getAdd(cast<Constant>(SO1), cast<Constant>(GO1));
3297 else {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003298 Sum = BinaryOperator::createAdd(SO1, GO1, PtrOp->getName()+".sum");
3299 InsertNewInstBefore(cast<Instruction>(Sum), GEP);
Chris Lattner5f667a62004-05-07 22:09:22 +00003300 }
Chris Lattner69193f92004-04-05 01:30:19 +00003301 }
Chris Lattner5f667a62004-05-07 22:09:22 +00003302
3303 // Recycle the GEP we already have if possible.
3304 if (SrcGEPOperands.size() == 2) {
3305 GEP.setOperand(0, SrcGEPOperands[0]);
3306 GEP.setOperand(1, Sum);
3307 return &GEP;
3308 } else {
3309 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
3310 SrcGEPOperands.end()-1);
3311 Indices.push_back(Sum);
3312 Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
3313 }
Chris Lattner69193f92004-04-05 01:30:19 +00003314 } else if (isa<Constant>(*GEP.idx_begin()) &&
3315 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
Chris Lattner57c67b02004-03-25 22:59:29 +00003316 SrcGEPOperands.size() != 1) {
Chris Lattnerae7a0d32002-08-02 19:29:35 +00003317 // Otherwise we can do the fold if the first index of the GEP is a zero
Chris Lattner57c67b02004-03-25 22:59:29 +00003318 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
3319 SrcGEPOperands.end());
Chris Lattnerae7a0d32002-08-02 19:29:35 +00003320 Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
3321 }
3322
3323 if (!Indices.empty())
Chris Lattner57c67b02004-03-25 22:59:29 +00003324 return new GetElementPtrInst(SrcGEPOperands[0], Indices, GEP.getName());
Chris Lattnerc59af1d2002-08-17 22:21:59 +00003325
Chris Lattner5f667a62004-05-07 22:09:22 +00003326 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
Chris Lattnerc59af1d2002-08-17 22:21:59 +00003327 // GEP of global variable. If all of the indices for this GEP are
3328 // constants, we can promote this to a constexpr instead of an instruction.
3329
3330 // Scan for nonconstants...
3331 std::vector<Constant*> Indices;
3332 User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
3333 for (; I != E && isa<Constant>(*I); ++I)
3334 Indices.push_back(cast<Constant>(*I));
3335
3336 if (I == E) { // If they are all constants...
Chris Lattnerf3edc492004-07-18 18:59:44 +00003337 Constant *CE = ConstantExpr::getGetElementPtr(GV, Indices);
Chris Lattnerc59af1d2002-08-17 22:21:59 +00003338
3339 // Replace all uses of the GEP with the new constexpr...
3340 return ReplaceInstUsesWith(GEP, CE);
3341 }
Chris Lattner5f667a62004-05-07 22:09:22 +00003342 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(PtrOp)) {
Chris Lattner8d0bacb2004-02-22 05:25:17 +00003343 if (CE->getOpcode() == Instruction::Cast) {
3344 if (HasZeroPointerIndex) {
3345 // transform: GEP (cast [10 x ubyte]* X to [0 x ubyte]*), long 0, ...
3346 // into : GEP [10 x ubyte]* X, long 0, ...
3347 //
3348 // This occurs when the program declares an array extern like "int X[];"
3349 //
3350 Constant *X = CE->getOperand(0);
3351 const PointerType *CPTy = cast<PointerType>(CE->getType());
3352 if (const PointerType *XTy = dyn_cast<PointerType>(X->getType()))
3353 if (const ArrayType *XATy =
3354 dyn_cast<ArrayType>(XTy->getElementType()))
3355 if (const ArrayType *CATy =
3356 dyn_cast<ArrayType>(CPTy->getElementType()))
3357 if (CATy->getElementType() == XATy->getElementType()) {
3358 // At this point, we know that the cast source type is a pointer
3359 // to an array of the same type as the destination pointer
3360 // array. Because the array type is never stepped over (there
3361 // is a leading zero) we can fold the cast into this GEP.
3362 GEP.setOperand(0, X);
3363 return &GEP;
3364 }
3365 }
3366 }
Chris Lattnerca081252001-12-14 16:52:21 +00003367 }
3368
Chris Lattnerca081252001-12-14 16:52:21 +00003369 return 0;
3370}
3371
Chris Lattner1085bdf2002-11-04 16:18:53 +00003372Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
3373 // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
3374 if (AI.isArrayAllocation()) // Check C != 1
3375 if (const ConstantUInt *C = dyn_cast<ConstantUInt>(AI.getArraySize())) {
3376 const Type *NewTy = ArrayType::get(AI.getAllocatedType(), C->getValue());
Chris Lattnera2620ac2002-11-09 00:49:43 +00003377 AllocationInst *New = 0;
Chris Lattner1085bdf2002-11-04 16:18:53 +00003378
3379 // Create and insert the replacement instruction...
3380 if (isa<MallocInst>(AI))
Chris Lattnerabb77c92004-03-19 06:08:10 +00003381 New = new MallocInst(NewTy, 0, AI.getName());
Chris Lattnera2620ac2002-11-09 00:49:43 +00003382 else {
3383 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
Chris Lattnerabb77c92004-03-19 06:08:10 +00003384 New = new AllocaInst(NewTy, 0, AI.getName());
Chris Lattnera2620ac2002-11-09 00:49:43 +00003385 }
Chris Lattnerabb77c92004-03-19 06:08:10 +00003386
3387 InsertNewInstBefore(New, AI);
Chris Lattner1085bdf2002-11-04 16:18:53 +00003388
3389 // Scan to the end of the allocation instructions, to skip over a block of
3390 // allocas if possible...
3391 //
3392 BasicBlock::iterator It = New;
3393 while (isa<AllocationInst>(*It)) ++It;
3394
3395 // Now that I is pointing to the first non-allocation-inst in the block,
3396 // insert our getelementptr instruction...
3397 //
Chris Lattner69193f92004-04-05 01:30:19 +00003398 std::vector<Value*> Idx(2, Constant::getNullValue(Type::IntTy));
Chris Lattner1085bdf2002-11-04 16:18:53 +00003399 Value *V = new GetElementPtrInst(New, Idx, New->getName()+".sub", It);
3400
3401 // Now make everything use the getelementptr instead of the original
3402 // allocation.
Chris Lattnerabb77c92004-03-19 06:08:10 +00003403 return ReplaceInstUsesWith(AI, V);
Chris Lattner1085bdf2002-11-04 16:18:53 +00003404 }
Chris Lattnerabb77c92004-03-19 06:08:10 +00003405
3406 // If alloca'ing a zero byte object, replace the alloca with a null pointer.
3407 // Note that we only do this for alloca's, because malloc should allocate and
3408 // return a unique pointer, even for a zero byte allocation.
Chris Lattner49df6ce2004-07-02 22:55:47 +00003409 if (isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized() &&
3410 TD->getTypeSize(AI.getAllocatedType()) == 0)
Chris Lattnerabb77c92004-03-19 06:08:10 +00003411 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
3412
Chris Lattner1085bdf2002-11-04 16:18:53 +00003413 return 0;
3414}
3415
Chris Lattner8427bff2003-12-07 01:24:23 +00003416Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
3417 Value *Op = FI.getOperand(0);
3418
3419 // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
3420 if (CastInst *CI = dyn_cast<CastInst>(Op))
3421 if (isa<PointerType>(CI->getOperand(0)->getType())) {
3422 FI.setOperand(0, CI->getOperand(0));
3423 return &FI;
3424 }
3425
Chris Lattnerf3a36602004-02-28 04:57:37 +00003426 // If we have 'free null' delete the instruction. This can happen in stl code
3427 // when lots of inlining happens.
Chris Lattner51ea1272004-02-28 05:22:00 +00003428 if (isa<ConstantPointerNull>(Op))
3429 return EraseInstFromFunction(FI);
Chris Lattnerf3a36602004-02-28 04:57:37 +00003430
Chris Lattner8427bff2003-12-07 01:24:23 +00003431 return 0;
3432}
3433
3434
Chris Lattner0f1d8a32003-06-26 05:06:25 +00003435/// GetGEPGlobalInitializer - Given a constant, and a getelementptr
3436/// constantexpr, return the constant value being addressed by the constant
3437/// expression, or null if something is funny.
3438///
3439static Constant *GetGEPGlobalInitializer(Constant *C, ConstantExpr *CE) {
Chris Lattner69193f92004-04-05 01:30:19 +00003440 if (CE->getOperand(1) != Constant::getNullValue(CE->getOperand(1)->getType()))
Chris Lattner0f1d8a32003-06-26 05:06:25 +00003441 return 0; // Do not allow stepping over the value!
3442
3443 // Loop over all of the operands, tracking down which value we are
3444 // addressing...
Chris Lattnered79d8a2004-05-27 17:30:27 +00003445 gep_type_iterator I = gep_type_begin(CE), E = gep_type_end(CE);
3446 for (++I; I != E; ++I)
3447 if (const StructType *STy = dyn_cast<StructType>(*I)) {
3448 ConstantUInt *CU = cast<ConstantUInt>(I.getOperand());
3449 assert(CU->getValue() < STy->getNumElements() &&
3450 "Struct index out of range!");
3451 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(C)) {
Alkis Evlogimenos83243722004-08-04 08:44:43 +00003452 C = CS->getOperand(CU->getValue());
Chris Lattnered79d8a2004-05-27 17:30:27 +00003453 } else if (isa<ConstantAggregateZero>(C)) {
3454 C = Constant::getNullValue(STy->getElementType(CU->getValue()));
3455 } else {
3456 return 0;
3457 }
3458 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand())) {
3459 const ArrayType *ATy = cast<ArrayType>(*I);
3460 if ((uint64_t)CI->getRawValue() >= ATy->getNumElements()) return 0;
3461 if (ConstantArray *CA = dyn_cast<ConstantArray>(C))
Alkis Evlogimenos83243722004-08-04 08:44:43 +00003462 C = CA->getOperand(CI->getRawValue());
Chris Lattnered79d8a2004-05-27 17:30:27 +00003463 else if (isa<ConstantAggregateZero>(C))
3464 C = Constant::getNullValue(ATy->getElementType());
3465 else
3466 return 0;
3467 } else {
Chris Lattner0f1d8a32003-06-26 05:06:25 +00003468 return 0;
Chris Lattnered79d8a2004-05-27 17:30:27 +00003469 }
Chris Lattner0f1d8a32003-06-26 05:06:25 +00003470 return C;
3471}
3472
Chris Lattner35e24772004-07-13 01:49:43 +00003473static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI) {
3474 User *CI = cast<User>(LI.getOperand(0));
3475
3476 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
3477 if (const PointerType *SrcTy =
3478 dyn_cast<PointerType>(CI->getOperand(0)->getType())) {
3479 const Type *SrcPTy = SrcTy->getElementType();
3480 if (SrcPTy->isSized() && DestPTy->isSized() &&
3481 IC.getTargetData().getTypeSize(SrcPTy) ==
3482 IC.getTargetData().getTypeSize(DestPTy) &&
3483 (SrcPTy->isInteger() || isa<PointerType>(SrcPTy)) &&
3484 (DestPTy->isInteger() || isa<PointerType>(DestPTy))) {
3485 // Okay, we are casting from one integer or pointer type to another of
3486 // the same size. Instead of casting the pointer before the load, cast
3487 // the result of the loaded value.
3488 Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CI->getOperand(0),
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00003489 CI->getName(),
3490 LI.isVolatile()),LI);
Chris Lattner35e24772004-07-13 01:49:43 +00003491 // Now cast the result of the load.
3492 return new CastInst(NewLoad, LI.getType());
3493 }
3494 }
3495 return 0;
3496}
3497
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00003498/// isSafeToLoadUnconditionally - Return true if we know that executing a load
Chris Lattnere6f13092004-09-19 19:18:10 +00003499/// from this value cannot trap. If it is not obviously safe to load from the
3500/// specified pointer, we do a quick local scan of the basic block containing
3501/// ScanFrom, to determine if the address is already accessed.
3502static bool isSafeToLoadUnconditionally(Value *V, Instruction *ScanFrom) {
3503 // If it is an alloca or global variable, it is always safe to load from.
3504 if (isa<AllocaInst>(V) || isa<GlobalVariable>(V)) return true;
3505
3506 // Otherwise, be a little bit agressive by scanning the local block where we
3507 // want to check to see if the pointer is already being loaded or stored
Alkis Evlogimenosd59cebf2004-09-20 06:42:58 +00003508 // from/to. If so, the previous load or store would have already trapped,
3509 // so there is no harm doing an extra load (also, CSE will later eliminate
3510 // the load entirely).
Chris Lattnere6f13092004-09-19 19:18:10 +00003511 BasicBlock::iterator BBI = ScanFrom, E = ScanFrom->getParent()->begin();
3512
Alkis Evlogimenosd59cebf2004-09-20 06:42:58 +00003513 while (BBI != E) {
Chris Lattnere6f13092004-09-19 19:18:10 +00003514 --BBI;
3515
3516 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
3517 if (LI->getOperand(0) == V) return true;
3518 } else if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
3519 if (SI->getOperand(1) == V) return true;
3520
Alkis Evlogimenosd59cebf2004-09-20 06:42:58 +00003521 }
Chris Lattnere6f13092004-09-19 19:18:10 +00003522 return false;
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00003523}
3524
Chris Lattner0f1d8a32003-06-26 05:06:25 +00003525Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
3526 Value *Op = LI.getOperand(0);
Chris Lattner7e8af382004-01-12 04:13:56 +00003527
Chris Lattner6679e462004-04-14 03:28:36 +00003528 if (Constant *C = dyn_cast<Constant>(Op))
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00003529 if (C->isNullValue() && !LI.isVolatile()) // load null -> 0
Chris Lattner6679e462004-04-14 03:28:36 +00003530 return ReplaceInstUsesWith(LI, Constant::getNullValue(LI.getType()));
Chris Lattner0f1d8a32003-06-26 05:06:25 +00003531
3532 // Instcombine load (constant global) into the value loaded...
3533 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
Chris Lattnerbdb0ce02003-07-22 21:46:59 +00003534 if (GV->isConstant() && !GV->isExternal())
Chris Lattner0f1d8a32003-06-26 05:06:25 +00003535 return ReplaceInstUsesWith(LI, GV->getInitializer());
3536
3537 // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded...
3538 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op))
Chris Lattner35e24772004-07-13 01:49:43 +00003539 if (CE->getOpcode() == Instruction::GetElementPtr) {
Reid Spencer87436872004-07-18 00:38:32 +00003540 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
3541 if (GV->isConstant() && !GV->isExternal())
3542 if (Constant *V = GetGEPGlobalInitializer(GV->getInitializer(), CE))
3543 return ReplaceInstUsesWith(LI, V);
Chris Lattner35e24772004-07-13 01:49:43 +00003544 } else if (CE->getOpcode() == Instruction::Cast) {
3545 if (Instruction *Res = InstCombineLoadCast(*this, LI))
3546 return Res;
3547 }
Chris Lattnere228ee52004-04-08 20:39:49 +00003548
3549 // load (cast X) --> cast (load X) iff safe
Chris Lattner35e24772004-07-13 01:49:43 +00003550 if (CastInst *CI = dyn_cast<CastInst>(Op))
3551 if (Instruction *Res = InstCombineLoadCast(*this, LI))
3552 return Res;
Chris Lattnere228ee52004-04-08 20:39:49 +00003553
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00003554 if (!LI.isVolatile() && Op->hasOneUse()) {
3555 // Change select and PHI nodes to select values instead of addresses: this
3556 // helps alias analysis out a lot, allows many others simplifications, and
3557 // exposes redundancy in the code.
3558 //
3559 // Note that we cannot do the transformation unless we know that the
3560 // introduced loads cannot trap! Something like this is valid as long as
3561 // the condition is always false: load (select bool %C, int* null, int* %G),
3562 // but it would not be valid if we transformed it to load from null
3563 // unconditionally.
3564 //
3565 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
3566 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
Chris Lattnere6f13092004-09-19 19:18:10 +00003567 if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
3568 isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00003569 Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
Chris Lattner42618552004-09-20 10:15:10 +00003570 SI->getOperand(1)->getName()+".val"), LI);
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00003571 Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
Chris Lattner42618552004-09-20 10:15:10 +00003572 SI->getOperand(2)->getName()+".val"), LI);
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00003573 return new SelectInst(SI->getCondition(), V1, V2);
3574 }
3575
Chris Lattnerbdcf41a2004-09-23 15:46:00 +00003576 // load (select (cond, null, P)) -> load P
3577 if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
3578 if (C->isNullValue()) {
3579 LI.setOperand(0, SI->getOperand(2));
3580 return &LI;
3581 }
3582
3583 // load (select (cond, P, null)) -> load P
3584 if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
3585 if (C->isNullValue()) {
3586 LI.setOperand(0, SI->getOperand(1));
3587 return &LI;
3588 }
3589
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00003590 } else if (PHINode *PN = dyn_cast<PHINode>(Op)) {
3591 // load (phi (&V1, &V2, &V3)) --> phi(load &V1, load &V2, load &V3)
Chris Lattner42618552004-09-20 10:15:10 +00003592 bool Safe = PN->getParent() == LI.getParent();
3593
3594 // Scan all of the instructions between the PHI and the load to make
3595 // sure there are no instructions that might possibly alter the value
3596 // loaded from the PHI.
3597 if (Safe) {
3598 BasicBlock::iterator I = &LI;
3599 for (--I; !isa<PHINode>(I); --I)
3600 if (isa<StoreInst>(I) || isa<CallInst>(I)) {
3601 Safe = false;
3602 break;
3603 }
3604 }
3605
3606 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e && Safe; ++i)
Chris Lattnere6f13092004-09-19 19:18:10 +00003607 if (!isSafeToLoadUnconditionally(PN->getIncomingValue(i),
Chris Lattner42618552004-09-20 10:15:10 +00003608 PN->getIncomingBlock(i)->getTerminator()))
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00003609 Safe = false;
Chris Lattner42618552004-09-20 10:15:10 +00003610
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00003611 if (Safe) {
3612 // Create the PHI.
3613 PHINode *NewPN = new PHINode(LI.getType(), PN->getName());
3614 InsertNewInstBefore(NewPN, *PN);
3615 std::map<BasicBlock*,Value*> LoadMap; // Don't insert duplicate loads
3616
3617 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
3618 BasicBlock *BB = PN->getIncomingBlock(i);
3619 Value *&TheLoad = LoadMap[BB];
3620 if (TheLoad == 0) {
3621 Value *InVal = PN->getIncomingValue(i);
3622 TheLoad = InsertNewInstBefore(new LoadInst(InVal,
3623 InVal->getName()+".val"),
3624 *BB->getTerminator());
3625 }
3626 NewPN->addIncoming(TheLoad, BB);
3627 }
3628 return ReplaceInstUsesWith(LI, NewPN);
3629 }
3630 }
3631 }
Chris Lattner0f1d8a32003-06-26 05:06:25 +00003632 return 0;
3633}
3634
3635
Chris Lattner9eef8a72003-06-04 04:46:00 +00003636Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
3637 // Change br (not X), label True, label False to: br X, label False, True
Chris Lattnerd4252a72004-07-30 07:50:03 +00003638 Value *X;
3639 BasicBlock *TrueDest;
3640 BasicBlock *FalseDest;
3641 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
3642 !isa<Constant>(X)) {
3643 // Swap Destinations and condition...
3644 BI.setCondition(X);
3645 BI.setSuccessor(0, FalseDest);
3646 BI.setSuccessor(1, TrueDest);
3647 return &BI;
3648 }
3649
3650 // Cannonicalize setne -> seteq
3651 Instruction::BinaryOps Op; Value *Y;
3652 if (match(&BI, m_Br(m_SetCond(Op, m_Value(X), m_Value(Y)),
3653 TrueDest, FalseDest)))
3654 if ((Op == Instruction::SetNE || Op == Instruction::SetLE ||
3655 Op == Instruction::SetGE) && BI.getCondition()->hasOneUse()) {
3656 SetCondInst *I = cast<SetCondInst>(BI.getCondition());
3657 std::string Name = I->getName(); I->setName("");
3658 Instruction::BinaryOps NewOpcode = SetCondInst::getInverseCondition(Op);
3659 Value *NewSCC = BinaryOperator::create(NewOpcode, X, Y, Name, I);
Chris Lattnere967b342003-06-04 05:10:11 +00003660 // Swap Destinations and condition...
Chris Lattnerd4252a72004-07-30 07:50:03 +00003661 BI.setCondition(NewSCC);
Chris Lattnere967b342003-06-04 05:10:11 +00003662 BI.setSuccessor(0, FalseDest);
3663 BI.setSuccessor(1, TrueDest);
Chris Lattnerd4252a72004-07-30 07:50:03 +00003664 removeFromWorkList(I);
3665 I->getParent()->getInstList().erase(I);
3666 WorkList.push_back(cast<Instruction>(NewSCC));
Chris Lattnere967b342003-06-04 05:10:11 +00003667 return &BI;
3668 }
Chris Lattnerd4252a72004-07-30 07:50:03 +00003669
Chris Lattner9eef8a72003-06-04 04:46:00 +00003670 return 0;
3671}
Chris Lattner1085bdf2002-11-04 16:18:53 +00003672
Chris Lattner4c9c20a2004-07-03 00:26:11 +00003673Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
3674 Value *Cond = SI.getCondition();
3675 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
3676 if (I->getOpcode() == Instruction::Add)
3677 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
3678 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
3679 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
3680 SI.setOperand(i, ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
3681 AddRHS));
3682 SI.setOperand(0, I->getOperand(0));
3683 WorkList.push_back(I);
3684 return &SI;
3685 }
3686 }
3687 return 0;
3688}
3689
Chris Lattnerca081252001-12-14 16:52:21 +00003690
Chris Lattner99f48c62002-09-02 04:59:56 +00003691void InstCombiner::removeFromWorkList(Instruction *I) {
3692 WorkList.erase(std::remove(WorkList.begin(), WorkList.end(), I),
3693 WorkList.end());
3694}
3695
Chris Lattner113f4f42002-06-25 16:13:24 +00003696bool InstCombiner::runOnFunction(Function &F) {
Chris Lattner260ab202002-04-18 17:39:14 +00003697 bool Changed = false;
Chris Lattnerf4ad1652003-11-02 05:57:39 +00003698 TD = &getAnalysis<TargetData>();
Chris Lattnerca081252001-12-14 16:52:21 +00003699
Chris Lattnerb643a9e2004-05-01 23:19:52 +00003700 for (inst_iterator i = inst_begin(F), e = inst_end(F); i != e; ++i)
3701 WorkList.push_back(&*i);
Chris Lattner2d3a7a62004-04-27 15:13:33 +00003702
Chris Lattnerca081252001-12-14 16:52:21 +00003703
3704 while (!WorkList.empty()) {
3705 Instruction *I = WorkList.back(); // Get an instruction from the worklist
3706 WorkList.pop_back();
3707
Misha Brukman632df282002-10-29 23:06:16 +00003708 // Check to see if we can DCE or ConstantPropagate the instruction...
Chris Lattner99f48c62002-09-02 04:59:56 +00003709 // Check to see if we can DIE the instruction...
3710 if (isInstructionTriviallyDead(I)) {
3711 // Add operands to the worklist...
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00003712 if (I->getNumOperands() < 4)
Chris Lattner51ea1272004-02-28 05:22:00 +00003713 AddUsesToWorkList(*I);
Chris Lattner99f48c62002-09-02 04:59:56 +00003714 ++NumDeadInst;
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00003715
3716 I->getParent()->getInstList().erase(I);
3717 removeFromWorkList(I);
3718 continue;
3719 }
Chris Lattner99f48c62002-09-02 04:59:56 +00003720
Misha Brukman632df282002-10-29 23:06:16 +00003721 // Instruction isn't dead, see if we can constant propagate it...
Chris Lattner99f48c62002-09-02 04:59:56 +00003722 if (Constant *C = ConstantFoldInstruction(I)) {
3723 // Add operands to the worklist...
Chris Lattner51ea1272004-02-28 05:22:00 +00003724 AddUsesToWorkList(*I);
Chris Lattnerc6509f42002-12-05 22:41:53 +00003725 ReplaceInstUsesWith(*I, C);
3726
Chris Lattner99f48c62002-09-02 04:59:56 +00003727 ++NumConstProp;
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00003728 I->getParent()->getInstList().erase(I);
Chris Lattner800aaaf2003-10-07 15:17:02 +00003729 removeFromWorkList(I);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00003730 continue;
Chris Lattner99f48c62002-09-02 04:59:56 +00003731 }
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00003732
Chris Lattnerca081252001-12-14 16:52:21 +00003733 // Now that we have an instruction, try combining it to simplify it...
Chris Lattnerae7a0d32002-08-02 19:29:35 +00003734 if (Instruction *Result = visit(*I)) {
Chris Lattner0b18c1d2002-05-10 15:38:35 +00003735 ++NumCombined;
Chris Lattner260ab202002-04-18 17:39:14 +00003736 // Should we replace the old instruction with a new one?
Chris Lattner053c0932002-05-14 15:24:07 +00003737 if (Result != I) {
Chris Lattner7d2a5392004-03-13 23:54:27 +00003738 DEBUG(std::cerr << "IC: Old = " << *I
3739 << " New = " << *Result);
3740
Chris Lattner396dbfe2004-06-09 05:08:07 +00003741 // Everything uses the new instruction now.
3742 I->replaceAllUsesWith(Result);
3743
3744 // Push the new instruction and any users onto the worklist.
3745 WorkList.push_back(Result);
3746 AddUsersToWorkList(*Result);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00003747
3748 // Move the name to the new instruction first...
3749 std::string OldName = I->getName(); I->setName("");
Chris Lattner950fc782003-10-07 22:58:41 +00003750 Result->setName(OldName);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00003751
3752 // Insert the new instruction into the basic block...
3753 BasicBlock *InstParent = I->getParent();
3754 InstParent->getInstList().insert(I, Result);
3755
Chris Lattner63d75af2004-05-01 23:27:23 +00003756 // Make sure that we reprocess all operands now that we reduced their
3757 // use counts.
Chris Lattnerb643a9e2004-05-01 23:19:52 +00003758 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
3759 if (Instruction *OpI = dyn_cast<Instruction>(I->getOperand(i)))
3760 WorkList.push_back(OpI);
3761
Chris Lattner396dbfe2004-06-09 05:08:07 +00003762 // Instructions can end up on the worklist more than once. Make sure
3763 // we do not process an instruction that has been deleted.
3764 removeFromWorkList(I);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00003765
3766 // Erase the old instruction.
3767 InstParent->getInstList().erase(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00003768 } else {
Chris Lattner7d2a5392004-03-13 23:54:27 +00003769 DEBUG(std::cerr << "IC: MOD = " << *I);
3770
Chris Lattnerae7a0d32002-08-02 19:29:35 +00003771 // If the instruction was modified, it's possible that it is now dead.
3772 // if so, remove it.
Chris Lattner63d75af2004-05-01 23:27:23 +00003773 if (isInstructionTriviallyDead(I)) {
3774 // Make sure we process all operands now that we are reducing their
3775 // use counts.
3776 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
3777 if (Instruction *OpI = dyn_cast<Instruction>(I->getOperand(i)))
3778 WorkList.push_back(OpI);
3779
3780 // Instructions may end up in the worklist more than once. Erase all
3781 // occurrances of this instruction.
Chris Lattner99f48c62002-09-02 04:59:56 +00003782 removeFromWorkList(I);
Chris Lattner63d75af2004-05-01 23:27:23 +00003783 I->getParent()->getInstList().erase(I);
Chris Lattner396dbfe2004-06-09 05:08:07 +00003784 } else {
3785 WorkList.push_back(Result);
3786 AddUsersToWorkList(*Result);
Chris Lattnerae7a0d32002-08-02 19:29:35 +00003787 }
Chris Lattner053c0932002-05-14 15:24:07 +00003788 }
Chris Lattner260ab202002-04-18 17:39:14 +00003789 Changed = true;
Chris Lattnerca081252001-12-14 16:52:21 +00003790 }
3791 }
3792
Chris Lattner260ab202002-04-18 17:39:14 +00003793 return Changed;
Chris Lattner04805fa2002-02-26 21:46:54 +00003794}
3795
Brian Gaeke38b79e82004-07-27 17:43:21 +00003796FunctionPass *llvm::createInstructionCombiningPass() {
Chris Lattner260ab202002-04-18 17:39:14 +00003797 return new InstCombiner();
Chris Lattner04805fa2002-02-26 21:46:54 +00003798}
Brian Gaeke960707c2003-11-11 22:41:34 +00003799