blob: 067a884bc9d532a00165dc3a2783f02845798324 [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 Lattner65b529f2002-04-08 20:18:09 +000020#include "llvm/ConstantHandling.h"
Chris Lattnerca081252001-12-14 16:52:21 +000021#include "llvm/iMemory.h"
Chris Lattner3a60d042002-04-15 19:45:29 +000022#include "llvm/iOther.h"
Chris Lattnerbbbdd852002-05-06 18:06:38 +000023#include "llvm/iPHINode.h"
Chris Lattner260ab202002-04-18 17:39:14 +000024#include "llvm/iOperators.h"
Chris Lattner04805fa2002-02-26 21:46:54 +000025#include "llvm/Pass.h"
Chris Lattner1085bdf2002-11-04 16:18:53 +000026#include "llvm/DerivedTypes.h"
Chris Lattner60a65912002-02-12 21:07:25 +000027#include "llvm/Support/InstIterator.h"
Chris Lattner260ab202002-04-18 17:39:14 +000028#include "llvm/Support/InstVisitor.h"
Chris Lattnerbf3a0992002-10-01 22:38:41 +000029#include "Support/Statistic.h"
Chris Lattner053c0932002-05-14 15:24:07 +000030#include <algorithm>
Chris Lattnerca081252001-12-14 16:52:21 +000031
Chris Lattner260ab202002-04-18 17:39:14 +000032namespace {
Chris Lattnerbf3a0992002-10-01 22:38:41 +000033 Statistic<> NumCombined ("instcombine", "Number of insts combined");
34 Statistic<> NumConstProp("instcombine", "Number of constant folds");
35 Statistic<> NumDeadInst ("instcombine", "Number of dead inst eliminated");
36
Chris Lattnerc8e66542002-04-27 06:56:12 +000037 class InstCombiner : public FunctionPass,
Chris Lattner260ab202002-04-18 17:39:14 +000038 public InstVisitor<InstCombiner, Instruction*> {
39 // Worklist of all of the instructions that need to be simplified.
40 std::vector<Instruction*> WorkList;
41
Chris Lattner113f4f42002-06-25 16:13:24 +000042 void AddUsesToWorkList(Instruction &I) {
Chris Lattner260ab202002-04-18 17:39:14 +000043 // The instruction was simplified, add all users of the instruction to
44 // the work lists because they might get more simplified now...
45 //
Chris Lattner113f4f42002-06-25 16:13:24 +000046 for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
Chris Lattner260ab202002-04-18 17:39:14 +000047 UI != UE; ++UI)
48 WorkList.push_back(cast<Instruction>(*UI));
49 }
50
Chris Lattner99f48c62002-09-02 04:59:56 +000051 // removeFromWorkList - remove all instances of I from the worklist.
52 void removeFromWorkList(Instruction *I);
Chris Lattner260ab202002-04-18 17:39:14 +000053 public:
Chris Lattner113f4f42002-06-25 16:13:24 +000054 virtual bool runOnFunction(Function &F);
Chris Lattner260ab202002-04-18 17:39:14 +000055
Chris Lattnerf12cc842002-04-28 21:27:06 +000056 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Chris Lattner820d9712002-10-21 20:00:28 +000057 AU.setPreservesCFG();
Chris Lattnerf12cc842002-04-28 21:27:06 +000058 }
59
Chris Lattner260ab202002-04-18 17:39:14 +000060 // Visitation implementation - Implement instruction combining for different
61 // instruction types. The semantics are as follows:
62 // Return Value:
63 // null - No change was made
Chris Lattnere6794492002-08-12 21:17:25 +000064 // I - Change was made, I is still valid, I may be dead though
Chris Lattner260ab202002-04-18 17:39:14 +000065 // otherwise - Change was made, replace I with returned instruction
66 //
Chris Lattner113f4f42002-06-25 16:13:24 +000067 Instruction *visitAdd(BinaryOperator &I);
68 Instruction *visitSub(BinaryOperator &I);
69 Instruction *visitMul(BinaryOperator &I);
70 Instruction *visitDiv(BinaryOperator &I);
71 Instruction *visitRem(BinaryOperator &I);
72 Instruction *visitAnd(BinaryOperator &I);
73 Instruction *visitOr (BinaryOperator &I);
74 Instruction *visitXor(BinaryOperator &I);
75 Instruction *visitSetCondInst(BinaryOperator &I);
Chris Lattnere8d6c602003-03-10 19:16:08 +000076 Instruction *visitShiftInst(ShiftInst &I);
Chris Lattner113f4f42002-06-25 16:13:24 +000077 Instruction *visitCastInst(CastInst &CI);
78 Instruction *visitPHINode(PHINode &PN);
79 Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
Chris Lattner1085bdf2002-11-04 16:18:53 +000080 Instruction *visitAllocationInst(AllocationInst &AI);
Chris Lattner260ab202002-04-18 17:39:14 +000081
82 // visitInstruction - Specify what to return for unhandled instructions...
Chris Lattner113f4f42002-06-25 16:13:24 +000083 Instruction *visitInstruction(Instruction &I) { return 0; }
Chris Lattner6d14f2a2002-08-09 23:47:40 +000084
85 // InsertNewInstBefore - insert an instruction New before instruction Old
86 // in the program. Add the new instruction to the worklist.
87 //
88 void InsertNewInstBefore(Instruction *New, Instruction &Old) {
Chris Lattner65217ff2002-08-23 18:32:43 +000089 assert(New && New->getParent() == 0 &&
90 "New instruction already inserted into a basic block!");
Chris Lattner6d14f2a2002-08-09 23:47:40 +000091 BasicBlock *BB = Old.getParent();
92 BB->getInstList().insert(&Old, New); // Insert inst
93 WorkList.push_back(New); // Add to worklist
94 }
95
96 // ReplaceInstUsesWith - This method is to be used when an instruction is
97 // found to be dead, replacable with another preexisting expression. Here
98 // we add all uses of I to the worklist, replace all uses of I with the new
99 // value, then return I, so that the inst combiner will know that I was
100 // modified.
101 //
102 Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
103 AddUsesToWorkList(I); // Add all modified instrs to worklist
104 I.replaceAllUsesWith(V);
105 return &I;
106 }
Chris Lattner260ab202002-04-18 17:39:14 +0000107 };
Chris Lattnerb28b6802002-07-23 18:06:35 +0000108
Chris Lattnerc8b70922002-07-26 21:12:46 +0000109 RegisterOpt<InstCombiner> X("instcombine", "Combine redundant instructions");
Chris Lattner260ab202002-04-18 17:39:14 +0000110}
111
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000112// getComplexity: Assign a complexity or rank value to LLVM Values...
113// 0 -> Constant, 1 -> Other, 2 -> Argument, 2 -> Unary, 3 -> OtherInst
114static unsigned getComplexity(Value *V) {
115 if (isa<Instruction>(V)) {
116 if (BinaryOperator::isNeg(V) || BinaryOperator::isNot(V))
117 return 2;
118 return 3;
119 }
120 if (isa<Argument>(V)) return 2;
121 return isa<Constant>(V) ? 0 : 1;
122}
Chris Lattner260ab202002-04-18 17:39:14 +0000123
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000124// SimplifyCommutative - This performs a few simplifications for commutative
125// operators:
Chris Lattner260ab202002-04-18 17:39:14 +0000126//
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000127// 1. Order operands such that they are listed from right (least complex) to
128// left (most complex). This puts constants before unary operators before
129// binary operators.
130//
131// 2. Handle the case of (op (op V, C1), C2), changing it to:
132// (op V, (op C1, C2))
133//
134static bool SimplifyCommutative(BinaryOperator &I) {
135 bool Changed = false;
136 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
137 Changed = !I.swapOperands();
138
139 if (!I.isAssociative()) return Changed;
140 Instruction::BinaryOps Opcode = I.getOpcode();
141 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0))) {
142 if (Op->getOpcode() == Opcode && isa<Constant>(I.getOperand(1)) &&
143 isa<Constant>(Op->getOperand(1))) {
144 Instruction *New = BinaryOperator::create(I.getOpcode(), I.getOperand(1),
145 Op->getOperand(1));
146 Constant *Folded = ConstantFoldInstruction(New);
147 delete New;
148 assert(Folded && "Couldn't constant fold commutative operand?");
149 I.setOperand(0, Op->getOperand(0));
150 I.setOperand(1, Folded);
151 return true;
152 }
153 }
154 return Changed;
Chris Lattner260ab202002-04-18 17:39:14 +0000155}
Chris Lattnerca081252001-12-14 16:52:21 +0000156
Chris Lattnerbb74e222003-03-10 23:06:50 +0000157// dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
158// if the LHS is a constant zero (which is the 'negate' form).
Chris Lattner9fa53de2002-05-06 16:49:18 +0000159//
Chris Lattnerbb74e222003-03-10 23:06:50 +0000160static inline Value *dyn_castNegVal(Value *V) {
161 if (BinaryOperator::isNeg(V))
162 return BinaryOperator::getNegArgument(cast<BinaryOperator>(V));
163
164 // Constants can be considered to be negated values...
165 if (Constant *C = dyn_cast<Constant>(V)) {
166 Constant *NC = *Constant::getNullValue(V->getType()) - *C;
167 assert(NC && "Couldn't constant fold a subtract!");
168 return NC;
169 }
170 return 0;
Chris Lattner9fa53de2002-05-06 16:49:18 +0000171}
172
Chris Lattnerbb74e222003-03-10 23:06:50 +0000173static inline Value *dyn_castNotVal(Value *V) {
174 if (BinaryOperator::isNot(V))
175 return BinaryOperator::getNotArgument(cast<BinaryOperator>(V));
176
177 // Constants can be considered to be not'ed values...
178 if (ConstantIntegral *C = dyn_cast<ConstantIntegral>(V)) {
179 Constant *NC = *ConstantIntegral::getAllOnesValue(C->getType()) ^ *C;
180 assert(NC && "Couldn't constant fold an exclusive or!");
181 return NC;
182 }
183 return 0;
184}
185
186static bool isOnlyUse(Value *V) {
187 return V->use_size() == 1 || isa<Constant>(V);
Chris Lattner3082c5a2003-02-18 19:28:33 +0000188}
Chris Lattner31ae8632002-08-14 17:51:49 +0000189
Chris Lattner3082c5a2003-02-18 19:28:33 +0000190
191// Log2 - Calculate the log base 2 for the specified value if it is exactly a
192// power of 2.
193static unsigned Log2(uint64_t Val) {
194 assert(Val > 1 && "Values 0 and 1 should be handled elsewhere!");
195 unsigned Count = 0;
196 while (Val != 1) {
197 if (Val & 1) return 0; // Multiple bits set?
198 Val >>= 1;
199 ++Count;
200 }
201 return Count;
Chris Lattner31ae8632002-08-14 17:51:49 +0000202}
203
Chris Lattner57c8d992003-02-18 19:57:07 +0000204static inline Value *dyn_castFoldableMul(Value *V) {
205 if (V->use_size() == 1 && V->getType()->isInteger())
206 if (Instruction *I = dyn_cast<Instruction>(V))
207 if (I->getOpcode() == Instruction::Mul)
208 if (isa<Constant>(I->getOperand(1)))
209 return I->getOperand(0);
210 return 0;
211}
212
213
Chris Lattner113f4f42002-06-25 16:13:24 +0000214Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000215 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +0000216 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
Chris Lattner9fa53de2002-05-06 16:49:18 +0000217
218 // Eliminate 'add int %X, 0'
Chris Lattnere6794492002-08-12 21:17:25 +0000219 if (RHS == Constant::getNullValue(I.getType()))
220 return ReplaceInstUsesWith(I, LHS);
Chris Lattner9fa53de2002-05-06 16:49:18 +0000221
Chris Lattner147e9752002-05-08 22:46:53 +0000222 // -A + B --> B - A
Chris Lattnerbb74e222003-03-10 23:06:50 +0000223 if (Value *V = dyn_castNegVal(LHS))
Chris Lattner147e9752002-05-08 22:46:53 +0000224 return BinaryOperator::create(Instruction::Sub, RHS, V);
Chris Lattner9fa53de2002-05-06 16:49:18 +0000225
226 // A + -B --> A - B
Chris Lattnerbb74e222003-03-10 23:06:50 +0000227 if (!isa<Constant>(RHS))
228 if (Value *V = dyn_castNegVal(RHS))
229 return BinaryOperator::create(Instruction::Sub, LHS, V);
Chris Lattner260ab202002-04-18 17:39:14 +0000230
Chris Lattner57c8d992003-02-18 19:57:07 +0000231 // X*C + X --> X * (C+1)
232 if (dyn_castFoldableMul(LHS) == RHS) {
233 Constant *CP1 = *cast<Constant>(cast<Instruction>(LHS)->getOperand(1)) +
234 *ConstantInt::get(I.getType(), 1);
235 assert(CP1 && "Couldn't constant fold C + 1?");
236 return BinaryOperator::create(Instruction::Mul, RHS, CP1);
237 }
238
239 // X + X*C --> X * (C+1)
240 if (dyn_castFoldableMul(RHS) == LHS) {
241 Constant *CP1 = *cast<Constant>(cast<Instruction>(RHS)->getOperand(1)) +
242 *ConstantInt::get(I.getType(), 1);
243 assert(CP1 && "Couldn't constant fold C + 1?");
244 return BinaryOperator::create(Instruction::Mul, LHS, CP1);
245 }
246
Chris Lattner113f4f42002-06-25 16:13:24 +0000247 return Changed ? &I : 0;
Chris Lattner260ab202002-04-18 17:39:14 +0000248}
249
Chris Lattner113f4f42002-06-25 16:13:24 +0000250Instruction *InstCombiner::visitSub(BinaryOperator &I) {
Chris Lattner113f4f42002-06-25 16:13:24 +0000251 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000252
Chris Lattnere6794492002-08-12 21:17:25 +0000253 if (Op0 == Op1) // sub X, X -> 0
254 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner260ab202002-04-18 17:39:14 +0000255
Chris Lattnere6794492002-08-12 21:17:25 +0000256 // If this is a 'B = x-(-A)', change to B = x+A...
Chris Lattnerbb74e222003-03-10 23:06:50 +0000257 if (Value *V = dyn_castNegVal(Op1))
Chris Lattner147e9752002-05-08 22:46:53 +0000258 return BinaryOperator::create(Instruction::Add, Op0, V);
Chris Lattner9fa53de2002-05-06 16:49:18 +0000259
Chris Lattner3082c5a2003-02-18 19:28:33 +0000260 // Replace (-1 - A) with (~A)...
261 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0))
262 if (C->isAllOnesValue())
263 return BinaryOperator::createNot(Op1);
Chris Lattnerad3c4952002-05-09 01:29:19 +0000264
Chris Lattner3082c5a2003-02-18 19:28:33 +0000265 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1))
266 if (Op1I->use_size() == 1) {
267 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
268 // is not used by anyone else...
269 //
270 if (Op1I->getOpcode() == Instruction::Sub) {
271 // Swap the two operands of the subexpr...
272 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
273 Op1I->setOperand(0, IIOp1);
274 Op1I->setOperand(1, IIOp0);
275
276 // Create the new top level add instruction...
277 return BinaryOperator::create(Instruction::Add, Op0, Op1);
278 }
279
280 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
281 //
282 if (Op1I->getOpcode() == Instruction::And &&
283 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
284 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
285
286 Instruction *NewNot = BinaryOperator::createNot(OtherOp, "B.not", &I);
287 return BinaryOperator::create(Instruction::And, Op0, NewNot);
288 }
Chris Lattner57c8d992003-02-18 19:57:07 +0000289
290 // X - X*C --> X * (1-C)
291 if (dyn_castFoldableMul(Op1I) == Op0) {
292 Constant *CP1 = *ConstantInt::get(I.getType(), 1) -
293 *cast<Constant>(cast<Instruction>(Op1)->getOperand(1));
294 assert(CP1 && "Couldn't constant fold 1-C?");
295 return BinaryOperator::create(Instruction::Mul, Op0, CP1);
296 }
Chris Lattnerad3c4952002-05-09 01:29:19 +0000297 }
Chris Lattner3082c5a2003-02-18 19:28:33 +0000298
Chris Lattner57c8d992003-02-18 19:57:07 +0000299 // X*C - X --> X * (C-1)
300 if (dyn_castFoldableMul(Op0) == Op1) {
301 Constant *CP1 = *cast<Constant>(cast<Instruction>(Op0)->getOperand(1)) -
302 *ConstantInt::get(I.getType(), 1);
303 assert(CP1 && "Couldn't constant fold C - 1?");
304 return BinaryOperator::create(Instruction::Mul, Op1, CP1);
305 }
306
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000307 return 0;
Chris Lattner260ab202002-04-18 17:39:14 +0000308}
309
Chris Lattner113f4f42002-06-25 16:13:24 +0000310Instruction *InstCombiner::visitMul(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000311 bool Changed = SimplifyCommutative(I);
Chris Lattner3082c5a2003-02-18 19:28:33 +0000312 Value *Op0 = I.getOperand(0);
Chris Lattner260ab202002-04-18 17:39:14 +0000313
Chris Lattnere6794492002-08-12 21:17:25 +0000314 // Simplify mul instructions with a constant RHS...
Chris Lattner3082c5a2003-02-18 19:28:33 +0000315 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
316 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
317 const Type *Ty = CI->getType();
318 uint64_t Val = Ty->isSigned() ?
319 (uint64_t)cast<ConstantSInt>(CI)->getValue() :
320 cast<ConstantUInt>(CI)->getValue();
321 switch (Val) {
322 case 0:
323 return ReplaceInstUsesWith(I, Op1); // Eliminate 'mul double %X, 0'
324 case 1:
325 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul int %X, 1'
326 case 2: // Convert 'mul int %X, 2' to 'add int %X, %X'
327 return BinaryOperator::create(Instruction::Add, Op0, Op0, I.getName());
328 }
Chris Lattner31ba1292002-04-29 22:24:47 +0000329
Chris Lattner3082c5a2003-02-18 19:28:33 +0000330 if (uint64_t C = Log2(Val)) // Replace X*(2^C) with X << C
331 return new ShiftInst(Instruction::Shl, Op0,
332 ConstantUInt::get(Type::UByteTy, C));
333 } else {
334 ConstantFP *Op1F = cast<ConstantFP>(Op1);
335 if (Op1F->isNullValue())
336 return ReplaceInstUsesWith(I, Op1);
Chris Lattner31ba1292002-04-29 22:24:47 +0000337
Chris Lattner3082c5a2003-02-18 19:28:33 +0000338 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
339 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
340 if (Op1F->getValue() == 1.0)
341 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0'
342 }
Chris Lattner260ab202002-04-18 17:39:14 +0000343 }
344
Chris Lattner934a64cf2003-03-10 23:23:04 +0000345 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
346 if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
347 return BinaryOperator::create(Instruction::Mul, Op0v, Op1v);
348
Chris Lattner113f4f42002-06-25 16:13:24 +0000349 return Changed ? &I : 0;
Chris Lattner260ab202002-04-18 17:39:14 +0000350}
351
Chris Lattner113f4f42002-06-25 16:13:24 +0000352Instruction *InstCombiner::visitDiv(BinaryOperator &I) {
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000353 // div X, 1 == X
Chris Lattner3082c5a2003-02-18 19:28:33 +0000354 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I.getOperand(1))) {
Chris Lattnere6794492002-08-12 21:17:25 +0000355 if (RHS->equalsInt(1))
356 return ReplaceInstUsesWith(I, I.getOperand(0));
Chris Lattner3082c5a2003-02-18 19:28:33 +0000357
358 // Check to see if this is an unsigned division with an exact power of 2,
359 // if so, convert to a right shift.
360 if (ConstantUInt *C = dyn_cast<ConstantUInt>(RHS))
361 if (uint64_t Val = C->getValue()) // Don't break X / 0
362 if (uint64_t C = Log2(Val))
363 return new ShiftInst(Instruction::Shr, I.getOperand(0),
364 ConstantUInt::get(Type::UByteTy, C));
365 }
366
367 // 0 / X == 0, we don't need to preserve faults!
368 if (ConstantInt *LHS = dyn_cast<ConstantInt>(I.getOperand(0)))
369 if (LHS->equalsInt(0))
370 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
371
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000372 return 0;
373}
374
375
Chris Lattner113f4f42002-06-25 16:13:24 +0000376Instruction *InstCombiner::visitRem(BinaryOperator &I) {
Chris Lattner3082c5a2003-02-18 19:28:33 +0000377 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I.getOperand(1))) {
378 if (RHS->equalsInt(1)) // X % 1 == 0
379 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
380
381 // Check to see if this is an unsigned remainder with an exact power of 2,
382 // if so, convert to a bitwise and.
383 if (ConstantUInt *C = dyn_cast<ConstantUInt>(RHS))
384 if (uint64_t Val = C->getValue()) // Don't break X % 0 (divide by zero)
385 if (Log2(Val))
386 return BinaryOperator::create(Instruction::And, I.getOperand(0),
387 ConstantUInt::get(I.getType(), Val-1));
388 }
389
390 // 0 % X == 0, we don't need to preserve faults!
391 if (ConstantInt *LHS = dyn_cast<ConstantInt>(I.getOperand(0)))
392 if (LHS->equalsInt(0))
Chris Lattnere6794492002-08-12 21:17:25 +0000393 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
394
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000395 return 0;
396}
397
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000398// isMaxValueMinusOne - return true if this is Max-1
Chris Lattnere6794492002-08-12 21:17:25 +0000399static bool isMaxValueMinusOne(const ConstantInt *C) {
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000400 if (const ConstantUInt *CU = dyn_cast<ConstantUInt>(C)) {
401 // Calculate -1 casted to the right type...
402 unsigned TypeBits = C->getType()->getPrimitiveSize()*8;
403 uint64_t Val = ~0ULL; // All ones
404 Val >>= 64-TypeBits; // Shift out unwanted 1 bits...
405 return CU->getValue() == Val-1;
406 }
407
408 const ConstantSInt *CS = cast<ConstantSInt>(C);
409
410 // Calculate 0111111111..11111
411 unsigned TypeBits = C->getType()->getPrimitiveSize()*8;
412 int64_t Val = INT64_MAX; // All ones
413 Val >>= 64-TypeBits; // Shift out unwanted 1 bits...
414 return CS->getValue() == Val-1;
415}
416
417// isMinValuePlusOne - return true if this is Min+1
Chris Lattnere6794492002-08-12 21:17:25 +0000418static bool isMinValuePlusOne(const ConstantInt *C) {
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000419 if (const ConstantUInt *CU = dyn_cast<ConstantUInt>(C))
420 return CU->getValue() == 1;
421
422 const ConstantSInt *CS = cast<ConstantSInt>(C);
423
424 // Calculate 1111111111000000000000
425 unsigned TypeBits = C->getType()->getPrimitiveSize()*8;
426 int64_t Val = -1; // All ones
427 Val <<= TypeBits-1; // Shift over to the right spot
428 return CS->getValue() == Val+1;
429}
430
431
Chris Lattner113f4f42002-06-25 16:13:24 +0000432Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000433 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +0000434 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000435
436 // and X, X = X and X, 0 == 0
Chris Lattnere6794492002-08-12 21:17:25 +0000437 if (Op0 == Op1 || Op1 == Constant::getNullValue(I.getType()))
438 return ReplaceInstUsesWith(I, Op1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000439
440 // and X, -1 == X
Chris Lattner83282632002-08-13 17:50:24 +0000441 if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1))
Chris Lattnere6794492002-08-12 21:17:25 +0000442 if (RHS->isAllOnesValue())
443 return ReplaceInstUsesWith(I, Op0);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000444
Chris Lattnerbb74e222003-03-10 23:06:50 +0000445 Value *Op0NotVal = dyn_castNotVal(Op0);
446 Value *Op1NotVal = dyn_castNotVal(Op1);
Chris Lattner3082c5a2003-02-18 19:28:33 +0000447
448 // (~A & ~B) == (~(A | B)) - Demorgan's Law
Chris Lattnerbb74e222003-03-10 23:06:50 +0000449 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Chris Lattner3082c5a2003-02-18 19:28:33 +0000450 Instruction *Or = BinaryOperator::create(Instruction::Or, Op0NotVal,
451 Op1NotVal,I.getName()+".demorgan",
452 &I);
Chris Lattner3e327a42003-03-10 23:13:59 +0000453 WorkList.push_back(Or);
Chris Lattner3082c5a2003-02-18 19:28:33 +0000454 return BinaryOperator::createNot(Or);
455 }
456
457 if (Op0NotVal == Op1 || Op1NotVal == Op0) // A & ~A == ~A & A == 0
458 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner65217ff2002-08-23 18:32:43 +0000459
Chris Lattner113f4f42002-06-25 16:13:24 +0000460 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000461}
462
463
464
Chris Lattner113f4f42002-06-25 16:13:24 +0000465Instruction *InstCombiner::visitOr(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000466 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +0000467 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000468
469 // or X, X = X or X, 0 == X
Chris Lattnere6794492002-08-12 21:17:25 +0000470 if (Op0 == Op1 || Op1 == Constant::getNullValue(I.getType()))
471 return ReplaceInstUsesWith(I, Op0);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000472
473 // or X, -1 == -1
Chris Lattner83282632002-08-13 17:50:24 +0000474 if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1))
Chris Lattnere6794492002-08-12 21:17:25 +0000475 if (RHS->isAllOnesValue())
476 return ReplaceInstUsesWith(I, Op1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000477
Chris Lattner3e327a42003-03-10 23:13:59 +0000478 Value *Op0NotVal = dyn_castNotVal(Op0);
479 Value *Op1NotVal = dyn_castNotVal(Op1);
Chris Lattner3082c5a2003-02-18 19:28:33 +0000480
Chris Lattner3e327a42003-03-10 23:13:59 +0000481 if (Op1 == Op0NotVal) // ~A | A == -1
482 return ReplaceInstUsesWith(I,
483 ConstantIntegral::getAllOnesValue(I.getType()));
484
485 if (Op0 == Op1NotVal) // A | ~A == -1
486 return ReplaceInstUsesWith(I,
487 ConstantIntegral::getAllOnesValue(I.getType()));
488
489 // (~A | ~B) == (~(A & B)) - Demorgan's Law
490 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
491 Instruction *And = BinaryOperator::create(Instruction::And, Op0NotVal,
492 Op1NotVal,I.getName()+".demorgan",
493 &I);
494 WorkList.push_back(And);
495 return BinaryOperator::createNot(And);
496 }
Chris Lattner3082c5a2003-02-18 19:28:33 +0000497
Chris Lattner113f4f42002-06-25 16:13:24 +0000498 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000499}
500
501
502
Chris Lattner113f4f42002-06-25 16:13:24 +0000503Instruction *InstCombiner::visitXor(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000504 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +0000505 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000506
507 // xor X, X = 0
Chris Lattnere6794492002-08-12 21:17:25 +0000508 if (Op0 == Op1)
509 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000510
Chris Lattner83282632002-08-13 17:50:24 +0000511 if (ConstantIntegral *Op1C = dyn_cast<ConstantIntegral>(Op1)) {
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000512 // xor X, 0 == X
Chris Lattnere6794492002-08-12 21:17:25 +0000513 if (Op1C->isNullValue())
514 return ReplaceInstUsesWith(I, Op0);
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000515
Chris Lattnerb8d6e402002-08-20 18:24:26 +0000516 // Is this a "NOT" instruction?
517 if (Op1C->isAllOnesValue()) {
518 // xor (xor X, -1), -1 = not (not X) = X
Chris Lattnerbb74e222003-03-10 23:06:50 +0000519 if (Value *X = dyn_castNotVal(Op0))
Chris Lattner31ae8632002-08-14 17:51:49 +0000520 return ReplaceInstUsesWith(I, X);
Chris Lattnerb8d6e402002-08-20 18:24:26 +0000521
522 // xor (setcc A, B), true = not (setcc A, B) = setncc A, B
523 if (SetCondInst *SCI = dyn_cast<SetCondInst>(Op0))
524 if (SCI->use_size() == 1)
525 return new SetCondInst(SCI->getInverseCondition(),
526 SCI->getOperand(0), SCI->getOperand(1));
527 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000528 }
529
Chris Lattnerbb74e222003-03-10 23:06:50 +0000530 if (Value *X = dyn_castNotVal(Op0)) // ~A ^ A == -1
Chris Lattner3082c5a2003-02-18 19:28:33 +0000531 if (X == Op1)
532 return ReplaceInstUsesWith(I,
533 ConstantIntegral::getAllOnesValue(I.getType()));
534
Chris Lattnerbb74e222003-03-10 23:06:50 +0000535 if (Value *X = dyn_castNotVal(Op1)) // A ^ ~A == -1
Chris Lattner3082c5a2003-02-18 19:28:33 +0000536 if (X == Op0)
537 return ReplaceInstUsesWith(I,
538 ConstantIntegral::getAllOnesValue(I.getType()));
539
Chris Lattner1bbb7b62003-03-10 18:24:17 +0000540
541
542 if (Instruction *Op1I = dyn_cast<Instruction>(Op1))
543 if (Op1I->getOpcode() == Instruction::Or)
544 if (Op1I->getOperand(0) == Op0) { // B^(B|A) == (A|B)^B
545 cast<BinaryOperator>(Op1I)->swapOperands();
546 I.swapOperands();
547 std::swap(Op0, Op1);
548 } else if (Op1I->getOperand(1) == Op0) { // B^(A|B) == (A|B)^B
549 I.swapOperands();
550 std::swap(Op0, Op1);
551 }
552
553 if (Instruction *Op0I = dyn_cast<Instruction>(Op0))
554 if (Op0I->getOpcode() == Instruction::Or && Op0I->use_size() == 1) {
555 if (Op0I->getOperand(0) == Op1) // (B|A)^B == (A|B)^B
556 cast<BinaryOperator>(Op0I)->swapOperands();
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000557 if (Op0I->getOperand(1) == Op1) { // (A|B)^B == A & ~B
Chris Lattner1bbb7b62003-03-10 18:24:17 +0000558 Value *NotB = BinaryOperator::createNot(Op1, Op1->getName()+".not", &I);
559 WorkList.push_back(cast<Instruction>(NotB));
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000560 return BinaryOperator::create(Instruction::And, Op0I->getOperand(0),
561 NotB);
Chris Lattner1bbb7b62003-03-10 18:24:17 +0000562 }
563 }
564
Chris Lattner113f4f42002-06-25 16:13:24 +0000565 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000566}
567
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000568// AddOne, SubOne - Add or subtract a constant one from an integer constant...
569static Constant *AddOne(ConstantInt *C) {
570 Constant *Result = *C + *ConstantInt::get(C->getType(), 1);
571 assert(Result && "Constant folding integer addition failed!");
572 return Result;
573}
574static Constant *SubOne(ConstantInt *C) {
575 Constant *Result = *C - *ConstantInt::get(C->getType(), 1);
576 assert(Result && "Constant folding integer addition failed!");
577 return Result;
578}
579
Chris Lattner1fc23f32002-05-09 20:11:54 +0000580// isTrueWhenEqual - Return true if the specified setcondinst instruction is
581// true when both operands are equal...
582//
Chris Lattner113f4f42002-06-25 16:13:24 +0000583static bool isTrueWhenEqual(Instruction &I) {
584 return I.getOpcode() == Instruction::SetEQ ||
585 I.getOpcode() == Instruction::SetGE ||
586 I.getOpcode() == Instruction::SetLE;
Chris Lattner1fc23f32002-05-09 20:11:54 +0000587}
588
Chris Lattner113f4f42002-06-25 16:13:24 +0000589Instruction *InstCombiner::visitSetCondInst(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000590 bool Changed = SimplifyCommutative(I);
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000591 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
592 const Type *Ty = Op0->getType();
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000593
594 // setcc X, X
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000595 if (Op0 == Op1)
596 return ReplaceInstUsesWith(I, ConstantBool::get(isTrueWhenEqual(I)));
Chris Lattner1fc23f32002-05-09 20:11:54 +0000597
598 // setcc <global*>, 0 - Global value addresses are never null!
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000599 if (isa<GlobalValue>(Op0) && isa<ConstantPointerNull>(Op1))
600 return ReplaceInstUsesWith(I, ConstantBool::get(!isTrueWhenEqual(I)));
601
602 // setcc's with boolean values can always be turned into bitwise operations
603 if (Ty == Type::BoolTy) {
604 // If this is <, >, or !=, we can change this into a simple xor instruction
605 if (!isTrueWhenEqual(I))
606 return BinaryOperator::create(Instruction::Xor, Op0, Op1, I.getName());
607
608 // Otherwise we need to make a temporary intermediate instruction and insert
609 // it into the instruction stream. This is what we are after:
610 //
611 // seteq bool %A, %B -> ~(A^B)
612 // setle bool %A, %B -> ~A | B
613 // setge bool %A, %B -> A | ~B
614 //
615 if (I.getOpcode() == Instruction::SetEQ) { // seteq case
616 Instruction *Xor = BinaryOperator::create(Instruction::Xor, Op0, Op1,
617 I.getName()+"tmp");
618 InsertNewInstBefore(Xor, I);
Chris Lattner31ae8632002-08-14 17:51:49 +0000619 return BinaryOperator::createNot(Xor, I.getName());
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000620 }
621
622 // Handle the setXe cases...
623 assert(I.getOpcode() == Instruction::SetGE ||
624 I.getOpcode() == Instruction::SetLE);
625
626 if (I.getOpcode() == Instruction::SetGE)
627 std::swap(Op0, Op1); // Change setge -> setle
628
629 // Now we just have the SetLE case.
Chris Lattner31ae8632002-08-14 17:51:49 +0000630 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000631 InsertNewInstBefore(Not, I);
632 return BinaryOperator::create(Instruction::Or, Not, Op1, I.getName());
633 }
634
635 // Check to see if we are doing one of many comparisons against constant
636 // integers at the end of their ranges...
637 //
638 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
639 // Check to see if we are comparing against the minimum or maximum value...
Chris Lattnere6794492002-08-12 21:17:25 +0000640 if (CI->isMinValue()) {
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000641 if (I.getOpcode() == Instruction::SetLT) // A < MIN -> FALSE
642 return ReplaceInstUsesWith(I, ConstantBool::False);
643 if (I.getOpcode() == Instruction::SetGE) // A >= MIN -> TRUE
644 return ReplaceInstUsesWith(I, ConstantBool::True);
645 if (I.getOpcode() == Instruction::SetLE) // A <= MIN -> A == MIN
646 return BinaryOperator::create(Instruction::SetEQ, Op0,Op1, I.getName());
647 if (I.getOpcode() == Instruction::SetGT) // A > MIN -> A != MIN
648 return BinaryOperator::create(Instruction::SetNE, Op0,Op1, I.getName());
649
Chris Lattnere6794492002-08-12 21:17:25 +0000650 } else if (CI->isMaxValue()) {
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000651 if (I.getOpcode() == Instruction::SetGT) // A > MAX -> FALSE
652 return ReplaceInstUsesWith(I, ConstantBool::False);
653 if (I.getOpcode() == Instruction::SetLE) // A <= MAX -> TRUE
654 return ReplaceInstUsesWith(I, ConstantBool::True);
655 if (I.getOpcode() == Instruction::SetGE) // A >= MAX -> A == MAX
656 return BinaryOperator::create(Instruction::SetEQ, Op0,Op1, I.getName());
657 if (I.getOpcode() == Instruction::SetLT) // A < MAX -> A != MAX
658 return BinaryOperator::create(Instruction::SetNE, Op0,Op1, I.getName());
659
660 // Comparing against a value really close to min or max?
661 } else if (isMinValuePlusOne(CI)) {
662 if (I.getOpcode() == Instruction::SetLT) // A < MIN+1 -> A == MIN
663 return BinaryOperator::create(Instruction::SetEQ, Op0,
664 SubOne(CI), I.getName());
665 if (I.getOpcode() == Instruction::SetGE) // A >= MIN-1 -> A != MIN
666 return BinaryOperator::create(Instruction::SetNE, Op0,
667 SubOne(CI), I.getName());
668
669 } else if (isMaxValueMinusOne(CI)) {
670 if (I.getOpcode() == Instruction::SetGT) // A > MAX-1 -> A == MAX
671 return BinaryOperator::create(Instruction::SetEQ, Op0,
672 AddOne(CI), I.getName());
673 if (I.getOpcode() == Instruction::SetLE) // A <= MAX-1 -> A != MAX
674 return BinaryOperator::create(Instruction::SetNE, Op0,
675 AddOne(CI), I.getName());
676 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000677 }
678
Chris Lattner113f4f42002-06-25 16:13:24 +0000679 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000680}
681
682
683
Chris Lattnere8d6c602003-03-10 19:16:08 +0000684Instruction *InstCombiner::visitShiftInst(ShiftInst &I) {
Chris Lattner113f4f42002-06-25 16:13:24 +0000685 assert(I.getOperand(1)->getType() == Type::UByteTy);
686 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000687
688 // shl X, 0 == X and shr X, 0 == X
689 // shl 0, X == 0 and shr 0, X == 0
690 if (Op1 == Constant::getNullValue(Type::UByteTy) ||
Chris Lattnere6794492002-08-12 21:17:25 +0000691 Op0 == Constant::getNullValue(Op0->getType()))
692 return ReplaceInstUsesWith(I, Op0);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000693
Chris Lattnere8d6c602003-03-10 19:16:08 +0000694 // If this is a shift of a shift, see if we can fold the two together...
695 if (ShiftInst *Op0SI = dyn_cast<ShiftInst>(Op0)) {
696 if (isa<Constant>(Op1) && isa<Constant>(Op0SI->getOperand(1))) {
697 ConstantUInt *ShiftAmt1C = cast<ConstantUInt>(Op0SI->getOperand(1));
698 unsigned ShiftAmt1 = ShiftAmt1C->getValue();
699 unsigned ShiftAmt2 = cast<ConstantUInt>(Op1)->getValue();
700
701 // Check for (A << c1) << c2 and (A >> c1) >> c2
702 if (I.getOpcode() == Op0SI->getOpcode()) {
703 unsigned Amt = ShiftAmt1+ShiftAmt2; // Fold into one big shift...
704 return new ShiftInst(I.getOpcode(), Op0SI->getOperand(0),
705 ConstantUInt::get(Type::UByteTy, Amt));
706 }
707
708 if (I.getType()->isUnsigned()) { // Check for (A << c1) >> c2 or visaversa
709 // Calculate bitmask for what gets shifted off the edge...
710 Constant *C = ConstantIntegral::getAllOnesValue(I.getType());
711 if (I.getOpcode() == Instruction::Shr)
712 C = *C >> *ShiftAmt1C;
713 else
714 C = *C << *ShiftAmt1C;
715 assert(C && "Couldn't constant fold shift expression?");
716
717 Instruction *Mask =
718 BinaryOperator::create(Instruction::And, Op0SI->getOperand(0),
719 C, Op0SI->getOperand(0)->getName()+".mask",&I);
720 WorkList.push_back(Mask);
721
722 // Figure out what flavor of shift we should use...
723 if (ShiftAmt1 == ShiftAmt2)
724 return ReplaceInstUsesWith(I, Mask); // (A << c) >> c === A & c2
725 else if (ShiftAmt1 < ShiftAmt2) {
726 return new ShiftInst(I.getOpcode(), Mask,
727 ConstantUInt::get(Type::UByteTy, ShiftAmt2-ShiftAmt1));
728 } else {
729 return new ShiftInst(Op0SI->getOpcode(), Mask,
730 ConstantUInt::get(Type::UByteTy, ShiftAmt1-ShiftAmt2));
731 }
732 }
733 }
734 }
735
Chris Lattnere6794492002-08-12 21:17:25 +0000736 // shl uint X, 32 = 0 and shr ubyte Y, 9 = 0, ... just don't eliminate shr of
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000737 // a signed value.
738 //
739 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(Op1)) {
Chris Lattnere8d6c602003-03-10 19:16:08 +0000740 unsigned TypeBits = Op0->getType()->getPrimitiveSize()*8;
741 if (CUI->getValue() >= TypeBits &&
742 (!Op0->getType()->isSigned() || I.getOpcode() == Instruction::Shl))
743 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
Chris Lattner55f3d942002-09-10 23:04:09 +0000744
745 // Check to see if we are shifting left by 1. If so, turn it into an add
746 // instruction.
747 if (I.getOpcode() == Instruction::Shl && CUI->equalsInt(1))
Chris Lattner3082c5a2003-02-18 19:28:33 +0000748 // Convert 'shl int %X, 1' to 'add int %X, %X'
Chris Lattner55f3d942002-09-10 23:04:09 +0000749 return BinaryOperator::create(Instruction::Add, Op0, Op0, I.getName());
750
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000751 }
Chris Lattner2e0fb392002-10-08 16:16:40 +0000752
753 // shr int -1, X = -1 (for any arithmetic shift rights of ~0)
754 if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(Op0))
755 if (I.getOpcode() == Instruction::Shr && CSI->isAllOnesValue())
756 return ReplaceInstUsesWith(I, CSI);
757
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000758 return 0;
759}
760
761
Chris Lattner48a44f72002-05-02 17:06:02 +0000762// isEliminableCastOfCast - Return true if it is valid to eliminate the CI
763// instruction.
764//
Chris Lattner113f4f42002-06-25 16:13:24 +0000765static inline bool isEliminableCastOfCast(const CastInst &CI,
Chris Lattner48a44f72002-05-02 17:06:02 +0000766 const CastInst *CSrc) {
Chris Lattner113f4f42002-06-25 16:13:24 +0000767 assert(CI.getOperand(0) == CSrc);
Chris Lattner48a44f72002-05-02 17:06:02 +0000768 const Type *SrcTy = CSrc->getOperand(0)->getType();
769 const Type *MidTy = CSrc->getType();
Chris Lattner113f4f42002-06-25 16:13:24 +0000770 const Type *DstTy = CI.getType();
Chris Lattner48a44f72002-05-02 17:06:02 +0000771
Chris Lattner650b6da2002-08-02 20:00:25 +0000772 // It is legal to eliminate the instruction if casting A->B->A if the sizes
773 // are identical and the bits don't get reinterpreted (for example
Chris Lattner0bb75912002-08-14 23:21:10 +0000774 // int->float->int would not be allowed)
Chris Lattner650b6da2002-08-02 20:00:25 +0000775 if (SrcTy == DstTy && SrcTy->isLosslesslyConvertableTo(MidTy))
776 return true;
Chris Lattner48a44f72002-05-02 17:06:02 +0000777
778 // Allow free casting and conversion of sizes as long as the sign doesn't
779 // change...
Chris Lattnerb0b412e2002-09-03 01:08:28 +0000780 if (SrcTy->isIntegral() && MidTy->isIntegral() && DstTy->isIntegral()) {
Chris Lattner650b6da2002-08-02 20:00:25 +0000781 unsigned SrcSize = SrcTy->getPrimitiveSize();
782 unsigned MidSize = MidTy->getPrimitiveSize();
783 unsigned DstSize = DstTy->getPrimitiveSize();
Chris Lattner650b6da2002-08-02 20:00:25 +0000784
Chris Lattner3732aca2002-08-15 16:15:25 +0000785 // Cases where we are monotonically decreasing the size of the type are
786 // always ok, regardless of what sign changes are going on.
787 //
Chris Lattner0bb75912002-08-14 23:21:10 +0000788 if (SrcSize >= MidSize && MidSize >= DstSize)
Chris Lattner650b6da2002-08-02 20:00:25 +0000789 return true;
Chris Lattner3732aca2002-08-15 16:15:25 +0000790
Chris Lattner555518c2002-09-23 23:39:43 +0000791 // Cases where the source and destination type are the same, but the middle
792 // type is bigger are noops.
793 //
794 if (SrcSize == DstSize && MidSize > SrcSize)
795 return true;
796
Chris Lattner3732aca2002-08-15 16:15:25 +0000797 // If we are monotonically growing, things are more complex.
798 //
799 if (SrcSize <= MidSize && MidSize <= DstSize) {
800 // We have eight combinations of signedness to worry about. Here's the
801 // table:
802 static const int SignTable[8] = {
803 // CODE, SrcSigned, MidSigned, DstSigned, Comment
804 1, // U U U Always ok
805 1, // U U S Always ok
806 3, // U S U Ok iff SrcSize != MidSize
807 3, // U S S Ok iff SrcSize != MidSize
808 0, // S U U Never ok
809 2, // S U S Ok iff MidSize == DstSize
810 1, // S S U Always ok
811 1, // S S S Always ok
812 };
813
814 // Choose an action based on the current entry of the signtable that this
815 // cast of cast refers to...
816 unsigned Row = SrcTy->isSigned()*4+MidTy->isSigned()*2+DstTy->isSigned();
817 switch (SignTable[Row]) {
818 case 0: return false; // Never ok
819 case 1: return true; // Always ok
820 case 2: return MidSize == DstSize; // Ok iff MidSize == DstSize
821 case 3: // Ok iff SrcSize != MidSize
822 return SrcSize != MidSize || SrcTy == Type::BoolTy;
823 default: assert(0 && "Bad entry in sign table!");
824 }
Chris Lattner3732aca2002-08-15 16:15:25 +0000825 }
Chris Lattner650b6da2002-08-02 20:00:25 +0000826 }
Chris Lattner48a44f72002-05-02 17:06:02 +0000827
828 // Otherwise, we cannot succeed. Specifically we do not want to allow things
829 // like: short -> ushort -> uint, because this can create wrong results if
830 // the input short is negative!
831 //
832 return false;
833}
834
835
836// CastInst simplification
Chris Lattner260ab202002-04-18 17:39:14 +0000837//
Chris Lattner113f4f42002-06-25 16:13:24 +0000838Instruction *InstCombiner::visitCastInst(CastInst &CI) {
Chris Lattner48a44f72002-05-02 17:06:02 +0000839 // If the user is casting a value to the same type, eliminate this cast
840 // instruction...
Chris Lattnere6794492002-08-12 21:17:25 +0000841 if (CI.getType() == CI.getOperand(0)->getType())
842 return ReplaceInstUsesWith(CI, CI.getOperand(0));
Chris Lattner48a44f72002-05-02 17:06:02 +0000843
Chris Lattner48a44f72002-05-02 17:06:02 +0000844 // If casting the result of another cast instruction, try to eliminate this
845 // one!
846 //
Chris Lattner650b6da2002-08-02 20:00:25 +0000847 if (CastInst *CSrc = dyn_cast<CastInst>(CI.getOperand(0))) {
Chris Lattner48a44f72002-05-02 17:06:02 +0000848 if (isEliminableCastOfCast(CI, CSrc)) {
849 // This instruction now refers directly to the cast's src operand. This
850 // has a good chance of making CSrc dead.
Chris Lattner113f4f42002-06-25 16:13:24 +0000851 CI.setOperand(0, CSrc->getOperand(0));
852 return &CI;
Chris Lattner48a44f72002-05-02 17:06:02 +0000853 }
854
Chris Lattner650b6da2002-08-02 20:00:25 +0000855 // If this is an A->B->A cast, and we are dealing with integral types, try
856 // to convert this into a logical 'and' instruction.
857 //
858 if (CSrc->getOperand(0)->getType() == CI.getType() &&
Chris Lattnerb0b412e2002-09-03 01:08:28 +0000859 CI.getType()->isInteger() && CSrc->getType()->isInteger() &&
Chris Lattner650b6da2002-08-02 20:00:25 +0000860 CI.getType()->isUnsigned() && CSrc->getType()->isUnsigned() &&
861 CSrc->getType()->getPrimitiveSize() < CI.getType()->getPrimitiveSize()){
862 assert(CSrc->getType() != Type::ULongTy &&
863 "Cannot have type bigger than ulong!");
864 unsigned AndValue = (1U << CSrc->getType()->getPrimitiveSize()*8)-1;
865 Constant *AndOp = ConstantUInt::get(CI.getType(), AndValue);
866 return BinaryOperator::create(Instruction::And, CSrc->getOperand(0),
867 AndOp);
868 }
869 }
870
Chris Lattner260ab202002-04-18 17:39:14 +0000871 return 0;
Chris Lattnerca081252001-12-14 16:52:21 +0000872}
873
Chris Lattner48a44f72002-05-02 17:06:02 +0000874
Chris Lattnerbbbdd852002-05-06 18:06:38 +0000875// PHINode simplification
876//
Chris Lattner113f4f42002-06-25 16:13:24 +0000877Instruction *InstCombiner::visitPHINode(PHINode &PN) {
Chris Lattnerbbbdd852002-05-06 18:06:38 +0000878 // If the PHI node only has one incoming value, eliminate the PHI node...
Chris Lattnere6794492002-08-12 21:17:25 +0000879 if (PN.getNumIncomingValues() == 1)
880 return ReplaceInstUsesWith(PN, PN.getIncomingValue(0));
Chris Lattner9cd1e662002-08-20 15:35:35 +0000881
882 // Otherwise if all of the incoming values are the same for the PHI, replace
883 // the PHI node with the incoming value.
884 //
Chris Lattnerf6c0efa2002-08-22 20:22:01 +0000885 Value *InVal = 0;
886 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
887 if (PN.getIncomingValue(i) != &PN) // Not the PHI node itself...
888 if (InVal && PN.getIncomingValue(i) != InVal)
889 return 0; // Not the same, bail out.
890 else
891 InVal = PN.getIncomingValue(i);
892
893 // The only case that could cause InVal to be null is if we have a PHI node
894 // that only has entries for itself. In this case, there is no entry into the
895 // loop, so kill the PHI.
896 //
897 if (InVal == 0) InVal = Constant::getNullValue(PN.getType());
Chris Lattnerbbbdd852002-05-06 18:06:38 +0000898
Chris Lattner9cd1e662002-08-20 15:35:35 +0000899 // All of the incoming values are the same, replace the PHI node now.
900 return ReplaceInstUsesWith(PN, InVal);
Chris Lattnerbbbdd852002-05-06 18:06:38 +0000901}
902
Chris Lattner48a44f72002-05-02 17:06:02 +0000903
Chris Lattner113f4f42002-06-25 16:13:24 +0000904Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
Chris Lattnerae7a0d32002-08-02 19:29:35 +0000905 // Is it 'getelementptr %P, uint 0' or 'getelementptr %P'
Chris Lattner113f4f42002-06-25 16:13:24 +0000906 // If so, eliminate the noop.
Chris Lattnerae7a0d32002-08-02 19:29:35 +0000907 if ((GEP.getNumOperands() == 2 &&
Chris Lattner136dab72002-09-11 01:21:33 +0000908 GEP.getOperand(1) == Constant::getNullValue(Type::LongTy)) ||
Chris Lattnere6794492002-08-12 21:17:25 +0000909 GEP.getNumOperands() == 1)
910 return ReplaceInstUsesWith(GEP, GEP.getOperand(0));
Chris Lattner48a44f72002-05-02 17:06:02 +0000911
Chris Lattnerae7a0d32002-08-02 19:29:35 +0000912 // Combine Indices - If the source pointer to this getelementptr instruction
913 // is a getelementptr instruction, combine the indices of the two
914 // getelementptr instructions into a single instruction.
915 //
Chris Lattnerc59af1d2002-08-17 22:21:59 +0000916 if (GetElementPtrInst *Src = dyn_cast<GetElementPtrInst>(GEP.getOperand(0))) {
Chris Lattnerae7a0d32002-08-02 19:29:35 +0000917 std::vector<Value *> Indices;
Chris Lattnerca081252001-12-14 16:52:21 +0000918
Chris Lattnerae7a0d32002-08-02 19:29:35 +0000919 // Can we combine the two pointer arithmetics offsets?
Chris Lattner235af562003-03-05 22:33:14 +0000920 if (Src->getNumOperands() == 2 && isa<Constant>(Src->getOperand(1)) &&
921 isa<Constant>(GEP.getOperand(1))) {
922 // Replace: gep (gep %P, long C1), long C2, ...
923 // With: gep %P, long (C1+C2), ...
924 Value *Sum = *cast<Constant>(Src->getOperand(1)) +
Chris Lattnerae7a0d32002-08-02 19:29:35 +0000925 *cast<Constant>(GEP.getOperand(1));
Chris Lattner235af562003-03-05 22:33:14 +0000926 assert(Sum && "Constant folding of longs failed!?");
927 GEP.setOperand(0, Src->getOperand(0));
928 GEP.setOperand(1, Sum);
929 AddUsesToWorkList(*Src); // Reduce use count of Src
930 return &GEP;
931 } else if (Src->getNumOperands() == 2 && Src->use_size() == 1) {
932 // Replace: gep (gep %P, long B), long A, ...
933 // With: T = long A+B; gep %P, T, ...
934 //
935 Value *Sum = BinaryOperator::create(Instruction::Add, Src->getOperand(1),
936 GEP.getOperand(1),
937 Src->getName()+".sum", &GEP);
938 GEP.setOperand(0, Src->getOperand(0));
939 GEP.setOperand(1, Sum);
940 WorkList.push_back(cast<Instruction>(Sum));
941 return &GEP;
Chris Lattner5d606a02002-11-04 16:43:32 +0000942 } else if (*GEP.idx_begin() == Constant::getNullValue(Type::LongTy) &&
Chris Lattnera8339e32002-09-17 21:05:42 +0000943 Src->getNumOperands() != 1) {
Chris Lattnerae7a0d32002-08-02 19:29:35 +0000944 // Otherwise we can do the fold if the first index of the GEP is a zero
945 Indices.insert(Indices.end(), Src->idx_begin(), Src->idx_end());
946 Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
Chris Lattner5d606a02002-11-04 16:43:32 +0000947 } else if (Src->getOperand(Src->getNumOperands()-1) ==
948 Constant::getNullValue(Type::LongTy)) {
949 // If the src gep ends with a constant array index, merge this get into
950 // it, even if we have a non-zero array index.
951 Indices.insert(Indices.end(), Src->idx_begin(), Src->idx_end()-1);
952 Indices.insert(Indices.end(), GEP.idx_begin(), GEP.idx_end());
Chris Lattnerae7a0d32002-08-02 19:29:35 +0000953 }
954
955 if (!Indices.empty())
956 return new GetElementPtrInst(Src->getOperand(0), Indices, GEP.getName());
Chris Lattnerc59af1d2002-08-17 22:21:59 +0000957
958 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(GEP.getOperand(0))) {
959 // GEP of global variable. If all of the indices for this GEP are
960 // constants, we can promote this to a constexpr instead of an instruction.
961
962 // Scan for nonconstants...
963 std::vector<Constant*> Indices;
964 User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
965 for (; I != E && isa<Constant>(*I); ++I)
966 Indices.push_back(cast<Constant>(*I));
967
968 if (I == E) { // If they are all constants...
969 ConstantExpr *CE =
970 ConstantExpr::getGetElementPtr(ConstantPointerRef::get(GV), Indices);
971
972 // Replace all uses of the GEP with the new constexpr...
973 return ReplaceInstUsesWith(GEP, CE);
974 }
Chris Lattnerca081252001-12-14 16:52:21 +0000975 }
976
Chris Lattnerca081252001-12-14 16:52:21 +0000977 return 0;
978}
979
Chris Lattner1085bdf2002-11-04 16:18:53 +0000980Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
981 // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
982 if (AI.isArrayAllocation()) // Check C != 1
983 if (const ConstantUInt *C = dyn_cast<ConstantUInt>(AI.getArraySize())) {
984 const Type *NewTy = ArrayType::get(AI.getAllocatedType(), C->getValue());
Chris Lattnera2620ac2002-11-09 00:49:43 +0000985 AllocationInst *New = 0;
Chris Lattner1085bdf2002-11-04 16:18:53 +0000986
987 // Create and insert the replacement instruction...
988 if (isa<MallocInst>(AI))
989 New = new MallocInst(NewTy, 0, AI.getName(), &AI);
Chris Lattnera2620ac2002-11-09 00:49:43 +0000990 else {
991 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
Chris Lattner1085bdf2002-11-04 16:18:53 +0000992 New = new AllocaInst(NewTy, 0, AI.getName(), &AI);
Chris Lattnera2620ac2002-11-09 00:49:43 +0000993 }
Chris Lattner1085bdf2002-11-04 16:18:53 +0000994
995 // Scan to the end of the allocation instructions, to skip over a block of
996 // allocas if possible...
997 //
998 BasicBlock::iterator It = New;
999 while (isa<AllocationInst>(*It)) ++It;
1000
1001 // Now that I is pointing to the first non-allocation-inst in the block,
1002 // insert our getelementptr instruction...
1003 //
1004 std::vector<Value*> Idx(2, Constant::getNullValue(Type::LongTy));
1005 Value *V = new GetElementPtrInst(New, Idx, New->getName()+".sub", It);
1006
1007 // Now make everything use the getelementptr instead of the original
1008 // allocation.
1009 ReplaceInstUsesWith(AI, V);
1010 return &AI;
1011 }
1012 return 0;
1013}
1014
1015
Chris Lattnerca081252001-12-14 16:52:21 +00001016
Chris Lattner99f48c62002-09-02 04:59:56 +00001017void InstCombiner::removeFromWorkList(Instruction *I) {
1018 WorkList.erase(std::remove(WorkList.begin(), WorkList.end(), I),
1019 WorkList.end());
1020}
1021
Chris Lattner113f4f42002-06-25 16:13:24 +00001022bool InstCombiner::runOnFunction(Function &F) {
Chris Lattner260ab202002-04-18 17:39:14 +00001023 bool Changed = false;
Chris Lattnerca081252001-12-14 16:52:21 +00001024
Chris Lattner260ab202002-04-18 17:39:14 +00001025 WorkList.insert(WorkList.end(), inst_begin(F), inst_end(F));
Chris Lattnerca081252001-12-14 16:52:21 +00001026
1027 while (!WorkList.empty()) {
1028 Instruction *I = WorkList.back(); // Get an instruction from the worklist
1029 WorkList.pop_back();
1030
Misha Brukman632df282002-10-29 23:06:16 +00001031 // Check to see if we can DCE or ConstantPropagate the instruction...
Chris Lattner99f48c62002-09-02 04:59:56 +00001032 // Check to see if we can DIE the instruction...
1033 if (isInstructionTriviallyDead(I)) {
1034 // Add operands to the worklist...
1035 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
1036 if (Instruction *Op = dyn_cast<Instruction>(I->getOperand(i)))
1037 WorkList.push_back(Op);
1038
1039 ++NumDeadInst;
1040 BasicBlock::iterator BBI = I;
1041 if (dceInstruction(BBI)) {
1042 removeFromWorkList(I);
1043 continue;
1044 }
1045 }
1046
Misha Brukman632df282002-10-29 23:06:16 +00001047 // Instruction isn't dead, see if we can constant propagate it...
Chris Lattner99f48c62002-09-02 04:59:56 +00001048 if (Constant *C = ConstantFoldInstruction(I)) {
1049 // Add operands to the worklist...
1050 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
1051 if (Instruction *Op = dyn_cast<Instruction>(I->getOperand(i)))
1052 WorkList.push_back(Op);
Chris Lattnerc6509f42002-12-05 22:41:53 +00001053 ReplaceInstUsesWith(*I, C);
1054
Chris Lattner99f48c62002-09-02 04:59:56 +00001055 ++NumConstProp;
1056 BasicBlock::iterator BBI = I;
1057 if (dceInstruction(BBI)) {
1058 removeFromWorkList(I);
1059 continue;
1060 }
1061 }
1062
Chris Lattnerca081252001-12-14 16:52:21 +00001063 // Now that we have an instruction, try combining it to simplify it...
Chris Lattnerae7a0d32002-08-02 19:29:35 +00001064 if (Instruction *Result = visit(*I)) {
Chris Lattner0b18c1d2002-05-10 15:38:35 +00001065 ++NumCombined;
Chris Lattner260ab202002-04-18 17:39:14 +00001066 // Should we replace the old instruction with a new one?
Chris Lattner053c0932002-05-14 15:24:07 +00001067 if (Result != I) {
1068 // Instructions can end up on the worklist more than once. Make sure
1069 // we do not process an instruction that has been deleted.
Chris Lattner99f48c62002-09-02 04:59:56 +00001070 removeFromWorkList(I);
Chris Lattner260ab202002-04-18 17:39:14 +00001071 ReplaceInstWithInst(I, Result);
Chris Lattner113f4f42002-06-25 16:13:24 +00001072 } else {
Chris Lattnerae7a0d32002-08-02 19:29:35 +00001073 BasicBlock::iterator II = I;
1074
1075 // If the instruction was modified, it's possible that it is now dead.
1076 // if so, remove it.
1077 if (dceInstruction(II)) {
1078 // Instructions may end up in the worklist more than once. Erase them
1079 // all.
Chris Lattner99f48c62002-09-02 04:59:56 +00001080 removeFromWorkList(I);
Chris Lattnerae7a0d32002-08-02 19:29:35 +00001081 Result = 0;
1082 }
Chris Lattner053c0932002-05-14 15:24:07 +00001083 }
Chris Lattner260ab202002-04-18 17:39:14 +00001084
Chris Lattnerae7a0d32002-08-02 19:29:35 +00001085 if (Result) {
1086 WorkList.push_back(Result);
1087 AddUsesToWorkList(*Result);
1088 }
Chris Lattner260ab202002-04-18 17:39:14 +00001089 Changed = true;
Chris Lattnerca081252001-12-14 16:52:21 +00001090 }
1091 }
1092
Chris Lattner260ab202002-04-18 17:39:14 +00001093 return Changed;
Chris Lattner04805fa2002-02-26 21:46:54 +00001094}
1095
1096Pass *createInstructionCombiningPass() {
Chris Lattner260ab202002-04-18 17:39:14 +00001097 return new InstCombiner();
Chris Lattner04805fa2002-02-26 21:46:54 +00001098}