blob: 21c58b696e0c42a3abef377d37f4a5c41bd8504f [file] [log] [blame]
Chris Lattnere6794492002-08-12 21:17:25 +00001//===- InstructionCombining.cpp - Combine multiple instructions -----------===//
Chris Lattnerca081252001-12-14 16:52:21 +00002//
3// InstructionCombining - Combine instructions to form fewer, simple
Chris Lattner99f48c62002-09-02 04:59:56 +00004// instructions. This pass does not modify the CFG This pass is where algebraic
5// simplification happens.
Chris Lattnerca081252001-12-14 16:52:21 +00006//
7// This pass combines things like:
8// %Y = add int 1, %X
9// %Z = add int 1, %Y
10// into:
11// %Z = add int 2, %X
12//
13// This is a simple worklist driven algorithm.
14//
15//===----------------------------------------------------------------------===//
16
Chris Lattnerb4cfa7f2002-05-07 20:03:00 +000017#include "llvm/Transforms/Scalar.h"
Chris Lattner9b55e5a2002-05-07 18:12:18 +000018#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Chris Lattnerae7a0d32002-08-02 19:29:35 +000019#include "llvm/Transforms/Utils/Local.h"
Chris Lattner471bd762003-05-22 19:07:21 +000020#include "llvm/Instructions.h"
Chris Lattner04805fa2002-02-26 21:46:54 +000021#include "llvm/Pass.h"
Chris Lattner34428442003-05-27 16:40:51 +000022#include "llvm/Constants.h"
23#include "llvm/ConstantHandling.h"
Chris Lattner1085bdf2002-11-04 16:18:53 +000024#include "llvm/DerivedTypes.h"
Chris Lattner60a65912002-02-12 21:07:25 +000025#include "llvm/Support/InstIterator.h"
Chris Lattner260ab202002-04-18 17:39:14 +000026#include "llvm/Support/InstVisitor.h"
Chris Lattnerbf3a0992002-10-01 22:38:41 +000027#include "Support/Statistic.h"
Chris Lattner053c0932002-05-14 15:24:07 +000028#include <algorithm>
Chris Lattnerca081252001-12-14 16:52:21 +000029
Chris Lattner260ab202002-04-18 17:39:14 +000030namespace {
Chris Lattnerbf3a0992002-10-01 22:38:41 +000031 Statistic<> NumCombined ("instcombine", "Number of insts combined");
32 Statistic<> NumConstProp("instcombine", "Number of constant folds");
33 Statistic<> NumDeadInst ("instcombine", "Number of dead inst eliminated");
34
Chris Lattnerc8e66542002-04-27 06:56:12 +000035 class InstCombiner : public FunctionPass,
Chris Lattner260ab202002-04-18 17:39:14 +000036 public InstVisitor<InstCombiner, Instruction*> {
37 // Worklist of all of the instructions that need to be simplified.
38 std::vector<Instruction*> WorkList;
39
Chris Lattner113f4f42002-06-25 16:13:24 +000040 void AddUsesToWorkList(Instruction &I) {
Chris Lattner260ab202002-04-18 17:39:14 +000041 // The instruction was simplified, add all users of the instruction to
42 // the work lists because they might get more simplified now...
43 //
Chris Lattner113f4f42002-06-25 16:13:24 +000044 for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
Chris Lattner260ab202002-04-18 17:39:14 +000045 UI != UE; ++UI)
46 WorkList.push_back(cast<Instruction>(*UI));
47 }
48
Chris Lattner99f48c62002-09-02 04:59:56 +000049 // removeFromWorkList - remove all instances of I from the worklist.
50 void removeFromWorkList(Instruction *I);
Chris Lattner260ab202002-04-18 17:39:14 +000051 public:
Chris Lattner113f4f42002-06-25 16:13:24 +000052 virtual bool runOnFunction(Function &F);
Chris Lattner260ab202002-04-18 17:39:14 +000053
Chris Lattnerf12cc842002-04-28 21:27:06 +000054 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Chris Lattner820d9712002-10-21 20:00:28 +000055 AU.setPreservesCFG();
Chris Lattnerf12cc842002-04-28 21:27:06 +000056 }
57
Chris Lattner260ab202002-04-18 17:39:14 +000058 // Visitation implementation - Implement instruction combining for different
59 // instruction types. The semantics are as follows:
60 // Return Value:
61 // null - No change was made
Chris Lattnere6794492002-08-12 21:17:25 +000062 // I - Change was made, I is still valid, I may be dead though
Chris Lattner260ab202002-04-18 17:39:14 +000063 // otherwise - Change was made, replace I with returned instruction
64 //
Chris Lattner113f4f42002-06-25 16:13:24 +000065 Instruction *visitAdd(BinaryOperator &I);
66 Instruction *visitSub(BinaryOperator &I);
67 Instruction *visitMul(BinaryOperator &I);
68 Instruction *visitDiv(BinaryOperator &I);
69 Instruction *visitRem(BinaryOperator &I);
70 Instruction *visitAnd(BinaryOperator &I);
71 Instruction *visitOr (BinaryOperator &I);
72 Instruction *visitXor(BinaryOperator &I);
73 Instruction *visitSetCondInst(BinaryOperator &I);
Chris Lattnere8d6c602003-03-10 19:16:08 +000074 Instruction *visitShiftInst(ShiftInst &I);
Chris Lattner113f4f42002-06-25 16:13:24 +000075 Instruction *visitCastInst(CastInst &CI);
76 Instruction *visitPHINode(PHINode &PN);
77 Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
Chris Lattner1085bdf2002-11-04 16:18:53 +000078 Instruction *visitAllocationInst(AllocationInst &AI);
Chris Lattner260ab202002-04-18 17:39:14 +000079
80 // visitInstruction - Specify what to return for unhandled instructions...
Chris Lattner113f4f42002-06-25 16:13:24 +000081 Instruction *visitInstruction(Instruction &I) { return 0; }
Chris Lattner6d14f2a2002-08-09 23:47:40 +000082
83 // InsertNewInstBefore - insert an instruction New before instruction Old
84 // in the program. Add the new instruction to the worklist.
85 //
86 void InsertNewInstBefore(Instruction *New, Instruction &Old) {
Chris Lattner65217ff2002-08-23 18:32:43 +000087 assert(New && New->getParent() == 0 &&
88 "New instruction already inserted into a basic block!");
Chris Lattner6d14f2a2002-08-09 23:47:40 +000089 BasicBlock *BB = Old.getParent();
90 BB->getInstList().insert(&Old, New); // Insert inst
91 WorkList.push_back(New); // Add to worklist
92 }
93
94 // ReplaceInstUsesWith - This method is to be used when an instruction is
95 // found to be dead, replacable with another preexisting expression. Here
96 // we add all uses of I to the worklist, replace all uses of I with the new
97 // value, then return I, so that the inst combiner will know that I was
98 // modified.
99 //
100 Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
101 AddUsesToWorkList(I); // Add all modified instrs to worklist
102 I.replaceAllUsesWith(V);
103 return &I;
104 }
Chris Lattner7fb29e12003-03-11 00:12:48 +0000105
106 // SimplifyCommutative - This performs a few simplifications for commutative
107 // operators...
108 bool SimplifyCommutative(BinaryOperator &I);
109
Chris Lattner260ab202002-04-18 17:39:14 +0000110 };
Chris Lattnerb28b6802002-07-23 18:06:35 +0000111
Chris Lattnerc8b70922002-07-26 21:12:46 +0000112 RegisterOpt<InstCombiner> X("instcombine", "Combine redundant instructions");
Chris Lattner260ab202002-04-18 17:39:14 +0000113}
114
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000115// getComplexity: Assign a complexity or rank value to LLVM Values...
116// 0 -> Constant, 1 -> Other, 2 -> Argument, 2 -> Unary, 3 -> OtherInst
117static unsigned getComplexity(Value *V) {
118 if (isa<Instruction>(V)) {
119 if (BinaryOperator::isNeg(V) || BinaryOperator::isNot(V))
120 return 2;
121 return 3;
122 }
123 if (isa<Argument>(V)) return 2;
124 return isa<Constant>(V) ? 0 : 1;
125}
Chris Lattner260ab202002-04-18 17:39:14 +0000126
Chris Lattner7fb29e12003-03-11 00:12:48 +0000127// isOnlyUse - Return true if this instruction will be deleted if we stop using
128// it.
129static bool isOnlyUse(Value *V) {
130 return V->use_size() == 1 || isa<Constant>(V);
131}
132
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000133// SimplifyCommutative - This performs a few simplifications for commutative
134// operators:
Chris Lattner260ab202002-04-18 17:39:14 +0000135//
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000136// 1. Order operands such that they are listed from right (least complex) to
137// left (most complex). This puts constants before unary operators before
138// binary operators.
139//
Chris Lattner7fb29e12003-03-11 00:12:48 +0000140// 2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
141// 3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000142//
Chris Lattner7fb29e12003-03-11 00:12:48 +0000143bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000144 bool Changed = false;
145 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
146 Changed = !I.swapOperands();
147
148 if (!I.isAssociative()) return Changed;
149 Instruction::BinaryOps Opcode = I.getOpcode();
Chris Lattner7fb29e12003-03-11 00:12:48 +0000150 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
151 if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
152 if (isa<Constant>(I.getOperand(1))) {
Chris Lattner34428442003-05-27 16:40:51 +0000153 Constant *Folded = ConstantExpr::get(I.getOpcode(),
154 cast<Constant>(I.getOperand(1)),
155 cast<Constant>(Op->getOperand(1)));
Chris Lattner7fb29e12003-03-11 00:12:48 +0000156 I.setOperand(0, Op->getOperand(0));
157 I.setOperand(1, Folded);
158 return true;
159 } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
160 if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
161 isOnlyUse(Op) && isOnlyUse(Op1)) {
162 Constant *C1 = cast<Constant>(Op->getOperand(1));
163 Constant *C2 = cast<Constant>(Op1->getOperand(1));
164
165 // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattner34428442003-05-27 16:40:51 +0000166 Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
Chris Lattner7fb29e12003-03-11 00:12:48 +0000167 Instruction *New = BinaryOperator::create(Opcode, Op->getOperand(0),
168 Op1->getOperand(0),
169 Op1->getName(), &I);
170 WorkList.push_back(New);
171 I.setOperand(0, New);
172 I.setOperand(1, Folded);
173 return true;
174 }
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000175 }
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000176 return Changed;
Chris Lattner260ab202002-04-18 17:39:14 +0000177}
Chris Lattnerca081252001-12-14 16:52:21 +0000178
Chris Lattnerbb74e222003-03-10 23:06:50 +0000179// dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
180// if the LHS is a constant zero (which is the 'negate' form).
Chris Lattner9fa53de2002-05-06 16:49:18 +0000181//
Chris Lattnerbb74e222003-03-10 23:06:50 +0000182static inline Value *dyn_castNegVal(Value *V) {
183 if (BinaryOperator::isNeg(V))
184 return BinaryOperator::getNegArgument(cast<BinaryOperator>(V));
185
Chris Lattner9244df62003-04-30 22:19:10 +0000186 // Constants can be considered to be negated values if they can be folded...
187 if (Constant *C = dyn_cast<Constant>(V))
Chris Lattner34428442003-05-27 16:40:51 +0000188 return ConstantExpr::get(Instruction::Sub,
189 Constant::getNullValue(V->getType()), C);
Chris Lattnerbb74e222003-03-10 23:06:50 +0000190 return 0;
Chris Lattner9fa53de2002-05-06 16:49:18 +0000191}
192
Chris Lattnerbb74e222003-03-10 23:06:50 +0000193static inline Value *dyn_castNotVal(Value *V) {
194 if (BinaryOperator::isNot(V))
195 return BinaryOperator::getNotArgument(cast<BinaryOperator>(V));
196
197 // Constants can be considered to be not'ed values...
Chris Lattnerdd65d862003-04-30 22:34:06 +0000198 if (ConstantIntegral *C = dyn_cast<ConstantIntegral>(V))
Chris Lattner34428442003-05-27 16:40:51 +0000199 return ConstantExpr::get(Instruction::Xor,
200 ConstantIntegral::getAllOnesValue(C->getType()),C);
Chris Lattnerbb74e222003-03-10 23:06:50 +0000201 return 0;
202}
203
Chris Lattner7fb29e12003-03-11 00:12:48 +0000204// dyn_castFoldableMul - If this value is a multiply that can be folded into
205// other computations (because it has a constant operand), return the
206// non-constant operand of the multiply.
207//
208static inline Value *dyn_castFoldableMul(Value *V) {
209 if (V->use_size() == 1 && V->getType()->isInteger())
210 if (Instruction *I = dyn_cast<Instruction>(V))
211 if (I->getOpcode() == Instruction::Mul)
212 if (isa<Constant>(I->getOperand(1)))
213 return I->getOperand(0);
214 return 0;
Chris Lattner3082c5a2003-02-18 19:28:33 +0000215}
Chris Lattner31ae8632002-08-14 17:51:49 +0000216
Chris Lattner7fb29e12003-03-11 00:12:48 +0000217// dyn_castMaskingAnd - If this value is an And instruction masking a value with
218// a constant, return the constant being anded with.
219//
220static inline Constant *dyn_castMaskingAnd(Value *V) {
221 if (Instruction *I = dyn_cast<Instruction>(V))
222 if (I->getOpcode() == Instruction::And)
223 return dyn_cast<Constant>(I->getOperand(1));
224
225 // If this is a constant, it acts just like we were masking with it.
226 return dyn_cast<Constant>(V);
227}
Chris Lattner3082c5a2003-02-18 19:28:33 +0000228
229// Log2 - Calculate the log base 2 for the specified value if it is exactly a
230// power of 2.
231static unsigned Log2(uint64_t Val) {
232 assert(Val > 1 && "Values 0 and 1 should be handled elsewhere!");
233 unsigned Count = 0;
234 while (Val != 1) {
235 if (Val & 1) return 0; // Multiple bits set?
236 Val >>= 1;
237 ++Count;
238 }
239 return Count;
Chris Lattner31ae8632002-08-14 17:51:49 +0000240}
241
Chris Lattner113f4f42002-06-25 16:13:24 +0000242Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000243 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +0000244 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
Chris Lattner9fa53de2002-05-06 16:49:18 +0000245
246 // Eliminate 'add int %X, 0'
Chris Lattnere6794492002-08-12 21:17:25 +0000247 if (RHS == Constant::getNullValue(I.getType()))
248 return ReplaceInstUsesWith(I, LHS);
Chris Lattner9fa53de2002-05-06 16:49:18 +0000249
Chris Lattner147e9752002-05-08 22:46:53 +0000250 // -A + B --> B - A
Chris Lattnerbb74e222003-03-10 23:06:50 +0000251 if (Value *V = dyn_castNegVal(LHS))
Chris Lattner147e9752002-05-08 22:46:53 +0000252 return BinaryOperator::create(Instruction::Sub, RHS, V);
Chris Lattner9fa53de2002-05-06 16:49:18 +0000253
254 // A + -B --> A - B
Chris Lattnerbb74e222003-03-10 23:06:50 +0000255 if (!isa<Constant>(RHS))
256 if (Value *V = dyn_castNegVal(RHS))
257 return BinaryOperator::create(Instruction::Sub, LHS, V);
Chris Lattner260ab202002-04-18 17:39:14 +0000258
Chris Lattner57c8d992003-02-18 19:57:07 +0000259 // X*C + X --> X * (C+1)
260 if (dyn_castFoldableMul(LHS) == RHS) {
Chris Lattner34428442003-05-27 16:40:51 +0000261 Constant *CP1 =
262 ConstantExpr::get(Instruction::Add,
263 cast<Constant>(cast<Instruction>(LHS)->getOperand(1)),
264 ConstantInt::get(I.getType(), 1));
Chris Lattner57c8d992003-02-18 19:57:07 +0000265 return BinaryOperator::create(Instruction::Mul, RHS, CP1);
266 }
267
268 // X + X*C --> X * (C+1)
269 if (dyn_castFoldableMul(RHS) == LHS) {
Chris Lattner34428442003-05-27 16:40:51 +0000270 Constant *CP1 =
271 ConstantExpr::get(Instruction::Add,
272 cast<Constant>(cast<Instruction>(RHS)->getOperand(1)),
273 ConstantInt::get(I.getType(), 1));
Chris Lattner57c8d992003-02-18 19:57:07 +0000274 return BinaryOperator::create(Instruction::Mul, LHS, CP1);
275 }
276
Chris Lattner7fb29e12003-03-11 00:12:48 +0000277 // (A & C1)+(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
278 if (Constant *C1 = dyn_castMaskingAnd(LHS))
279 if (Constant *C2 = dyn_castMaskingAnd(RHS))
Chris Lattner34428442003-05-27 16:40:51 +0000280 if (ConstantExpr::get(Instruction::And, C1, C2)->isNullValue())
Chris Lattner7fb29e12003-03-11 00:12:48 +0000281 return BinaryOperator::create(Instruction::Or, LHS, RHS);
282
Chris Lattner113f4f42002-06-25 16:13:24 +0000283 return Changed ? &I : 0;
Chris Lattner260ab202002-04-18 17:39:14 +0000284}
285
Chris Lattner113f4f42002-06-25 16:13:24 +0000286Instruction *InstCombiner::visitSub(BinaryOperator &I) {
Chris Lattner113f4f42002-06-25 16:13:24 +0000287 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000288
Chris Lattnere6794492002-08-12 21:17:25 +0000289 if (Op0 == Op1) // sub X, X -> 0
290 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner260ab202002-04-18 17:39:14 +0000291
Chris Lattnere6794492002-08-12 21:17:25 +0000292 // If this is a 'B = x-(-A)', change to B = x+A...
Chris Lattnerbb74e222003-03-10 23:06:50 +0000293 if (Value *V = dyn_castNegVal(Op1))
Chris Lattner147e9752002-05-08 22:46:53 +0000294 return BinaryOperator::create(Instruction::Add, Op0, V);
Chris Lattner9fa53de2002-05-06 16:49:18 +0000295
Chris Lattner3082c5a2003-02-18 19:28:33 +0000296 // Replace (-1 - A) with (~A)...
297 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0))
298 if (C->isAllOnesValue())
299 return BinaryOperator::createNot(Op1);
Chris Lattnerad3c4952002-05-09 01:29:19 +0000300
Chris Lattner3082c5a2003-02-18 19:28:33 +0000301 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1))
302 if (Op1I->use_size() == 1) {
303 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
304 // is not used by anyone else...
305 //
306 if (Op1I->getOpcode() == Instruction::Sub) {
307 // Swap the two operands of the subexpr...
308 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
309 Op1I->setOperand(0, IIOp1);
310 Op1I->setOperand(1, IIOp0);
311
312 // Create the new top level add instruction...
313 return BinaryOperator::create(Instruction::Add, Op0, Op1);
314 }
315
316 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
317 //
318 if (Op1I->getOpcode() == Instruction::And &&
319 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
320 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
321
322 Instruction *NewNot = BinaryOperator::createNot(OtherOp, "B.not", &I);
323 return BinaryOperator::create(Instruction::And, Op0, NewNot);
324 }
Chris Lattner57c8d992003-02-18 19:57:07 +0000325
326 // X - X*C --> X * (1-C)
327 if (dyn_castFoldableMul(Op1I) == Op0) {
Chris Lattner34428442003-05-27 16:40:51 +0000328 Constant *CP1 =
329 ConstantExpr::get(Instruction::Sub,
330 ConstantInt::get(I.getType(), 1),
331 cast<Constant>(cast<Instruction>(Op1)->getOperand(1)));
Chris Lattner57c8d992003-02-18 19:57:07 +0000332 assert(CP1 && "Couldn't constant fold 1-C?");
333 return BinaryOperator::create(Instruction::Mul, Op0, CP1);
334 }
Chris Lattnerad3c4952002-05-09 01:29:19 +0000335 }
Chris Lattner3082c5a2003-02-18 19:28:33 +0000336
Chris Lattner57c8d992003-02-18 19:57:07 +0000337 // X*C - X --> X * (C-1)
338 if (dyn_castFoldableMul(Op0) == Op1) {
Chris Lattner34428442003-05-27 16:40:51 +0000339 Constant *CP1 =
340 ConstantExpr::get(Instruction::Sub,
341 cast<Constant>(cast<Instruction>(Op0)->getOperand(1)),
342 ConstantInt::get(I.getType(), 1));
Chris Lattner57c8d992003-02-18 19:57:07 +0000343 assert(CP1 && "Couldn't constant fold C - 1?");
344 return BinaryOperator::create(Instruction::Mul, Op1, CP1);
345 }
346
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000347 return 0;
Chris Lattner260ab202002-04-18 17:39:14 +0000348}
349
Chris Lattner113f4f42002-06-25 16:13:24 +0000350Instruction *InstCombiner::visitMul(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000351 bool Changed = SimplifyCommutative(I);
Chris Lattner3082c5a2003-02-18 19:28:33 +0000352 Value *Op0 = I.getOperand(0);
Chris Lattner260ab202002-04-18 17:39:14 +0000353
Chris Lattnere6794492002-08-12 21:17:25 +0000354 // Simplify mul instructions with a constant RHS...
Chris Lattner3082c5a2003-02-18 19:28:33 +0000355 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
356 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
357 const Type *Ty = CI->getType();
358 uint64_t Val = Ty->isSigned() ?
359 (uint64_t)cast<ConstantSInt>(CI)->getValue() :
360 cast<ConstantUInt>(CI)->getValue();
361 switch (Val) {
362 case 0:
363 return ReplaceInstUsesWith(I, Op1); // Eliminate 'mul double %X, 0'
364 case 1:
365 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul int %X, 1'
366 case 2: // Convert 'mul int %X, 2' to 'add int %X, %X'
367 return BinaryOperator::create(Instruction::Add, Op0, Op0, I.getName());
368 }
Chris Lattner31ba1292002-04-29 22:24:47 +0000369
Chris Lattner3082c5a2003-02-18 19:28:33 +0000370 if (uint64_t C = Log2(Val)) // Replace X*(2^C) with X << C
371 return new ShiftInst(Instruction::Shl, Op0,
372 ConstantUInt::get(Type::UByteTy, C));
373 } else {
374 ConstantFP *Op1F = cast<ConstantFP>(Op1);
375 if (Op1F->isNullValue())
376 return ReplaceInstUsesWith(I, Op1);
Chris Lattner31ba1292002-04-29 22:24:47 +0000377
Chris Lattner3082c5a2003-02-18 19:28:33 +0000378 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
379 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
380 if (Op1F->getValue() == 1.0)
381 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0'
382 }
Chris Lattner260ab202002-04-18 17:39:14 +0000383 }
384
Chris Lattner934a64cf2003-03-10 23:23:04 +0000385 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
386 if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
387 return BinaryOperator::create(Instruction::Mul, Op0v, Op1v);
388
Chris Lattner113f4f42002-06-25 16:13:24 +0000389 return Changed ? &I : 0;
Chris Lattner260ab202002-04-18 17:39:14 +0000390}
391
Chris Lattner113f4f42002-06-25 16:13:24 +0000392Instruction *InstCombiner::visitDiv(BinaryOperator &I) {
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000393 // div X, 1 == X
Chris Lattner3082c5a2003-02-18 19:28:33 +0000394 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I.getOperand(1))) {
Chris Lattnere6794492002-08-12 21:17:25 +0000395 if (RHS->equalsInt(1))
396 return ReplaceInstUsesWith(I, I.getOperand(0));
Chris Lattner3082c5a2003-02-18 19:28:33 +0000397
398 // Check to see if this is an unsigned division with an exact power of 2,
399 // if so, convert to a right shift.
400 if (ConstantUInt *C = dyn_cast<ConstantUInt>(RHS))
401 if (uint64_t Val = C->getValue()) // Don't break X / 0
402 if (uint64_t C = Log2(Val))
403 return new ShiftInst(Instruction::Shr, I.getOperand(0),
404 ConstantUInt::get(Type::UByteTy, C));
405 }
406
407 // 0 / X == 0, we don't need to preserve faults!
408 if (ConstantInt *LHS = dyn_cast<ConstantInt>(I.getOperand(0)))
409 if (LHS->equalsInt(0))
410 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
411
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000412 return 0;
413}
414
415
Chris Lattner113f4f42002-06-25 16:13:24 +0000416Instruction *InstCombiner::visitRem(BinaryOperator &I) {
Chris Lattner3082c5a2003-02-18 19:28:33 +0000417 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I.getOperand(1))) {
418 if (RHS->equalsInt(1)) // X % 1 == 0
419 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
420
421 // Check to see if this is an unsigned remainder with an exact power of 2,
422 // if so, convert to a bitwise and.
423 if (ConstantUInt *C = dyn_cast<ConstantUInt>(RHS))
424 if (uint64_t Val = C->getValue()) // Don't break X % 0 (divide by zero)
425 if (Log2(Val))
426 return BinaryOperator::create(Instruction::And, I.getOperand(0),
427 ConstantUInt::get(I.getType(), Val-1));
428 }
429
430 // 0 % X == 0, we don't need to preserve faults!
431 if (ConstantInt *LHS = dyn_cast<ConstantInt>(I.getOperand(0)))
432 if (LHS->equalsInt(0))
Chris Lattnere6794492002-08-12 21:17:25 +0000433 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
434
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000435 return 0;
436}
437
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000438// isMaxValueMinusOne - return true if this is Max-1
Chris Lattnere6794492002-08-12 21:17:25 +0000439static bool isMaxValueMinusOne(const ConstantInt *C) {
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000440 if (const ConstantUInt *CU = dyn_cast<ConstantUInt>(C)) {
441 // Calculate -1 casted to the right type...
442 unsigned TypeBits = C->getType()->getPrimitiveSize()*8;
443 uint64_t Val = ~0ULL; // All ones
444 Val >>= 64-TypeBits; // Shift out unwanted 1 bits...
445 return CU->getValue() == Val-1;
446 }
447
448 const ConstantSInt *CS = cast<ConstantSInt>(C);
449
450 // Calculate 0111111111..11111
451 unsigned TypeBits = C->getType()->getPrimitiveSize()*8;
452 int64_t Val = INT64_MAX; // All ones
453 Val >>= 64-TypeBits; // Shift out unwanted 1 bits...
454 return CS->getValue() == Val-1;
455}
456
457// isMinValuePlusOne - return true if this is Min+1
Chris Lattnere6794492002-08-12 21:17:25 +0000458static bool isMinValuePlusOne(const ConstantInt *C) {
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000459 if (const ConstantUInt *CU = dyn_cast<ConstantUInt>(C))
460 return CU->getValue() == 1;
461
462 const ConstantSInt *CS = cast<ConstantSInt>(C);
463
464 // Calculate 1111111111000000000000
465 unsigned TypeBits = C->getType()->getPrimitiveSize()*8;
466 int64_t Val = -1; // All ones
467 Val <<= TypeBits-1; // Shift over to the right spot
468 return CS->getValue() == Val+1;
469}
470
471
Chris Lattner113f4f42002-06-25 16:13:24 +0000472Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000473 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +0000474 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000475
476 // and X, X = X and X, 0 == 0
Chris Lattnere6794492002-08-12 21:17:25 +0000477 if (Op0 == Op1 || Op1 == Constant::getNullValue(I.getType()))
478 return ReplaceInstUsesWith(I, Op1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000479
480 // and X, -1 == X
Chris Lattner83282632002-08-13 17:50:24 +0000481 if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1))
Chris Lattnere6794492002-08-12 21:17:25 +0000482 if (RHS->isAllOnesValue())
483 return ReplaceInstUsesWith(I, Op0);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000484
Chris Lattnerbb74e222003-03-10 23:06:50 +0000485 Value *Op0NotVal = dyn_castNotVal(Op0);
486 Value *Op1NotVal = dyn_castNotVal(Op1);
Chris Lattner3082c5a2003-02-18 19:28:33 +0000487
488 // (~A & ~B) == (~(A | B)) - Demorgan's Law
Chris Lattnerbb74e222003-03-10 23:06:50 +0000489 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Chris Lattner3082c5a2003-02-18 19:28:33 +0000490 Instruction *Or = BinaryOperator::create(Instruction::Or, Op0NotVal,
491 Op1NotVal,I.getName()+".demorgan",
492 &I);
Chris Lattner3e327a42003-03-10 23:13:59 +0000493 WorkList.push_back(Or);
Chris Lattner3082c5a2003-02-18 19:28:33 +0000494 return BinaryOperator::createNot(Or);
495 }
496
497 if (Op0NotVal == Op1 || Op1NotVal == Op0) // A & ~A == ~A & A == 0
498 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner65217ff2002-08-23 18:32:43 +0000499
Chris Lattner113f4f42002-06-25 16:13:24 +0000500 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000501}
502
503
504
Chris Lattner113f4f42002-06-25 16:13:24 +0000505Instruction *InstCombiner::visitOr(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000506 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +0000507 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000508
509 // or X, X = X or X, 0 == X
Chris Lattnere6794492002-08-12 21:17:25 +0000510 if (Op0 == Op1 || Op1 == Constant::getNullValue(I.getType()))
511 return ReplaceInstUsesWith(I, Op0);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000512
513 // or X, -1 == -1
Chris Lattner83282632002-08-13 17:50:24 +0000514 if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1))
Chris Lattnere6794492002-08-12 21:17:25 +0000515 if (RHS->isAllOnesValue())
516 return ReplaceInstUsesWith(I, Op1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000517
Chris Lattner3e327a42003-03-10 23:13:59 +0000518 Value *Op0NotVal = dyn_castNotVal(Op0);
519 Value *Op1NotVal = dyn_castNotVal(Op1);
Chris Lattner3082c5a2003-02-18 19:28:33 +0000520
Chris Lattner3e327a42003-03-10 23:13:59 +0000521 if (Op1 == Op0NotVal) // ~A | A == -1
522 return ReplaceInstUsesWith(I,
523 ConstantIntegral::getAllOnesValue(I.getType()));
524
525 if (Op0 == Op1NotVal) // A | ~A == -1
526 return ReplaceInstUsesWith(I,
527 ConstantIntegral::getAllOnesValue(I.getType()));
528
529 // (~A | ~B) == (~(A & B)) - Demorgan's Law
530 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
531 Instruction *And = BinaryOperator::create(Instruction::And, Op0NotVal,
532 Op1NotVal,I.getName()+".demorgan",
533 &I);
534 WorkList.push_back(And);
535 return BinaryOperator::createNot(And);
536 }
Chris Lattner3082c5a2003-02-18 19:28:33 +0000537
Chris Lattner113f4f42002-06-25 16:13:24 +0000538 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000539}
540
541
542
Chris Lattner113f4f42002-06-25 16:13:24 +0000543Instruction *InstCombiner::visitXor(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000544 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +0000545 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000546
547 // xor X, X = 0
Chris Lattnere6794492002-08-12 21:17:25 +0000548 if (Op0 == Op1)
549 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000550
Chris Lattner83282632002-08-13 17:50:24 +0000551 if (ConstantIntegral *Op1C = dyn_cast<ConstantIntegral>(Op1)) {
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000552 // xor X, 0 == X
Chris Lattnere6794492002-08-12 21:17:25 +0000553 if (Op1C->isNullValue())
554 return ReplaceInstUsesWith(I, Op0);
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000555
Chris Lattnerb8d6e402002-08-20 18:24:26 +0000556 // Is this a "NOT" instruction?
557 if (Op1C->isAllOnesValue()) {
558 // xor (xor X, -1), -1 = not (not X) = X
Chris Lattnerbb74e222003-03-10 23:06:50 +0000559 if (Value *X = dyn_castNotVal(Op0))
Chris Lattner31ae8632002-08-14 17:51:49 +0000560 return ReplaceInstUsesWith(I, X);
Chris Lattnerb8d6e402002-08-20 18:24:26 +0000561
562 // xor (setcc A, B), true = not (setcc A, B) = setncc A, B
563 if (SetCondInst *SCI = dyn_cast<SetCondInst>(Op0))
564 if (SCI->use_size() == 1)
565 return new SetCondInst(SCI->getInverseCondition(),
566 SCI->getOperand(0), SCI->getOperand(1));
567 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000568 }
569
Chris Lattnerbb74e222003-03-10 23:06:50 +0000570 if (Value *X = dyn_castNotVal(Op0)) // ~A ^ A == -1
Chris Lattner3082c5a2003-02-18 19:28:33 +0000571 if (X == Op1)
572 return ReplaceInstUsesWith(I,
573 ConstantIntegral::getAllOnesValue(I.getType()));
574
Chris Lattnerbb74e222003-03-10 23:06:50 +0000575 if (Value *X = dyn_castNotVal(Op1)) // A ^ ~A == -1
Chris Lattner3082c5a2003-02-18 19:28:33 +0000576 if (X == Op0)
577 return ReplaceInstUsesWith(I,
578 ConstantIntegral::getAllOnesValue(I.getType()));
579
Chris Lattner1bbb7b62003-03-10 18:24:17 +0000580 if (Instruction *Op1I = dyn_cast<Instruction>(Op1))
581 if (Op1I->getOpcode() == Instruction::Or)
582 if (Op1I->getOperand(0) == Op0) { // B^(B|A) == (A|B)^B
583 cast<BinaryOperator>(Op1I)->swapOperands();
584 I.swapOperands();
585 std::swap(Op0, Op1);
586 } else if (Op1I->getOperand(1) == Op0) { // B^(A|B) == (A|B)^B
587 I.swapOperands();
588 std::swap(Op0, Op1);
589 }
590
591 if (Instruction *Op0I = dyn_cast<Instruction>(Op0))
592 if (Op0I->getOpcode() == Instruction::Or && Op0I->use_size() == 1) {
593 if (Op0I->getOperand(0) == Op1) // (B|A)^B == (A|B)^B
594 cast<BinaryOperator>(Op0I)->swapOperands();
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000595 if (Op0I->getOperand(1) == Op1) { // (A|B)^B == A & ~B
Chris Lattner1bbb7b62003-03-10 18:24:17 +0000596 Value *NotB = BinaryOperator::createNot(Op1, Op1->getName()+".not", &I);
597 WorkList.push_back(cast<Instruction>(NotB));
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000598 return BinaryOperator::create(Instruction::And, Op0I->getOperand(0),
599 NotB);
Chris Lattner1bbb7b62003-03-10 18:24:17 +0000600 }
601 }
602
Chris Lattner7fb29e12003-03-11 00:12:48 +0000603 // (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1^C2 == 0
604 if (Constant *C1 = dyn_castMaskingAnd(Op0))
605 if (Constant *C2 = dyn_castMaskingAnd(Op1))
Chris Lattner34428442003-05-27 16:40:51 +0000606 if (ConstantExpr::get(Instruction::And, C1, C2)->isNullValue())
Chris Lattner7fb29e12003-03-11 00:12:48 +0000607 return BinaryOperator::create(Instruction::Or, Op0, Op1);
608
Chris Lattner113f4f42002-06-25 16:13:24 +0000609 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000610}
611
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000612// AddOne, SubOne - Add or subtract a constant one from an integer constant...
613static Constant *AddOne(ConstantInt *C) {
Chris Lattner34428442003-05-27 16:40:51 +0000614 Constant *Result = ConstantExpr::get(Instruction::Add, C,
615 ConstantInt::get(C->getType(), 1));
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000616 assert(Result && "Constant folding integer addition failed!");
617 return Result;
618}
619static Constant *SubOne(ConstantInt *C) {
Chris Lattner34428442003-05-27 16:40:51 +0000620 Constant *Result = ConstantExpr::get(Instruction::Sub, C,
621 ConstantInt::get(C->getType(), 1));
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000622 assert(Result && "Constant folding integer addition failed!");
623 return Result;
624}
625
Chris Lattner1fc23f32002-05-09 20:11:54 +0000626// isTrueWhenEqual - Return true if the specified setcondinst instruction is
627// true when both operands are equal...
628//
Chris Lattner113f4f42002-06-25 16:13:24 +0000629static bool isTrueWhenEqual(Instruction &I) {
630 return I.getOpcode() == Instruction::SetEQ ||
631 I.getOpcode() == Instruction::SetGE ||
632 I.getOpcode() == Instruction::SetLE;
Chris Lattner1fc23f32002-05-09 20:11:54 +0000633}
634
Chris Lattner113f4f42002-06-25 16:13:24 +0000635Instruction *InstCombiner::visitSetCondInst(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000636 bool Changed = SimplifyCommutative(I);
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000637 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
638 const Type *Ty = Op0->getType();
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000639
640 // setcc X, X
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000641 if (Op0 == Op1)
642 return ReplaceInstUsesWith(I, ConstantBool::get(isTrueWhenEqual(I)));
Chris Lattner1fc23f32002-05-09 20:11:54 +0000643
644 // setcc <global*>, 0 - Global value addresses are never null!
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000645 if (isa<GlobalValue>(Op0) && isa<ConstantPointerNull>(Op1))
646 return ReplaceInstUsesWith(I, ConstantBool::get(!isTrueWhenEqual(I)));
647
648 // setcc's with boolean values can always be turned into bitwise operations
649 if (Ty == Type::BoolTy) {
650 // If this is <, >, or !=, we can change this into a simple xor instruction
651 if (!isTrueWhenEqual(I))
652 return BinaryOperator::create(Instruction::Xor, Op0, Op1, I.getName());
653
654 // Otherwise we need to make a temporary intermediate instruction and insert
655 // it into the instruction stream. This is what we are after:
656 //
657 // seteq bool %A, %B -> ~(A^B)
658 // setle bool %A, %B -> ~A | B
659 // setge bool %A, %B -> A | ~B
660 //
661 if (I.getOpcode() == Instruction::SetEQ) { // seteq case
662 Instruction *Xor = BinaryOperator::create(Instruction::Xor, Op0, Op1,
663 I.getName()+"tmp");
664 InsertNewInstBefore(Xor, I);
Chris Lattner31ae8632002-08-14 17:51:49 +0000665 return BinaryOperator::createNot(Xor, I.getName());
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000666 }
667
668 // Handle the setXe cases...
669 assert(I.getOpcode() == Instruction::SetGE ||
670 I.getOpcode() == Instruction::SetLE);
671
672 if (I.getOpcode() == Instruction::SetGE)
673 std::swap(Op0, Op1); // Change setge -> setle
674
675 // Now we just have the SetLE case.
Chris Lattner31ae8632002-08-14 17:51:49 +0000676 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000677 InsertNewInstBefore(Not, I);
678 return BinaryOperator::create(Instruction::Or, Not, Op1, I.getName());
679 }
680
681 // Check to see if we are doing one of many comparisons against constant
682 // integers at the end of their ranges...
683 //
684 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner791ac1a2003-06-01 03:35:25 +0000685 if (CI->isNullValue() && I.getOpcode() == Instruction::SetNE)
686 return new CastInst(Op0, Type::BoolTy, I.getName());
687
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000688 // Check to see if we are comparing against the minimum or maximum value...
Chris Lattnere6794492002-08-12 21:17:25 +0000689 if (CI->isMinValue()) {
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000690 if (I.getOpcode() == Instruction::SetLT) // A < MIN -> FALSE
691 return ReplaceInstUsesWith(I, ConstantBool::False);
692 if (I.getOpcode() == Instruction::SetGE) // A >= MIN -> TRUE
693 return ReplaceInstUsesWith(I, ConstantBool::True);
694 if (I.getOpcode() == Instruction::SetLE) // A <= MIN -> A == MIN
695 return BinaryOperator::create(Instruction::SetEQ, Op0,Op1, I.getName());
696 if (I.getOpcode() == Instruction::SetGT) // A > MIN -> A != MIN
697 return BinaryOperator::create(Instruction::SetNE, Op0,Op1, I.getName());
698
Chris Lattnere6794492002-08-12 21:17:25 +0000699 } else if (CI->isMaxValue()) {
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000700 if (I.getOpcode() == Instruction::SetGT) // A > MAX -> FALSE
701 return ReplaceInstUsesWith(I, ConstantBool::False);
702 if (I.getOpcode() == Instruction::SetLE) // A <= MAX -> TRUE
703 return ReplaceInstUsesWith(I, ConstantBool::True);
704 if (I.getOpcode() == Instruction::SetGE) // A >= MAX -> A == MAX
705 return BinaryOperator::create(Instruction::SetEQ, Op0,Op1, I.getName());
706 if (I.getOpcode() == Instruction::SetLT) // A < MAX -> A != MAX
707 return BinaryOperator::create(Instruction::SetNE, Op0,Op1, I.getName());
708
709 // Comparing against a value really close to min or max?
710 } else if (isMinValuePlusOne(CI)) {
711 if (I.getOpcode() == Instruction::SetLT) // A < MIN+1 -> A == MIN
712 return BinaryOperator::create(Instruction::SetEQ, Op0,
713 SubOne(CI), I.getName());
714 if (I.getOpcode() == Instruction::SetGE) // A >= MIN-1 -> A != MIN
715 return BinaryOperator::create(Instruction::SetNE, Op0,
716 SubOne(CI), I.getName());
717
718 } else if (isMaxValueMinusOne(CI)) {
719 if (I.getOpcode() == Instruction::SetGT) // A > MAX-1 -> A == MAX
720 return BinaryOperator::create(Instruction::SetEQ, Op0,
721 AddOne(CI), I.getName());
722 if (I.getOpcode() == Instruction::SetLE) // A <= MAX-1 -> A != MAX
723 return BinaryOperator::create(Instruction::SetNE, Op0,
724 AddOne(CI), I.getName());
725 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000726 }
727
Chris Lattner113f4f42002-06-25 16:13:24 +0000728 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000729}
730
731
732
Chris Lattnere8d6c602003-03-10 19:16:08 +0000733Instruction *InstCombiner::visitShiftInst(ShiftInst &I) {
Chris Lattner113f4f42002-06-25 16:13:24 +0000734 assert(I.getOperand(1)->getType() == Type::UByteTy);
735 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000736
737 // shl X, 0 == X and shr X, 0 == X
738 // shl 0, X == 0 and shr 0, X == 0
739 if (Op1 == Constant::getNullValue(Type::UByteTy) ||
Chris Lattnere6794492002-08-12 21:17:25 +0000740 Op0 == Constant::getNullValue(Op0->getType()))
741 return ReplaceInstUsesWith(I, Op0);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000742
Chris Lattnere8d6c602003-03-10 19:16:08 +0000743 // If this is a shift of a shift, see if we can fold the two together...
744 if (ShiftInst *Op0SI = dyn_cast<ShiftInst>(Op0)) {
745 if (isa<Constant>(Op1) && isa<Constant>(Op0SI->getOperand(1))) {
746 ConstantUInt *ShiftAmt1C = cast<ConstantUInt>(Op0SI->getOperand(1));
747 unsigned ShiftAmt1 = ShiftAmt1C->getValue();
748 unsigned ShiftAmt2 = cast<ConstantUInt>(Op1)->getValue();
749
750 // Check for (A << c1) << c2 and (A >> c1) >> c2
751 if (I.getOpcode() == Op0SI->getOpcode()) {
752 unsigned Amt = ShiftAmt1+ShiftAmt2; // Fold into one big shift...
753 return new ShiftInst(I.getOpcode(), Op0SI->getOperand(0),
754 ConstantUInt::get(Type::UByteTy, Amt));
755 }
756
757 if (I.getType()->isUnsigned()) { // Check for (A << c1) >> c2 or visaversa
758 // Calculate bitmask for what gets shifted off the edge...
759 Constant *C = ConstantIntegral::getAllOnesValue(I.getType());
760 if (I.getOpcode() == Instruction::Shr)
Chris Lattner34428442003-05-27 16:40:51 +0000761 C = ConstantExpr::getShift(Instruction::Shr, C, ShiftAmt1C);
Chris Lattnere8d6c602003-03-10 19:16:08 +0000762 else
Chris Lattner34428442003-05-27 16:40:51 +0000763 C = ConstantExpr::getShift(Instruction::Shl, C, ShiftAmt1C);
Chris Lattnere8d6c602003-03-10 19:16:08 +0000764
765 Instruction *Mask =
766 BinaryOperator::create(Instruction::And, Op0SI->getOperand(0),
767 C, Op0SI->getOperand(0)->getName()+".mask",&I);
768 WorkList.push_back(Mask);
769
770 // Figure out what flavor of shift we should use...
771 if (ShiftAmt1 == ShiftAmt2)
772 return ReplaceInstUsesWith(I, Mask); // (A << c) >> c === A & c2
773 else if (ShiftAmt1 < ShiftAmt2) {
774 return new ShiftInst(I.getOpcode(), Mask,
775 ConstantUInt::get(Type::UByteTy, ShiftAmt2-ShiftAmt1));
776 } else {
777 return new ShiftInst(Op0SI->getOpcode(), Mask,
778 ConstantUInt::get(Type::UByteTy, ShiftAmt1-ShiftAmt2));
779 }
780 }
781 }
782 }
783
Chris Lattnere6794492002-08-12 21:17:25 +0000784 // shl uint X, 32 = 0 and shr ubyte Y, 9 = 0, ... just don't eliminate shr of
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000785 // a signed value.
786 //
787 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(Op1)) {
Chris Lattnere8d6c602003-03-10 19:16:08 +0000788 unsigned TypeBits = Op0->getType()->getPrimitiveSize()*8;
789 if (CUI->getValue() >= TypeBits &&
790 (!Op0->getType()->isSigned() || I.getOpcode() == Instruction::Shl))
791 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
Chris Lattner55f3d942002-09-10 23:04:09 +0000792
793 // Check to see if we are shifting left by 1. If so, turn it into an add
794 // instruction.
795 if (I.getOpcode() == Instruction::Shl && CUI->equalsInt(1))
Chris Lattner3082c5a2003-02-18 19:28:33 +0000796 // Convert 'shl int %X, 1' to 'add int %X, %X'
Chris Lattner55f3d942002-09-10 23:04:09 +0000797 return BinaryOperator::create(Instruction::Add, Op0, Op0, I.getName());
798
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000799 }
Chris Lattner2e0fb392002-10-08 16:16:40 +0000800
801 // shr int -1, X = -1 (for any arithmetic shift rights of ~0)
802 if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(Op0))
803 if (I.getOpcode() == Instruction::Shr && CSI->isAllOnesValue())
804 return ReplaceInstUsesWith(I, CSI);
805
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000806 return 0;
807}
808
809
Chris Lattner48a44f72002-05-02 17:06:02 +0000810// isEliminableCastOfCast - Return true if it is valid to eliminate the CI
811// instruction.
812//
Chris Lattner113f4f42002-06-25 16:13:24 +0000813static inline bool isEliminableCastOfCast(const CastInst &CI,
Chris Lattner48a44f72002-05-02 17:06:02 +0000814 const CastInst *CSrc) {
Chris Lattner113f4f42002-06-25 16:13:24 +0000815 assert(CI.getOperand(0) == CSrc);
Chris Lattner48a44f72002-05-02 17:06:02 +0000816 const Type *SrcTy = CSrc->getOperand(0)->getType();
817 const Type *MidTy = CSrc->getType();
Chris Lattner113f4f42002-06-25 16:13:24 +0000818 const Type *DstTy = CI.getType();
Chris Lattner48a44f72002-05-02 17:06:02 +0000819
Chris Lattner650b6da2002-08-02 20:00:25 +0000820 // It is legal to eliminate the instruction if casting A->B->A if the sizes
821 // are identical and the bits don't get reinterpreted (for example
Chris Lattner0bb75912002-08-14 23:21:10 +0000822 // int->float->int would not be allowed)
Misha Brukmane5838c42003-05-20 18:45:36 +0000823 if (SrcTy == DstTy && SrcTy->isLosslesslyConvertibleTo(MidTy))
Chris Lattner650b6da2002-08-02 20:00:25 +0000824 return true;
Chris Lattner48a44f72002-05-02 17:06:02 +0000825
826 // Allow free casting and conversion of sizes as long as the sign doesn't
827 // change...
Chris Lattnerb0b412e2002-09-03 01:08:28 +0000828 if (SrcTy->isIntegral() && MidTy->isIntegral() && DstTy->isIntegral()) {
Chris Lattner650b6da2002-08-02 20:00:25 +0000829 unsigned SrcSize = SrcTy->getPrimitiveSize();
830 unsigned MidSize = MidTy->getPrimitiveSize();
831 unsigned DstSize = DstTy->getPrimitiveSize();
Chris Lattner650b6da2002-08-02 20:00:25 +0000832
Chris Lattner3732aca2002-08-15 16:15:25 +0000833 // Cases where we are monotonically decreasing the size of the type are
834 // always ok, regardless of what sign changes are going on.
835 //
Chris Lattner0bb75912002-08-14 23:21:10 +0000836 if (SrcSize >= MidSize && MidSize >= DstSize)
Chris Lattner650b6da2002-08-02 20:00:25 +0000837 return true;
Chris Lattner3732aca2002-08-15 16:15:25 +0000838
Chris Lattner555518c2002-09-23 23:39:43 +0000839 // Cases where the source and destination type are the same, but the middle
840 // type is bigger are noops.
841 //
842 if (SrcSize == DstSize && MidSize > SrcSize)
843 return true;
844
Chris Lattner3732aca2002-08-15 16:15:25 +0000845 // If we are monotonically growing, things are more complex.
846 //
847 if (SrcSize <= MidSize && MidSize <= DstSize) {
848 // We have eight combinations of signedness to worry about. Here's the
849 // table:
850 static const int SignTable[8] = {
851 // CODE, SrcSigned, MidSigned, DstSigned, Comment
852 1, // U U U Always ok
853 1, // U U S Always ok
854 3, // U S U Ok iff SrcSize != MidSize
855 3, // U S S Ok iff SrcSize != MidSize
856 0, // S U U Never ok
857 2, // S U S Ok iff MidSize == DstSize
858 1, // S S U Always ok
859 1, // S S S Always ok
860 };
861
862 // Choose an action based on the current entry of the signtable that this
863 // cast of cast refers to...
864 unsigned Row = SrcTy->isSigned()*4+MidTy->isSigned()*2+DstTy->isSigned();
865 switch (SignTable[Row]) {
866 case 0: return false; // Never ok
867 case 1: return true; // Always ok
868 case 2: return MidSize == DstSize; // Ok iff MidSize == DstSize
869 case 3: // Ok iff SrcSize != MidSize
870 return SrcSize != MidSize || SrcTy == Type::BoolTy;
871 default: assert(0 && "Bad entry in sign table!");
872 }
Chris Lattner3732aca2002-08-15 16:15:25 +0000873 }
Chris Lattner650b6da2002-08-02 20:00:25 +0000874 }
Chris Lattner48a44f72002-05-02 17:06:02 +0000875
876 // Otherwise, we cannot succeed. Specifically we do not want to allow things
877 // like: short -> ushort -> uint, because this can create wrong results if
878 // the input short is negative!
879 //
880 return false;
881}
882
883
884// CastInst simplification
Chris Lattner260ab202002-04-18 17:39:14 +0000885//
Chris Lattner113f4f42002-06-25 16:13:24 +0000886Instruction *InstCombiner::visitCastInst(CastInst &CI) {
Chris Lattner48a44f72002-05-02 17:06:02 +0000887 // If the user is casting a value to the same type, eliminate this cast
888 // instruction...
Chris Lattnere6794492002-08-12 21:17:25 +0000889 if (CI.getType() == CI.getOperand(0)->getType())
890 return ReplaceInstUsesWith(CI, CI.getOperand(0));
Chris Lattner48a44f72002-05-02 17:06:02 +0000891
Chris Lattner48a44f72002-05-02 17:06:02 +0000892 // If casting the result of another cast instruction, try to eliminate this
893 // one!
894 //
Chris Lattner650b6da2002-08-02 20:00:25 +0000895 if (CastInst *CSrc = dyn_cast<CastInst>(CI.getOperand(0))) {
Chris Lattner48a44f72002-05-02 17:06:02 +0000896 if (isEliminableCastOfCast(CI, CSrc)) {
897 // This instruction now refers directly to the cast's src operand. This
898 // has a good chance of making CSrc dead.
Chris Lattner113f4f42002-06-25 16:13:24 +0000899 CI.setOperand(0, CSrc->getOperand(0));
900 return &CI;
Chris Lattner48a44f72002-05-02 17:06:02 +0000901 }
902
Chris Lattner650b6da2002-08-02 20:00:25 +0000903 // If this is an A->B->A cast, and we are dealing with integral types, try
904 // to convert this into a logical 'and' instruction.
905 //
906 if (CSrc->getOperand(0)->getType() == CI.getType() &&
Chris Lattnerb0b412e2002-09-03 01:08:28 +0000907 CI.getType()->isInteger() && CSrc->getType()->isInteger() &&
Chris Lattner650b6da2002-08-02 20:00:25 +0000908 CI.getType()->isUnsigned() && CSrc->getType()->isUnsigned() &&
909 CSrc->getType()->getPrimitiveSize() < CI.getType()->getPrimitiveSize()){
910 assert(CSrc->getType() != Type::ULongTy &&
911 "Cannot have type bigger than ulong!");
Chris Lattner196897c2003-05-26 23:41:32 +0000912 uint64_t AndValue = (1ULL << CSrc->getType()->getPrimitiveSize()*8)-1;
Chris Lattner650b6da2002-08-02 20:00:25 +0000913 Constant *AndOp = ConstantUInt::get(CI.getType(), AndValue);
914 return BinaryOperator::create(Instruction::And, CSrc->getOperand(0),
915 AndOp);
916 }
917 }
918
Chris Lattner260ab202002-04-18 17:39:14 +0000919 return 0;
Chris Lattnerca081252001-12-14 16:52:21 +0000920}
921
Chris Lattner48a44f72002-05-02 17:06:02 +0000922
Chris Lattnerbbbdd852002-05-06 18:06:38 +0000923// PHINode simplification
924//
Chris Lattner113f4f42002-06-25 16:13:24 +0000925Instruction *InstCombiner::visitPHINode(PHINode &PN) {
Chris Lattnerbbbdd852002-05-06 18:06:38 +0000926 // If the PHI node only has one incoming value, eliminate the PHI node...
Chris Lattnere6794492002-08-12 21:17:25 +0000927 if (PN.getNumIncomingValues() == 1)
928 return ReplaceInstUsesWith(PN, PN.getIncomingValue(0));
Chris Lattner9cd1e662002-08-20 15:35:35 +0000929
930 // Otherwise if all of the incoming values are the same for the PHI, replace
931 // the PHI node with the incoming value.
932 //
Chris Lattnerf6c0efa2002-08-22 20:22:01 +0000933 Value *InVal = 0;
934 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
935 if (PN.getIncomingValue(i) != &PN) // Not the PHI node itself...
936 if (InVal && PN.getIncomingValue(i) != InVal)
937 return 0; // Not the same, bail out.
938 else
939 InVal = PN.getIncomingValue(i);
940
941 // The only case that could cause InVal to be null is if we have a PHI node
942 // that only has entries for itself. In this case, there is no entry into the
943 // loop, so kill the PHI.
944 //
945 if (InVal == 0) InVal = Constant::getNullValue(PN.getType());
Chris Lattnerbbbdd852002-05-06 18:06:38 +0000946
Chris Lattner9cd1e662002-08-20 15:35:35 +0000947 // All of the incoming values are the same, replace the PHI node now.
948 return ReplaceInstUsesWith(PN, InVal);
Chris Lattnerbbbdd852002-05-06 18:06:38 +0000949}
950
Chris Lattner48a44f72002-05-02 17:06:02 +0000951
Chris Lattner113f4f42002-06-25 16:13:24 +0000952Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
Chris Lattner471bd762003-05-22 19:07:21 +0000953 // Is it 'getelementptr %P, long 0' or 'getelementptr %P'
Chris Lattner113f4f42002-06-25 16:13:24 +0000954 // If so, eliminate the noop.
Chris Lattnerae7a0d32002-08-02 19:29:35 +0000955 if ((GEP.getNumOperands() == 2 &&
Chris Lattner136dab72002-09-11 01:21:33 +0000956 GEP.getOperand(1) == Constant::getNullValue(Type::LongTy)) ||
Chris Lattnere6794492002-08-12 21:17:25 +0000957 GEP.getNumOperands() == 1)
958 return ReplaceInstUsesWith(GEP, GEP.getOperand(0));
Chris Lattner48a44f72002-05-02 17:06:02 +0000959
Chris Lattnerae7a0d32002-08-02 19:29:35 +0000960 // Combine Indices - If the source pointer to this getelementptr instruction
961 // is a getelementptr instruction, combine the indices of the two
962 // getelementptr instructions into a single instruction.
963 //
Chris Lattnerc59af1d2002-08-17 22:21:59 +0000964 if (GetElementPtrInst *Src = dyn_cast<GetElementPtrInst>(GEP.getOperand(0))) {
Chris Lattnerae7a0d32002-08-02 19:29:35 +0000965 std::vector<Value *> Indices;
Chris Lattnerca081252001-12-14 16:52:21 +0000966
Chris Lattnerae7a0d32002-08-02 19:29:35 +0000967 // Can we combine the two pointer arithmetics offsets?
Chris Lattner471bd762003-05-22 19:07:21 +0000968 if (Src->getNumOperands() == 2 && isa<Constant>(Src->getOperand(1)) &&
969 isa<Constant>(GEP.getOperand(1))) {
Chris Lattner235af562003-03-05 22:33:14 +0000970 // Replace: gep (gep %P, long C1), long C2, ...
971 // With: gep %P, long (C1+C2), ...
Chris Lattner34428442003-05-27 16:40:51 +0000972 Value *Sum = ConstantExpr::get(Instruction::Add,
973 cast<Constant>(Src->getOperand(1)),
974 cast<Constant>(GEP.getOperand(1)));
Chris Lattner235af562003-03-05 22:33:14 +0000975 assert(Sum && "Constant folding of longs failed!?");
976 GEP.setOperand(0, Src->getOperand(0));
977 GEP.setOperand(1, Sum);
978 AddUsesToWorkList(*Src); // Reduce use count of Src
979 return &GEP;
Chris Lattner471bd762003-05-22 19:07:21 +0000980 } else if (Src->getNumOperands() == 2) {
Chris Lattner235af562003-03-05 22:33:14 +0000981 // Replace: gep (gep %P, long B), long A, ...
982 // With: T = long A+B; gep %P, T, ...
983 //
984 Value *Sum = BinaryOperator::create(Instruction::Add, Src->getOperand(1),
985 GEP.getOperand(1),
986 Src->getName()+".sum", &GEP);
987 GEP.setOperand(0, Src->getOperand(0));
988 GEP.setOperand(1, Sum);
989 WorkList.push_back(cast<Instruction>(Sum));
990 return &GEP;
Chris Lattner5d606a02002-11-04 16:43:32 +0000991 } else if (*GEP.idx_begin() == Constant::getNullValue(Type::LongTy) &&
Chris Lattnera8339e32002-09-17 21:05:42 +0000992 Src->getNumOperands() != 1) {
Chris Lattnerae7a0d32002-08-02 19:29:35 +0000993 // Otherwise we can do the fold if the first index of the GEP is a zero
994 Indices.insert(Indices.end(), Src->idx_begin(), Src->idx_end());
995 Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
Chris Lattner5d606a02002-11-04 16:43:32 +0000996 } else if (Src->getOperand(Src->getNumOperands()-1) ==
997 Constant::getNullValue(Type::LongTy)) {
998 // If the src gep ends with a constant array index, merge this get into
999 // it, even if we have a non-zero array index.
1000 Indices.insert(Indices.end(), Src->idx_begin(), Src->idx_end()-1);
1001 Indices.insert(Indices.end(), GEP.idx_begin(), GEP.idx_end());
Chris Lattnerae7a0d32002-08-02 19:29:35 +00001002 }
1003
1004 if (!Indices.empty())
1005 return new GetElementPtrInst(Src->getOperand(0), Indices, GEP.getName());
Chris Lattnerc59af1d2002-08-17 22:21:59 +00001006
1007 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(GEP.getOperand(0))) {
1008 // GEP of global variable. If all of the indices for this GEP are
1009 // constants, we can promote this to a constexpr instead of an instruction.
1010
1011 // Scan for nonconstants...
1012 std::vector<Constant*> Indices;
1013 User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
1014 for (; I != E && isa<Constant>(*I); ++I)
1015 Indices.push_back(cast<Constant>(*I));
1016
1017 if (I == E) { // If they are all constants...
Chris Lattner46b3d302003-04-16 22:40:51 +00001018 Constant *CE =
Chris Lattnerc59af1d2002-08-17 22:21:59 +00001019 ConstantExpr::getGetElementPtr(ConstantPointerRef::get(GV), Indices);
1020
1021 // Replace all uses of the GEP with the new constexpr...
1022 return ReplaceInstUsesWith(GEP, CE);
1023 }
Chris Lattnerca081252001-12-14 16:52:21 +00001024 }
1025
Chris Lattnerca081252001-12-14 16:52:21 +00001026 return 0;
1027}
1028
Chris Lattner1085bdf2002-11-04 16:18:53 +00001029Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
1030 // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
1031 if (AI.isArrayAllocation()) // Check C != 1
1032 if (const ConstantUInt *C = dyn_cast<ConstantUInt>(AI.getArraySize())) {
1033 const Type *NewTy = ArrayType::get(AI.getAllocatedType(), C->getValue());
Chris Lattnera2620ac2002-11-09 00:49:43 +00001034 AllocationInst *New = 0;
Chris Lattner1085bdf2002-11-04 16:18:53 +00001035
1036 // Create and insert the replacement instruction...
1037 if (isa<MallocInst>(AI))
1038 New = new MallocInst(NewTy, 0, AI.getName(), &AI);
Chris Lattnera2620ac2002-11-09 00:49:43 +00001039 else {
1040 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
Chris Lattner1085bdf2002-11-04 16:18:53 +00001041 New = new AllocaInst(NewTy, 0, AI.getName(), &AI);
Chris Lattnera2620ac2002-11-09 00:49:43 +00001042 }
Chris Lattner1085bdf2002-11-04 16:18:53 +00001043
1044 // Scan to the end of the allocation instructions, to skip over a block of
1045 // allocas if possible...
1046 //
1047 BasicBlock::iterator It = New;
1048 while (isa<AllocationInst>(*It)) ++It;
1049
1050 // Now that I is pointing to the first non-allocation-inst in the block,
1051 // insert our getelementptr instruction...
1052 //
1053 std::vector<Value*> Idx(2, Constant::getNullValue(Type::LongTy));
1054 Value *V = new GetElementPtrInst(New, Idx, New->getName()+".sub", It);
1055
1056 // Now make everything use the getelementptr instead of the original
1057 // allocation.
1058 ReplaceInstUsesWith(AI, V);
1059 return &AI;
1060 }
1061 return 0;
1062}
1063
1064
Chris Lattnerca081252001-12-14 16:52:21 +00001065
Chris Lattner99f48c62002-09-02 04:59:56 +00001066void InstCombiner::removeFromWorkList(Instruction *I) {
1067 WorkList.erase(std::remove(WorkList.begin(), WorkList.end(), I),
1068 WorkList.end());
1069}
1070
Chris Lattner113f4f42002-06-25 16:13:24 +00001071bool InstCombiner::runOnFunction(Function &F) {
Chris Lattner260ab202002-04-18 17:39:14 +00001072 bool Changed = false;
Chris Lattnerca081252001-12-14 16:52:21 +00001073
Chris Lattner260ab202002-04-18 17:39:14 +00001074 WorkList.insert(WorkList.end(), inst_begin(F), inst_end(F));
Chris Lattnerca081252001-12-14 16:52:21 +00001075
1076 while (!WorkList.empty()) {
1077 Instruction *I = WorkList.back(); // Get an instruction from the worklist
1078 WorkList.pop_back();
1079
Misha Brukman632df282002-10-29 23:06:16 +00001080 // Check to see if we can DCE or ConstantPropagate the instruction...
Chris Lattner99f48c62002-09-02 04:59:56 +00001081 // Check to see if we can DIE the instruction...
1082 if (isInstructionTriviallyDead(I)) {
1083 // Add operands to the worklist...
1084 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
1085 if (Instruction *Op = dyn_cast<Instruction>(I->getOperand(i)))
1086 WorkList.push_back(Op);
1087
1088 ++NumDeadInst;
1089 BasicBlock::iterator BBI = I;
1090 if (dceInstruction(BBI)) {
1091 removeFromWorkList(I);
1092 continue;
1093 }
1094 }
1095
Misha Brukman632df282002-10-29 23:06:16 +00001096 // Instruction isn't dead, see if we can constant propagate it...
Chris Lattner99f48c62002-09-02 04:59:56 +00001097 if (Constant *C = ConstantFoldInstruction(I)) {
1098 // Add operands to the worklist...
1099 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
1100 if (Instruction *Op = dyn_cast<Instruction>(I->getOperand(i)))
1101 WorkList.push_back(Op);
Chris Lattnerc6509f42002-12-05 22:41:53 +00001102 ReplaceInstUsesWith(*I, C);
1103
Chris Lattner99f48c62002-09-02 04:59:56 +00001104 ++NumConstProp;
1105 BasicBlock::iterator BBI = I;
1106 if (dceInstruction(BBI)) {
1107 removeFromWorkList(I);
1108 continue;
1109 }
1110 }
1111
Chris Lattnerca081252001-12-14 16:52:21 +00001112 // Now that we have an instruction, try combining it to simplify it...
Chris Lattnerae7a0d32002-08-02 19:29:35 +00001113 if (Instruction *Result = visit(*I)) {
Chris Lattner0b18c1d2002-05-10 15:38:35 +00001114 ++NumCombined;
Chris Lattner260ab202002-04-18 17:39:14 +00001115 // Should we replace the old instruction with a new one?
Chris Lattner053c0932002-05-14 15:24:07 +00001116 if (Result != I) {
1117 // Instructions can end up on the worklist more than once. Make sure
1118 // we do not process an instruction that has been deleted.
Chris Lattner99f48c62002-09-02 04:59:56 +00001119 removeFromWorkList(I);
Chris Lattner260ab202002-04-18 17:39:14 +00001120 ReplaceInstWithInst(I, Result);
Chris Lattner113f4f42002-06-25 16:13:24 +00001121 } else {
Chris Lattnerae7a0d32002-08-02 19:29:35 +00001122 BasicBlock::iterator II = I;
1123
1124 // If the instruction was modified, it's possible that it is now dead.
1125 // if so, remove it.
1126 if (dceInstruction(II)) {
1127 // Instructions may end up in the worklist more than once. Erase them
1128 // all.
Chris Lattner99f48c62002-09-02 04:59:56 +00001129 removeFromWorkList(I);
Chris Lattnerae7a0d32002-08-02 19:29:35 +00001130 Result = 0;
1131 }
Chris Lattner053c0932002-05-14 15:24:07 +00001132 }
Chris Lattner260ab202002-04-18 17:39:14 +00001133
Chris Lattnerae7a0d32002-08-02 19:29:35 +00001134 if (Result) {
1135 WorkList.push_back(Result);
1136 AddUsesToWorkList(*Result);
1137 }
Chris Lattner260ab202002-04-18 17:39:14 +00001138 Changed = true;
Chris Lattnerca081252001-12-14 16:52:21 +00001139 }
1140 }
1141
Chris Lattner260ab202002-04-18 17:39:14 +00001142 return Changed;
Chris Lattner04805fa2002-02-26 21:46:54 +00001143}
1144
1145Pass *createInstructionCombiningPass() {
Chris Lattner260ab202002-04-18 17:39:14 +00001146 return new InstCombiner();
Chris Lattner04805fa2002-02-26 21:46:54 +00001147}