blob: f66448257b39e4a8750b1cede10f8a3cb1c1d179 [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 Lattner9fa53de2002-05-06 16:49:18 +0000157// dyn_castNegInst - Given a 'sub' instruction, return the RHS of the
158// instruction if the LHS is a constant zero (which is the 'negate' form).
159//
160static inline Value *dyn_castNegInst(Value *V) {
Chris Lattner3082c5a2003-02-18 19:28:33 +0000161 return BinaryOperator::isNeg(V) ?
162 BinaryOperator::getNegArgument(cast<BinaryOperator>(V)) : 0;
Chris Lattner9fa53de2002-05-06 16:49:18 +0000163}
164
Chris Lattner31ae8632002-08-14 17:51:49 +0000165static inline Value *dyn_castNotInst(Value *V) {
Chris Lattner3082c5a2003-02-18 19:28:33 +0000166 return BinaryOperator::isNot(V) ?
167 BinaryOperator::getNotArgument(cast<BinaryOperator>(V)) : 0;
168}
Chris Lattner31ae8632002-08-14 17:51:49 +0000169
Chris Lattner3082c5a2003-02-18 19:28:33 +0000170
171// Log2 - Calculate the log base 2 for the specified value if it is exactly a
172// power of 2.
173static unsigned Log2(uint64_t Val) {
174 assert(Val > 1 && "Values 0 and 1 should be handled elsewhere!");
175 unsigned Count = 0;
176 while (Val != 1) {
177 if (Val & 1) return 0; // Multiple bits set?
178 Val >>= 1;
179 ++Count;
180 }
181 return Count;
Chris Lattner31ae8632002-08-14 17:51:49 +0000182}
183
Chris Lattner57c8d992003-02-18 19:57:07 +0000184static inline Value *dyn_castFoldableMul(Value *V) {
185 if (V->use_size() == 1 && V->getType()->isInteger())
186 if (Instruction *I = dyn_cast<Instruction>(V))
187 if (I->getOpcode() == Instruction::Mul)
188 if (isa<Constant>(I->getOperand(1)))
189 return I->getOperand(0);
190 return 0;
191}
192
193
Chris Lattner113f4f42002-06-25 16:13:24 +0000194Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000195 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +0000196 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
Chris Lattner9fa53de2002-05-06 16:49:18 +0000197
198 // Eliminate 'add int %X, 0'
Chris Lattnere6794492002-08-12 21:17:25 +0000199 if (RHS == Constant::getNullValue(I.getType()))
200 return ReplaceInstUsesWith(I, LHS);
Chris Lattner9fa53de2002-05-06 16:49:18 +0000201
Chris Lattner147e9752002-05-08 22:46:53 +0000202 // -A + B --> B - A
Chris Lattner9fa53de2002-05-06 16:49:18 +0000203 if (Value *V = dyn_castNegInst(LHS))
Chris Lattner147e9752002-05-08 22:46:53 +0000204 return BinaryOperator::create(Instruction::Sub, RHS, V);
Chris Lattner9fa53de2002-05-06 16:49:18 +0000205
206 // A + -B --> A - B
207 if (Value *V = dyn_castNegInst(RHS))
Chris Lattner147e9752002-05-08 22:46:53 +0000208 return BinaryOperator::create(Instruction::Sub, LHS, V);
Chris Lattner260ab202002-04-18 17:39:14 +0000209
Chris Lattner57c8d992003-02-18 19:57:07 +0000210 // X*C + X --> X * (C+1)
211 if (dyn_castFoldableMul(LHS) == RHS) {
212 Constant *CP1 = *cast<Constant>(cast<Instruction>(LHS)->getOperand(1)) +
213 *ConstantInt::get(I.getType(), 1);
214 assert(CP1 && "Couldn't constant fold C + 1?");
215 return BinaryOperator::create(Instruction::Mul, RHS, CP1);
216 }
217
218 // X + X*C --> X * (C+1)
219 if (dyn_castFoldableMul(RHS) == LHS) {
220 Constant *CP1 = *cast<Constant>(cast<Instruction>(RHS)->getOperand(1)) +
221 *ConstantInt::get(I.getType(), 1);
222 assert(CP1 && "Couldn't constant fold C + 1?");
223 return BinaryOperator::create(Instruction::Mul, LHS, CP1);
224 }
225
Chris Lattner113f4f42002-06-25 16:13:24 +0000226 return Changed ? &I : 0;
Chris Lattner260ab202002-04-18 17:39:14 +0000227}
228
Chris Lattner113f4f42002-06-25 16:13:24 +0000229Instruction *InstCombiner::visitSub(BinaryOperator &I) {
Chris Lattner113f4f42002-06-25 16:13:24 +0000230 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000231
Chris Lattnere6794492002-08-12 21:17:25 +0000232 if (Op0 == Op1) // sub X, X -> 0
233 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner260ab202002-04-18 17:39:14 +0000234
235 // If this is a subtract instruction with a constant RHS, convert it to an add
236 // instruction of a negative constant
237 //
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000238 if (Constant *Op2 = dyn_cast<Constant>(Op1))
Chris Lattner113f4f42002-06-25 16:13:24 +0000239 if (Constant *RHS = *Constant::getNullValue(I.getType()) - *Op2) // 0 - RHS
240 return BinaryOperator::create(Instruction::Add, Op0, RHS, I.getName());
Chris Lattner260ab202002-04-18 17:39:14 +0000241
Chris Lattnere6794492002-08-12 21:17:25 +0000242 // If this is a 'B = x-(-A)', change to B = x+A...
Chris Lattner147e9752002-05-08 22:46:53 +0000243 if (Value *V = dyn_castNegInst(Op1))
244 return BinaryOperator::create(Instruction::Add, Op0, V);
Chris Lattner9fa53de2002-05-06 16:49:18 +0000245
Chris Lattner3082c5a2003-02-18 19:28:33 +0000246 // Replace (-1 - A) with (~A)...
247 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0))
248 if (C->isAllOnesValue())
249 return BinaryOperator::createNot(Op1);
Chris Lattnerad3c4952002-05-09 01:29:19 +0000250
Chris Lattner3082c5a2003-02-18 19:28:33 +0000251 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1))
252 if (Op1I->use_size() == 1) {
253 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
254 // is not used by anyone else...
255 //
256 if (Op1I->getOpcode() == Instruction::Sub) {
257 // Swap the two operands of the subexpr...
258 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
259 Op1I->setOperand(0, IIOp1);
260 Op1I->setOperand(1, IIOp0);
261
262 // Create the new top level add instruction...
263 return BinaryOperator::create(Instruction::Add, Op0, Op1);
264 }
265
266 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
267 //
268 if (Op1I->getOpcode() == Instruction::And &&
269 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
270 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
271
272 Instruction *NewNot = BinaryOperator::createNot(OtherOp, "B.not", &I);
273 return BinaryOperator::create(Instruction::And, Op0, NewNot);
274 }
Chris Lattner57c8d992003-02-18 19:57:07 +0000275
276 // X - X*C --> X * (1-C)
277 if (dyn_castFoldableMul(Op1I) == Op0) {
278 Constant *CP1 = *ConstantInt::get(I.getType(), 1) -
279 *cast<Constant>(cast<Instruction>(Op1)->getOperand(1));
280 assert(CP1 && "Couldn't constant fold 1-C?");
281 return BinaryOperator::create(Instruction::Mul, Op0, CP1);
282 }
Chris Lattnerad3c4952002-05-09 01:29:19 +0000283 }
Chris Lattner3082c5a2003-02-18 19:28:33 +0000284
Chris Lattner57c8d992003-02-18 19:57:07 +0000285 // X*C - X --> X * (C-1)
286 if (dyn_castFoldableMul(Op0) == Op1) {
287 Constant *CP1 = *cast<Constant>(cast<Instruction>(Op0)->getOperand(1)) -
288 *ConstantInt::get(I.getType(), 1);
289 assert(CP1 && "Couldn't constant fold C - 1?");
290 return BinaryOperator::create(Instruction::Mul, Op1, CP1);
291 }
292
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000293 return 0;
Chris Lattner260ab202002-04-18 17:39:14 +0000294}
295
Chris Lattner113f4f42002-06-25 16:13:24 +0000296Instruction *InstCombiner::visitMul(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000297 bool Changed = SimplifyCommutative(I);
Chris Lattner3082c5a2003-02-18 19:28:33 +0000298 Value *Op0 = I.getOperand(0);
Chris Lattner260ab202002-04-18 17:39:14 +0000299
Chris Lattnere6794492002-08-12 21:17:25 +0000300 // Simplify mul instructions with a constant RHS...
Chris Lattner3082c5a2003-02-18 19:28:33 +0000301 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
302 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
303 const Type *Ty = CI->getType();
304 uint64_t Val = Ty->isSigned() ?
305 (uint64_t)cast<ConstantSInt>(CI)->getValue() :
306 cast<ConstantUInt>(CI)->getValue();
307 switch (Val) {
308 case 0:
309 return ReplaceInstUsesWith(I, Op1); // Eliminate 'mul double %X, 0'
310 case 1:
311 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul int %X, 1'
312 case 2: // Convert 'mul int %X, 2' to 'add int %X, %X'
313 return BinaryOperator::create(Instruction::Add, Op0, Op0, I.getName());
314 }
Chris Lattner31ba1292002-04-29 22:24:47 +0000315
Chris Lattner3082c5a2003-02-18 19:28:33 +0000316 if (uint64_t C = Log2(Val)) // Replace X*(2^C) with X << C
317 return new ShiftInst(Instruction::Shl, Op0,
318 ConstantUInt::get(Type::UByteTy, C));
319 } else {
320 ConstantFP *Op1F = cast<ConstantFP>(Op1);
321 if (Op1F->isNullValue())
322 return ReplaceInstUsesWith(I, Op1);
Chris Lattner31ba1292002-04-29 22:24:47 +0000323
Chris Lattner3082c5a2003-02-18 19:28:33 +0000324 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
325 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
326 if (Op1F->getValue() == 1.0)
327 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0'
328 }
Chris Lattner260ab202002-04-18 17:39:14 +0000329 }
330
Chris Lattner113f4f42002-06-25 16:13:24 +0000331 return Changed ? &I : 0;
Chris Lattner260ab202002-04-18 17:39:14 +0000332}
333
Chris Lattner113f4f42002-06-25 16:13:24 +0000334Instruction *InstCombiner::visitDiv(BinaryOperator &I) {
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000335 // div X, 1 == X
Chris Lattner3082c5a2003-02-18 19:28:33 +0000336 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I.getOperand(1))) {
Chris Lattnere6794492002-08-12 21:17:25 +0000337 if (RHS->equalsInt(1))
338 return ReplaceInstUsesWith(I, I.getOperand(0));
Chris Lattner3082c5a2003-02-18 19:28:33 +0000339
340 // Check to see if this is an unsigned division with an exact power of 2,
341 // if so, convert to a right shift.
342 if (ConstantUInt *C = dyn_cast<ConstantUInt>(RHS))
343 if (uint64_t Val = C->getValue()) // Don't break X / 0
344 if (uint64_t C = Log2(Val))
345 return new ShiftInst(Instruction::Shr, I.getOperand(0),
346 ConstantUInt::get(Type::UByteTy, C));
347 }
348
349 // 0 / X == 0, we don't need to preserve faults!
350 if (ConstantInt *LHS = dyn_cast<ConstantInt>(I.getOperand(0)))
351 if (LHS->equalsInt(0))
352 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
353
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000354 return 0;
355}
356
357
Chris Lattner113f4f42002-06-25 16:13:24 +0000358Instruction *InstCombiner::visitRem(BinaryOperator &I) {
Chris Lattner3082c5a2003-02-18 19:28:33 +0000359 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I.getOperand(1))) {
360 if (RHS->equalsInt(1)) // X % 1 == 0
361 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
362
363 // Check to see if this is an unsigned remainder with an exact power of 2,
364 // if so, convert to a bitwise and.
365 if (ConstantUInt *C = dyn_cast<ConstantUInt>(RHS))
366 if (uint64_t Val = C->getValue()) // Don't break X % 0 (divide by zero)
367 if (Log2(Val))
368 return BinaryOperator::create(Instruction::And, I.getOperand(0),
369 ConstantUInt::get(I.getType(), Val-1));
370 }
371
372 // 0 % X == 0, we don't need to preserve faults!
373 if (ConstantInt *LHS = dyn_cast<ConstantInt>(I.getOperand(0)))
374 if (LHS->equalsInt(0))
Chris Lattnere6794492002-08-12 21:17:25 +0000375 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
376
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000377 return 0;
378}
379
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000380// isMaxValueMinusOne - return true if this is Max-1
Chris Lattnere6794492002-08-12 21:17:25 +0000381static bool isMaxValueMinusOne(const ConstantInt *C) {
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000382 if (const ConstantUInt *CU = dyn_cast<ConstantUInt>(C)) {
383 // Calculate -1 casted to the right type...
384 unsigned TypeBits = C->getType()->getPrimitiveSize()*8;
385 uint64_t Val = ~0ULL; // All ones
386 Val >>= 64-TypeBits; // Shift out unwanted 1 bits...
387 return CU->getValue() == Val-1;
388 }
389
390 const ConstantSInt *CS = cast<ConstantSInt>(C);
391
392 // Calculate 0111111111..11111
393 unsigned TypeBits = C->getType()->getPrimitiveSize()*8;
394 int64_t Val = INT64_MAX; // All ones
395 Val >>= 64-TypeBits; // Shift out unwanted 1 bits...
396 return CS->getValue() == Val-1;
397}
398
399// isMinValuePlusOne - return true if this is Min+1
Chris Lattnere6794492002-08-12 21:17:25 +0000400static bool isMinValuePlusOne(const ConstantInt *C) {
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000401 if (const ConstantUInt *CU = dyn_cast<ConstantUInt>(C))
402 return CU->getValue() == 1;
403
404 const ConstantSInt *CS = cast<ConstantSInt>(C);
405
406 // Calculate 1111111111000000000000
407 unsigned TypeBits = C->getType()->getPrimitiveSize()*8;
408 int64_t Val = -1; // All ones
409 Val <<= TypeBits-1; // Shift over to the right spot
410 return CS->getValue() == Val+1;
411}
412
413
Chris Lattner113f4f42002-06-25 16:13:24 +0000414Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000415 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +0000416 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000417
418 // and X, X = X and X, 0 == 0
Chris Lattnere6794492002-08-12 21:17:25 +0000419 if (Op0 == Op1 || Op1 == Constant::getNullValue(I.getType()))
420 return ReplaceInstUsesWith(I, Op1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000421
422 // and X, -1 == X
Chris Lattner83282632002-08-13 17:50:24 +0000423 if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1))
Chris Lattnere6794492002-08-12 21:17:25 +0000424 if (RHS->isAllOnesValue())
425 return ReplaceInstUsesWith(I, Op0);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000426
Chris Lattner3082c5a2003-02-18 19:28:33 +0000427 Value *Op0NotVal = dyn_castNotInst(Op0);
428 Value *Op1NotVal = dyn_castNotInst(Op1);
429
430 // (~A & ~B) == (~(A | B)) - Demorgan's Law
431 if (Op0->use_size() == 1 && Op1->use_size() == 1 && Op0NotVal && Op1NotVal) {
432 Instruction *Or = BinaryOperator::create(Instruction::Or, Op0NotVal,
433 Op1NotVal,I.getName()+".demorgan",
434 &I);
435 return BinaryOperator::createNot(Or);
436 }
437
438 if (Op0NotVal == Op1 || Op1NotVal == Op0) // A & ~A == ~A & A == 0
439 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner65217ff2002-08-23 18:32:43 +0000440
Chris Lattner113f4f42002-06-25 16:13:24 +0000441 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000442}
443
444
445
Chris Lattner113f4f42002-06-25 16:13:24 +0000446Instruction *InstCombiner::visitOr(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000447 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +0000448 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000449
450 // or X, X = X or X, 0 == X
Chris Lattnere6794492002-08-12 21:17:25 +0000451 if (Op0 == Op1 || Op1 == Constant::getNullValue(I.getType()))
452 return ReplaceInstUsesWith(I, Op0);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000453
454 // or X, -1 == -1
Chris Lattner83282632002-08-13 17:50:24 +0000455 if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1))
Chris Lattnere6794492002-08-12 21:17:25 +0000456 if (RHS->isAllOnesValue())
457 return ReplaceInstUsesWith(I, Op1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000458
Chris Lattner3082c5a2003-02-18 19:28:33 +0000459 if (Value *X = dyn_castNotInst(Op0)) // ~A | A == -1
460 if (X == Op1)
461 return ReplaceInstUsesWith(I,
462 ConstantIntegral::getAllOnesValue(I.getType()));
463
464 if (Value *X = dyn_castNotInst(Op1)) // A | ~A == -1
465 if (X == Op0)
466 return ReplaceInstUsesWith(I,
467 ConstantIntegral::getAllOnesValue(I.getType()));
468
Chris Lattner113f4f42002-06-25 16:13:24 +0000469 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000470}
471
472
473
Chris Lattner113f4f42002-06-25 16:13:24 +0000474Instruction *InstCombiner::visitXor(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000475 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +0000476 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000477
478 // xor X, X = 0
Chris Lattnere6794492002-08-12 21:17:25 +0000479 if (Op0 == Op1)
480 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000481
Chris Lattner83282632002-08-13 17:50:24 +0000482 if (ConstantIntegral *Op1C = dyn_cast<ConstantIntegral>(Op1)) {
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000483 // xor X, 0 == X
Chris Lattnere6794492002-08-12 21:17:25 +0000484 if (Op1C->isNullValue())
485 return ReplaceInstUsesWith(I, Op0);
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000486
Chris Lattnerb8d6e402002-08-20 18:24:26 +0000487 // Is this a "NOT" instruction?
488 if (Op1C->isAllOnesValue()) {
489 // xor (xor X, -1), -1 = not (not X) = X
Chris Lattner31ae8632002-08-14 17:51:49 +0000490 if (Value *X = dyn_castNotInst(Op0))
491 return ReplaceInstUsesWith(I, X);
Chris Lattnerb8d6e402002-08-20 18:24:26 +0000492
493 // xor (setcc A, B), true = not (setcc A, B) = setncc A, B
494 if (SetCondInst *SCI = dyn_cast<SetCondInst>(Op0))
495 if (SCI->use_size() == 1)
496 return new SetCondInst(SCI->getInverseCondition(),
497 SCI->getOperand(0), SCI->getOperand(1));
498 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000499 }
500
Chris Lattner3082c5a2003-02-18 19:28:33 +0000501 if (Value *X = dyn_castNotInst(Op0)) // ~A ^ A == -1
502 if (X == Op1)
503 return ReplaceInstUsesWith(I,
504 ConstantIntegral::getAllOnesValue(I.getType()));
505
506 if (Value *X = dyn_castNotInst(Op1)) // A ^ ~A == -1
507 if (X == Op0)
508 return ReplaceInstUsesWith(I,
509 ConstantIntegral::getAllOnesValue(I.getType()));
510
Chris Lattner1bbb7b62003-03-10 18:24:17 +0000511
512
513 if (Instruction *Op1I = dyn_cast<Instruction>(Op1))
514 if (Op1I->getOpcode() == Instruction::Or)
515 if (Op1I->getOperand(0) == Op0) { // B^(B|A) == (A|B)^B
516 cast<BinaryOperator>(Op1I)->swapOperands();
517 I.swapOperands();
518 std::swap(Op0, Op1);
519 } else if (Op1I->getOperand(1) == Op0) { // B^(A|B) == (A|B)^B
520 I.swapOperands();
521 std::swap(Op0, Op1);
522 }
523
524 if (Instruction *Op0I = dyn_cast<Instruction>(Op0))
525 if (Op0I->getOpcode() == Instruction::Or && Op0I->use_size() == 1) {
526 if (Op0I->getOperand(0) == Op1) // (B|A)^B == (A|B)^B
527 cast<BinaryOperator>(Op0I)->swapOperands();
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000528 if (Op0I->getOperand(1) == Op1) { // (A|B)^B == A & ~B
Chris Lattner1bbb7b62003-03-10 18:24:17 +0000529 Value *NotB = BinaryOperator::createNot(Op1, Op1->getName()+".not", &I);
530 WorkList.push_back(cast<Instruction>(NotB));
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000531 return BinaryOperator::create(Instruction::And, Op0I->getOperand(0),
532 NotB);
Chris Lattner1bbb7b62003-03-10 18:24:17 +0000533 }
534 }
535
Chris Lattner113f4f42002-06-25 16:13:24 +0000536 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000537}
538
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000539// AddOne, SubOne - Add or subtract a constant one from an integer constant...
540static Constant *AddOne(ConstantInt *C) {
541 Constant *Result = *C + *ConstantInt::get(C->getType(), 1);
542 assert(Result && "Constant folding integer addition failed!");
543 return Result;
544}
545static Constant *SubOne(ConstantInt *C) {
546 Constant *Result = *C - *ConstantInt::get(C->getType(), 1);
547 assert(Result && "Constant folding integer addition failed!");
548 return Result;
549}
550
Chris Lattner1fc23f32002-05-09 20:11:54 +0000551// isTrueWhenEqual - Return true if the specified setcondinst instruction is
552// true when both operands are equal...
553//
Chris Lattner113f4f42002-06-25 16:13:24 +0000554static bool isTrueWhenEqual(Instruction &I) {
555 return I.getOpcode() == Instruction::SetEQ ||
556 I.getOpcode() == Instruction::SetGE ||
557 I.getOpcode() == Instruction::SetLE;
Chris Lattner1fc23f32002-05-09 20:11:54 +0000558}
559
Chris Lattner113f4f42002-06-25 16:13:24 +0000560Instruction *InstCombiner::visitSetCondInst(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000561 bool Changed = SimplifyCommutative(I);
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000562 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
563 const Type *Ty = Op0->getType();
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000564
565 // setcc X, X
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000566 if (Op0 == Op1)
567 return ReplaceInstUsesWith(I, ConstantBool::get(isTrueWhenEqual(I)));
Chris Lattner1fc23f32002-05-09 20:11:54 +0000568
569 // setcc <global*>, 0 - Global value addresses are never null!
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000570 if (isa<GlobalValue>(Op0) && isa<ConstantPointerNull>(Op1))
571 return ReplaceInstUsesWith(I, ConstantBool::get(!isTrueWhenEqual(I)));
572
573 // setcc's with boolean values can always be turned into bitwise operations
574 if (Ty == Type::BoolTy) {
575 // If this is <, >, or !=, we can change this into a simple xor instruction
576 if (!isTrueWhenEqual(I))
577 return BinaryOperator::create(Instruction::Xor, Op0, Op1, I.getName());
578
579 // Otherwise we need to make a temporary intermediate instruction and insert
580 // it into the instruction stream. This is what we are after:
581 //
582 // seteq bool %A, %B -> ~(A^B)
583 // setle bool %A, %B -> ~A | B
584 // setge bool %A, %B -> A | ~B
585 //
586 if (I.getOpcode() == Instruction::SetEQ) { // seteq case
587 Instruction *Xor = BinaryOperator::create(Instruction::Xor, Op0, Op1,
588 I.getName()+"tmp");
589 InsertNewInstBefore(Xor, I);
Chris Lattner31ae8632002-08-14 17:51:49 +0000590 return BinaryOperator::createNot(Xor, I.getName());
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000591 }
592
593 // Handle the setXe cases...
594 assert(I.getOpcode() == Instruction::SetGE ||
595 I.getOpcode() == Instruction::SetLE);
596
597 if (I.getOpcode() == Instruction::SetGE)
598 std::swap(Op0, Op1); // Change setge -> setle
599
600 // Now we just have the SetLE case.
Chris Lattner31ae8632002-08-14 17:51:49 +0000601 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000602 InsertNewInstBefore(Not, I);
603 return BinaryOperator::create(Instruction::Or, Not, Op1, I.getName());
604 }
605
606 // Check to see if we are doing one of many comparisons against constant
607 // integers at the end of their ranges...
608 //
609 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
610 // Check to see if we are comparing against the minimum or maximum value...
Chris Lattnere6794492002-08-12 21:17:25 +0000611 if (CI->isMinValue()) {
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000612 if (I.getOpcode() == Instruction::SetLT) // A < MIN -> FALSE
613 return ReplaceInstUsesWith(I, ConstantBool::False);
614 if (I.getOpcode() == Instruction::SetGE) // A >= MIN -> TRUE
615 return ReplaceInstUsesWith(I, ConstantBool::True);
616 if (I.getOpcode() == Instruction::SetLE) // A <= MIN -> A == MIN
617 return BinaryOperator::create(Instruction::SetEQ, Op0,Op1, I.getName());
618 if (I.getOpcode() == Instruction::SetGT) // A > MIN -> A != MIN
619 return BinaryOperator::create(Instruction::SetNE, Op0,Op1, I.getName());
620
Chris Lattnere6794492002-08-12 21:17:25 +0000621 } else if (CI->isMaxValue()) {
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000622 if (I.getOpcode() == Instruction::SetGT) // A > MAX -> FALSE
623 return ReplaceInstUsesWith(I, ConstantBool::False);
624 if (I.getOpcode() == Instruction::SetLE) // A <= MAX -> TRUE
625 return ReplaceInstUsesWith(I, ConstantBool::True);
626 if (I.getOpcode() == Instruction::SetGE) // A >= MAX -> A == MAX
627 return BinaryOperator::create(Instruction::SetEQ, Op0,Op1, I.getName());
628 if (I.getOpcode() == Instruction::SetLT) // A < MAX -> A != MAX
629 return BinaryOperator::create(Instruction::SetNE, Op0,Op1, I.getName());
630
631 // Comparing against a value really close to min or max?
632 } else if (isMinValuePlusOne(CI)) {
633 if (I.getOpcode() == Instruction::SetLT) // A < MIN+1 -> A == MIN
634 return BinaryOperator::create(Instruction::SetEQ, Op0,
635 SubOne(CI), I.getName());
636 if (I.getOpcode() == Instruction::SetGE) // A >= MIN-1 -> A != MIN
637 return BinaryOperator::create(Instruction::SetNE, Op0,
638 SubOne(CI), I.getName());
639
640 } else if (isMaxValueMinusOne(CI)) {
641 if (I.getOpcode() == Instruction::SetGT) // A > MAX-1 -> A == MAX
642 return BinaryOperator::create(Instruction::SetEQ, Op0,
643 AddOne(CI), I.getName());
644 if (I.getOpcode() == Instruction::SetLE) // A <= MAX-1 -> A != MAX
645 return BinaryOperator::create(Instruction::SetNE, Op0,
646 AddOne(CI), I.getName());
647 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000648 }
649
Chris Lattner113f4f42002-06-25 16:13:24 +0000650 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000651}
652
653
654
Chris Lattnere8d6c602003-03-10 19:16:08 +0000655Instruction *InstCombiner::visitShiftInst(ShiftInst &I) {
Chris Lattner113f4f42002-06-25 16:13:24 +0000656 assert(I.getOperand(1)->getType() == Type::UByteTy);
657 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000658
659 // shl X, 0 == X and shr X, 0 == X
660 // shl 0, X == 0 and shr 0, X == 0
661 if (Op1 == Constant::getNullValue(Type::UByteTy) ||
Chris Lattnere6794492002-08-12 21:17:25 +0000662 Op0 == Constant::getNullValue(Op0->getType()))
663 return ReplaceInstUsesWith(I, Op0);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000664
Chris Lattnere8d6c602003-03-10 19:16:08 +0000665 // If this is a shift of a shift, see if we can fold the two together...
666 if (ShiftInst *Op0SI = dyn_cast<ShiftInst>(Op0)) {
667 if (isa<Constant>(Op1) && isa<Constant>(Op0SI->getOperand(1))) {
668 ConstantUInt *ShiftAmt1C = cast<ConstantUInt>(Op0SI->getOperand(1));
669 unsigned ShiftAmt1 = ShiftAmt1C->getValue();
670 unsigned ShiftAmt2 = cast<ConstantUInt>(Op1)->getValue();
671
672 // Check for (A << c1) << c2 and (A >> c1) >> c2
673 if (I.getOpcode() == Op0SI->getOpcode()) {
674 unsigned Amt = ShiftAmt1+ShiftAmt2; // Fold into one big shift...
675 return new ShiftInst(I.getOpcode(), Op0SI->getOperand(0),
676 ConstantUInt::get(Type::UByteTy, Amt));
677 }
678
679 if (I.getType()->isUnsigned()) { // Check for (A << c1) >> c2 or visaversa
680 // Calculate bitmask for what gets shifted off the edge...
681 Constant *C = ConstantIntegral::getAllOnesValue(I.getType());
682 if (I.getOpcode() == Instruction::Shr)
683 C = *C >> *ShiftAmt1C;
684 else
685 C = *C << *ShiftAmt1C;
686 assert(C && "Couldn't constant fold shift expression?");
687
688 Instruction *Mask =
689 BinaryOperator::create(Instruction::And, Op0SI->getOperand(0),
690 C, Op0SI->getOperand(0)->getName()+".mask",&I);
691 WorkList.push_back(Mask);
692
693 // Figure out what flavor of shift we should use...
694 if (ShiftAmt1 == ShiftAmt2)
695 return ReplaceInstUsesWith(I, Mask); // (A << c) >> c === A & c2
696 else if (ShiftAmt1 < ShiftAmt2) {
697 return new ShiftInst(I.getOpcode(), Mask,
698 ConstantUInt::get(Type::UByteTy, ShiftAmt2-ShiftAmt1));
699 } else {
700 return new ShiftInst(Op0SI->getOpcode(), Mask,
701 ConstantUInt::get(Type::UByteTy, ShiftAmt1-ShiftAmt2));
702 }
703 }
704 }
705 }
706
Chris Lattnere6794492002-08-12 21:17:25 +0000707 // shl uint X, 32 = 0 and shr ubyte Y, 9 = 0, ... just don't eliminate shr of
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000708 // a signed value.
709 //
710 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(Op1)) {
Chris Lattnere8d6c602003-03-10 19:16:08 +0000711 unsigned TypeBits = Op0->getType()->getPrimitiveSize()*8;
712 if (CUI->getValue() >= TypeBits &&
713 (!Op0->getType()->isSigned() || I.getOpcode() == Instruction::Shl))
714 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
Chris Lattner55f3d942002-09-10 23:04:09 +0000715
716 // Check to see if we are shifting left by 1. If so, turn it into an add
717 // instruction.
718 if (I.getOpcode() == Instruction::Shl && CUI->equalsInt(1))
Chris Lattner3082c5a2003-02-18 19:28:33 +0000719 // Convert 'shl int %X, 1' to 'add int %X, %X'
Chris Lattner55f3d942002-09-10 23:04:09 +0000720 return BinaryOperator::create(Instruction::Add, Op0, Op0, I.getName());
721
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000722 }
Chris Lattner2e0fb392002-10-08 16:16:40 +0000723
724 // shr int -1, X = -1 (for any arithmetic shift rights of ~0)
725 if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(Op0))
726 if (I.getOpcode() == Instruction::Shr && CSI->isAllOnesValue())
727 return ReplaceInstUsesWith(I, CSI);
728
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000729 return 0;
730}
731
732
Chris Lattner48a44f72002-05-02 17:06:02 +0000733// isEliminableCastOfCast - Return true if it is valid to eliminate the CI
734// instruction.
735//
Chris Lattner113f4f42002-06-25 16:13:24 +0000736static inline bool isEliminableCastOfCast(const CastInst &CI,
Chris Lattner48a44f72002-05-02 17:06:02 +0000737 const CastInst *CSrc) {
Chris Lattner113f4f42002-06-25 16:13:24 +0000738 assert(CI.getOperand(0) == CSrc);
Chris Lattner48a44f72002-05-02 17:06:02 +0000739 const Type *SrcTy = CSrc->getOperand(0)->getType();
740 const Type *MidTy = CSrc->getType();
Chris Lattner113f4f42002-06-25 16:13:24 +0000741 const Type *DstTy = CI.getType();
Chris Lattner48a44f72002-05-02 17:06:02 +0000742
Chris Lattner650b6da2002-08-02 20:00:25 +0000743 // It is legal to eliminate the instruction if casting A->B->A if the sizes
744 // are identical and the bits don't get reinterpreted (for example
Chris Lattner0bb75912002-08-14 23:21:10 +0000745 // int->float->int would not be allowed)
Chris Lattner650b6da2002-08-02 20:00:25 +0000746 if (SrcTy == DstTy && SrcTy->isLosslesslyConvertableTo(MidTy))
747 return true;
Chris Lattner48a44f72002-05-02 17:06:02 +0000748
749 // Allow free casting and conversion of sizes as long as the sign doesn't
750 // change...
Chris Lattnerb0b412e2002-09-03 01:08:28 +0000751 if (SrcTy->isIntegral() && MidTy->isIntegral() && DstTy->isIntegral()) {
Chris Lattner650b6da2002-08-02 20:00:25 +0000752 unsigned SrcSize = SrcTy->getPrimitiveSize();
753 unsigned MidSize = MidTy->getPrimitiveSize();
754 unsigned DstSize = DstTy->getPrimitiveSize();
Chris Lattner650b6da2002-08-02 20:00:25 +0000755
Chris Lattner3732aca2002-08-15 16:15:25 +0000756 // Cases where we are monotonically decreasing the size of the type are
757 // always ok, regardless of what sign changes are going on.
758 //
Chris Lattner0bb75912002-08-14 23:21:10 +0000759 if (SrcSize >= MidSize && MidSize >= DstSize)
Chris Lattner650b6da2002-08-02 20:00:25 +0000760 return true;
Chris Lattner3732aca2002-08-15 16:15:25 +0000761
Chris Lattner555518c2002-09-23 23:39:43 +0000762 // Cases where the source and destination type are the same, but the middle
763 // type is bigger are noops.
764 //
765 if (SrcSize == DstSize && MidSize > SrcSize)
766 return true;
767
Chris Lattner3732aca2002-08-15 16:15:25 +0000768 // If we are monotonically growing, things are more complex.
769 //
770 if (SrcSize <= MidSize && MidSize <= DstSize) {
771 // We have eight combinations of signedness to worry about. Here's the
772 // table:
773 static const int SignTable[8] = {
774 // CODE, SrcSigned, MidSigned, DstSigned, Comment
775 1, // U U U Always ok
776 1, // U U S Always ok
777 3, // U S U Ok iff SrcSize != MidSize
778 3, // U S S Ok iff SrcSize != MidSize
779 0, // S U U Never ok
780 2, // S U S Ok iff MidSize == DstSize
781 1, // S S U Always ok
782 1, // S S S Always ok
783 };
784
785 // Choose an action based on the current entry of the signtable that this
786 // cast of cast refers to...
787 unsigned Row = SrcTy->isSigned()*4+MidTy->isSigned()*2+DstTy->isSigned();
788 switch (SignTable[Row]) {
789 case 0: return false; // Never ok
790 case 1: return true; // Always ok
791 case 2: return MidSize == DstSize; // Ok iff MidSize == DstSize
792 case 3: // Ok iff SrcSize != MidSize
793 return SrcSize != MidSize || SrcTy == Type::BoolTy;
794 default: assert(0 && "Bad entry in sign table!");
795 }
Chris Lattner3732aca2002-08-15 16:15:25 +0000796 }
Chris Lattner650b6da2002-08-02 20:00:25 +0000797 }
Chris Lattner48a44f72002-05-02 17:06:02 +0000798
799 // Otherwise, we cannot succeed. Specifically we do not want to allow things
800 // like: short -> ushort -> uint, because this can create wrong results if
801 // the input short is negative!
802 //
803 return false;
804}
805
806
807// CastInst simplification
Chris Lattner260ab202002-04-18 17:39:14 +0000808//
Chris Lattner113f4f42002-06-25 16:13:24 +0000809Instruction *InstCombiner::visitCastInst(CastInst &CI) {
Chris Lattner48a44f72002-05-02 17:06:02 +0000810 // If the user is casting a value to the same type, eliminate this cast
811 // instruction...
Chris Lattnere6794492002-08-12 21:17:25 +0000812 if (CI.getType() == CI.getOperand(0)->getType())
813 return ReplaceInstUsesWith(CI, CI.getOperand(0));
Chris Lattner48a44f72002-05-02 17:06:02 +0000814
Chris Lattner48a44f72002-05-02 17:06:02 +0000815 // If casting the result of another cast instruction, try to eliminate this
816 // one!
817 //
Chris Lattner650b6da2002-08-02 20:00:25 +0000818 if (CastInst *CSrc = dyn_cast<CastInst>(CI.getOperand(0))) {
Chris Lattner48a44f72002-05-02 17:06:02 +0000819 if (isEliminableCastOfCast(CI, CSrc)) {
820 // This instruction now refers directly to the cast's src operand. This
821 // has a good chance of making CSrc dead.
Chris Lattner113f4f42002-06-25 16:13:24 +0000822 CI.setOperand(0, CSrc->getOperand(0));
823 return &CI;
Chris Lattner48a44f72002-05-02 17:06:02 +0000824 }
825
Chris Lattner650b6da2002-08-02 20:00:25 +0000826 // If this is an A->B->A cast, and we are dealing with integral types, try
827 // to convert this into a logical 'and' instruction.
828 //
829 if (CSrc->getOperand(0)->getType() == CI.getType() &&
Chris Lattnerb0b412e2002-09-03 01:08:28 +0000830 CI.getType()->isInteger() && CSrc->getType()->isInteger() &&
Chris Lattner650b6da2002-08-02 20:00:25 +0000831 CI.getType()->isUnsigned() && CSrc->getType()->isUnsigned() &&
832 CSrc->getType()->getPrimitiveSize() < CI.getType()->getPrimitiveSize()){
833 assert(CSrc->getType() != Type::ULongTy &&
834 "Cannot have type bigger than ulong!");
835 unsigned AndValue = (1U << CSrc->getType()->getPrimitiveSize()*8)-1;
836 Constant *AndOp = ConstantUInt::get(CI.getType(), AndValue);
837 return BinaryOperator::create(Instruction::And, CSrc->getOperand(0),
838 AndOp);
839 }
840 }
841
Chris Lattner260ab202002-04-18 17:39:14 +0000842 return 0;
Chris Lattnerca081252001-12-14 16:52:21 +0000843}
844
Chris Lattner48a44f72002-05-02 17:06:02 +0000845
Chris Lattnerbbbdd852002-05-06 18:06:38 +0000846// PHINode simplification
847//
Chris Lattner113f4f42002-06-25 16:13:24 +0000848Instruction *InstCombiner::visitPHINode(PHINode &PN) {
Chris Lattnerbbbdd852002-05-06 18:06:38 +0000849 // If the PHI node only has one incoming value, eliminate the PHI node...
Chris Lattnere6794492002-08-12 21:17:25 +0000850 if (PN.getNumIncomingValues() == 1)
851 return ReplaceInstUsesWith(PN, PN.getIncomingValue(0));
Chris Lattner9cd1e662002-08-20 15:35:35 +0000852
853 // Otherwise if all of the incoming values are the same for the PHI, replace
854 // the PHI node with the incoming value.
855 //
Chris Lattnerf6c0efa2002-08-22 20:22:01 +0000856 Value *InVal = 0;
857 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
858 if (PN.getIncomingValue(i) != &PN) // Not the PHI node itself...
859 if (InVal && PN.getIncomingValue(i) != InVal)
860 return 0; // Not the same, bail out.
861 else
862 InVal = PN.getIncomingValue(i);
863
864 // The only case that could cause InVal to be null is if we have a PHI node
865 // that only has entries for itself. In this case, there is no entry into the
866 // loop, so kill the PHI.
867 //
868 if (InVal == 0) InVal = Constant::getNullValue(PN.getType());
Chris Lattnerbbbdd852002-05-06 18:06:38 +0000869
Chris Lattner9cd1e662002-08-20 15:35:35 +0000870 // All of the incoming values are the same, replace the PHI node now.
871 return ReplaceInstUsesWith(PN, InVal);
Chris Lattnerbbbdd852002-05-06 18:06:38 +0000872}
873
Chris Lattner48a44f72002-05-02 17:06:02 +0000874
Chris Lattner113f4f42002-06-25 16:13:24 +0000875Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
Chris Lattnerae7a0d32002-08-02 19:29:35 +0000876 // Is it 'getelementptr %P, uint 0' or 'getelementptr %P'
Chris Lattner113f4f42002-06-25 16:13:24 +0000877 // If so, eliminate the noop.
Chris Lattnerae7a0d32002-08-02 19:29:35 +0000878 if ((GEP.getNumOperands() == 2 &&
Chris Lattner136dab72002-09-11 01:21:33 +0000879 GEP.getOperand(1) == Constant::getNullValue(Type::LongTy)) ||
Chris Lattnere6794492002-08-12 21:17:25 +0000880 GEP.getNumOperands() == 1)
881 return ReplaceInstUsesWith(GEP, GEP.getOperand(0));
Chris Lattner48a44f72002-05-02 17:06:02 +0000882
Chris Lattnerae7a0d32002-08-02 19:29:35 +0000883 // Combine Indices - If the source pointer to this getelementptr instruction
884 // is a getelementptr instruction, combine the indices of the two
885 // getelementptr instructions into a single instruction.
886 //
Chris Lattnerc59af1d2002-08-17 22:21:59 +0000887 if (GetElementPtrInst *Src = dyn_cast<GetElementPtrInst>(GEP.getOperand(0))) {
Chris Lattnerae7a0d32002-08-02 19:29:35 +0000888 std::vector<Value *> Indices;
Chris Lattnerca081252001-12-14 16:52:21 +0000889
Chris Lattnerae7a0d32002-08-02 19:29:35 +0000890 // Can we combine the two pointer arithmetics offsets?
Chris Lattner235af562003-03-05 22:33:14 +0000891 if (Src->getNumOperands() == 2 && isa<Constant>(Src->getOperand(1)) &&
892 isa<Constant>(GEP.getOperand(1))) {
893 // Replace: gep (gep %P, long C1), long C2, ...
894 // With: gep %P, long (C1+C2), ...
895 Value *Sum = *cast<Constant>(Src->getOperand(1)) +
Chris Lattnerae7a0d32002-08-02 19:29:35 +0000896 *cast<Constant>(GEP.getOperand(1));
Chris Lattner235af562003-03-05 22:33:14 +0000897 assert(Sum && "Constant folding of longs failed!?");
898 GEP.setOperand(0, Src->getOperand(0));
899 GEP.setOperand(1, Sum);
900 AddUsesToWorkList(*Src); // Reduce use count of Src
901 return &GEP;
902 } else if (Src->getNumOperands() == 2 && Src->use_size() == 1) {
903 // Replace: gep (gep %P, long B), long A, ...
904 // With: T = long A+B; gep %P, T, ...
905 //
906 Value *Sum = BinaryOperator::create(Instruction::Add, Src->getOperand(1),
907 GEP.getOperand(1),
908 Src->getName()+".sum", &GEP);
909 GEP.setOperand(0, Src->getOperand(0));
910 GEP.setOperand(1, Sum);
911 WorkList.push_back(cast<Instruction>(Sum));
912 return &GEP;
Chris Lattner5d606a02002-11-04 16:43:32 +0000913 } else if (*GEP.idx_begin() == Constant::getNullValue(Type::LongTy) &&
Chris Lattnera8339e32002-09-17 21:05:42 +0000914 Src->getNumOperands() != 1) {
Chris Lattnerae7a0d32002-08-02 19:29:35 +0000915 // Otherwise we can do the fold if the first index of the GEP is a zero
916 Indices.insert(Indices.end(), Src->idx_begin(), Src->idx_end());
917 Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
Chris Lattner5d606a02002-11-04 16:43:32 +0000918 } else if (Src->getOperand(Src->getNumOperands()-1) ==
919 Constant::getNullValue(Type::LongTy)) {
920 // If the src gep ends with a constant array index, merge this get into
921 // it, even if we have a non-zero array index.
922 Indices.insert(Indices.end(), Src->idx_begin(), Src->idx_end()-1);
923 Indices.insert(Indices.end(), GEP.idx_begin(), GEP.idx_end());
Chris Lattnerae7a0d32002-08-02 19:29:35 +0000924 }
925
926 if (!Indices.empty())
927 return new GetElementPtrInst(Src->getOperand(0), Indices, GEP.getName());
Chris Lattnerc59af1d2002-08-17 22:21:59 +0000928
929 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(GEP.getOperand(0))) {
930 // GEP of global variable. If all of the indices for this GEP are
931 // constants, we can promote this to a constexpr instead of an instruction.
932
933 // Scan for nonconstants...
934 std::vector<Constant*> Indices;
935 User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
936 for (; I != E && isa<Constant>(*I); ++I)
937 Indices.push_back(cast<Constant>(*I));
938
939 if (I == E) { // If they are all constants...
940 ConstantExpr *CE =
941 ConstantExpr::getGetElementPtr(ConstantPointerRef::get(GV), Indices);
942
943 // Replace all uses of the GEP with the new constexpr...
944 return ReplaceInstUsesWith(GEP, CE);
945 }
Chris Lattnerca081252001-12-14 16:52:21 +0000946 }
947
Chris Lattnerca081252001-12-14 16:52:21 +0000948 return 0;
949}
950
Chris Lattner1085bdf2002-11-04 16:18:53 +0000951Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
952 // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
953 if (AI.isArrayAllocation()) // Check C != 1
954 if (const ConstantUInt *C = dyn_cast<ConstantUInt>(AI.getArraySize())) {
955 const Type *NewTy = ArrayType::get(AI.getAllocatedType(), C->getValue());
Chris Lattnera2620ac2002-11-09 00:49:43 +0000956 AllocationInst *New = 0;
Chris Lattner1085bdf2002-11-04 16:18:53 +0000957
958 // Create and insert the replacement instruction...
959 if (isa<MallocInst>(AI))
960 New = new MallocInst(NewTy, 0, AI.getName(), &AI);
Chris Lattnera2620ac2002-11-09 00:49:43 +0000961 else {
962 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
Chris Lattner1085bdf2002-11-04 16:18:53 +0000963 New = new AllocaInst(NewTy, 0, AI.getName(), &AI);
Chris Lattnera2620ac2002-11-09 00:49:43 +0000964 }
Chris Lattner1085bdf2002-11-04 16:18:53 +0000965
966 // Scan to the end of the allocation instructions, to skip over a block of
967 // allocas if possible...
968 //
969 BasicBlock::iterator It = New;
970 while (isa<AllocationInst>(*It)) ++It;
971
972 // Now that I is pointing to the first non-allocation-inst in the block,
973 // insert our getelementptr instruction...
974 //
975 std::vector<Value*> Idx(2, Constant::getNullValue(Type::LongTy));
976 Value *V = new GetElementPtrInst(New, Idx, New->getName()+".sub", It);
977
978 // Now make everything use the getelementptr instead of the original
979 // allocation.
980 ReplaceInstUsesWith(AI, V);
981 return &AI;
982 }
983 return 0;
984}
985
986
Chris Lattnerca081252001-12-14 16:52:21 +0000987
Chris Lattner99f48c62002-09-02 04:59:56 +0000988void InstCombiner::removeFromWorkList(Instruction *I) {
989 WorkList.erase(std::remove(WorkList.begin(), WorkList.end(), I),
990 WorkList.end());
991}
992
Chris Lattner113f4f42002-06-25 16:13:24 +0000993bool InstCombiner::runOnFunction(Function &F) {
Chris Lattner260ab202002-04-18 17:39:14 +0000994 bool Changed = false;
Chris Lattnerca081252001-12-14 16:52:21 +0000995
Chris Lattner260ab202002-04-18 17:39:14 +0000996 WorkList.insert(WorkList.end(), inst_begin(F), inst_end(F));
Chris Lattnerca081252001-12-14 16:52:21 +0000997
998 while (!WorkList.empty()) {
999 Instruction *I = WorkList.back(); // Get an instruction from the worklist
1000 WorkList.pop_back();
1001
Misha Brukman632df282002-10-29 23:06:16 +00001002 // Check to see if we can DCE or ConstantPropagate the instruction...
Chris Lattner99f48c62002-09-02 04:59:56 +00001003 // Check to see if we can DIE the instruction...
1004 if (isInstructionTriviallyDead(I)) {
1005 // Add operands to the worklist...
1006 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
1007 if (Instruction *Op = dyn_cast<Instruction>(I->getOperand(i)))
1008 WorkList.push_back(Op);
1009
1010 ++NumDeadInst;
1011 BasicBlock::iterator BBI = I;
1012 if (dceInstruction(BBI)) {
1013 removeFromWorkList(I);
1014 continue;
1015 }
1016 }
1017
Misha Brukman632df282002-10-29 23:06:16 +00001018 // Instruction isn't dead, see if we can constant propagate it...
Chris Lattner99f48c62002-09-02 04:59:56 +00001019 if (Constant *C = ConstantFoldInstruction(I)) {
1020 // Add operands to the worklist...
1021 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
1022 if (Instruction *Op = dyn_cast<Instruction>(I->getOperand(i)))
1023 WorkList.push_back(Op);
Chris Lattnerc6509f42002-12-05 22:41:53 +00001024 ReplaceInstUsesWith(*I, C);
1025
Chris Lattner99f48c62002-09-02 04:59:56 +00001026 ++NumConstProp;
1027 BasicBlock::iterator BBI = I;
1028 if (dceInstruction(BBI)) {
1029 removeFromWorkList(I);
1030 continue;
1031 }
1032 }
1033
Chris Lattnerca081252001-12-14 16:52:21 +00001034 // Now that we have an instruction, try combining it to simplify it...
Chris Lattnerae7a0d32002-08-02 19:29:35 +00001035 if (Instruction *Result = visit(*I)) {
Chris Lattner0b18c1d2002-05-10 15:38:35 +00001036 ++NumCombined;
Chris Lattner260ab202002-04-18 17:39:14 +00001037 // Should we replace the old instruction with a new one?
Chris Lattner053c0932002-05-14 15:24:07 +00001038 if (Result != I) {
1039 // Instructions can end up on the worklist more than once. Make sure
1040 // we do not process an instruction that has been deleted.
Chris Lattner99f48c62002-09-02 04:59:56 +00001041 removeFromWorkList(I);
Chris Lattner260ab202002-04-18 17:39:14 +00001042 ReplaceInstWithInst(I, Result);
Chris Lattner113f4f42002-06-25 16:13:24 +00001043 } else {
Chris Lattnerae7a0d32002-08-02 19:29:35 +00001044 BasicBlock::iterator II = I;
1045
1046 // If the instruction was modified, it's possible that it is now dead.
1047 // if so, remove it.
1048 if (dceInstruction(II)) {
1049 // Instructions may end up in the worklist more than once. Erase them
1050 // all.
Chris Lattner99f48c62002-09-02 04:59:56 +00001051 removeFromWorkList(I);
Chris Lattnerae7a0d32002-08-02 19:29:35 +00001052 Result = 0;
1053 }
Chris Lattner053c0932002-05-14 15:24:07 +00001054 }
Chris Lattner260ab202002-04-18 17:39:14 +00001055
Chris Lattnerae7a0d32002-08-02 19:29:35 +00001056 if (Result) {
1057 WorkList.push_back(Result);
1058 AddUsesToWorkList(*Result);
1059 }
Chris Lattner260ab202002-04-18 17:39:14 +00001060 Changed = true;
Chris Lattnerca081252001-12-14 16:52:21 +00001061 }
1062 }
1063
Chris Lattner260ab202002-04-18 17:39:14 +00001064 return Changed;
Chris Lattner04805fa2002-02-26 21:46:54 +00001065}
1066
1067Pass *createInstructionCombiningPass() {
Chris Lattner260ab202002-04-18 17:39:14 +00001068 return new InstCombiner();
Chris Lattner04805fa2002-02-26 21:46:54 +00001069}