blob: 30e143dec46ca3f43f0aa72f350e6909d205198a [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
4// instructions. This pass does not modify the CFG, and has a tendancy to
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00005// make instructions dead, so a subsequent DIE pass is useful. This pass is
6// where algebraic simplification happens.
Chris Lattnerca081252001-12-14 16:52:21 +00007//
8// This pass combines things like:
9// %Y = add int 1, %X
10// %Z = add int 1, %Y
11// into:
12// %Z = add int 2, %X
13//
14// This is a simple worklist driven algorithm.
15//
16//===----------------------------------------------------------------------===//
17
Chris Lattnerb4cfa7f2002-05-07 20:03:00 +000018#include "llvm/Transforms/Scalar.h"
Chris Lattner9b55e5a2002-05-07 18:12:18 +000019#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Chris Lattnerae7a0d32002-08-02 19:29:35 +000020#include "llvm/Transforms/Utils/Local.h"
Chris Lattner65b529f2002-04-08 20:18:09 +000021#include "llvm/ConstantHandling.h"
Chris Lattnerca081252001-12-14 16:52:21 +000022#include "llvm/iMemory.h"
Chris Lattner3a60d042002-04-15 19:45:29 +000023#include "llvm/iOther.h"
Chris Lattnerbbbdd852002-05-06 18:06:38 +000024#include "llvm/iPHINode.h"
Chris Lattner260ab202002-04-18 17:39:14 +000025#include "llvm/iOperators.h"
Chris Lattner04805fa2002-02-26 21:46:54 +000026#include "llvm/Pass.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 Lattner0b18c1d2002-05-10 15:38:35 +000029#include "Support/StatisticReporter.h"
Chris Lattner053c0932002-05-14 15:24:07 +000030#include <algorithm>
Chris Lattnerca081252001-12-14 16:52:21 +000031
Chris Lattner0b18c1d2002-05-10 15:38:35 +000032static Statistic<> NumCombined("instcombine\t- Number of insts combined");
Chris Lattnerca081252001-12-14 16:52:21 +000033
Chris Lattner260ab202002-04-18 17:39:14 +000034namespace {
Chris Lattnerc8e66542002-04-27 06:56:12 +000035 class InstCombiner : public FunctionPass,
Chris Lattner260ab202002-04-18 17:39:14 +000036 public InstVisitor<InstCombiner, Instruction*> {
37 // Worklist of all of the instructions that need to be simplified.
38 std::vector<Instruction*> WorkList;
39
Chris Lattner113f4f42002-06-25 16:13:24 +000040 void AddUsesToWorkList(Instruction &I) {
Chris Lattner260ab202002-04-18 17:39:14 +000041 // The instruction was simplified, add all users of the instruction to
42 // the work lists because they might get more simplified now...
43 //
Chris Lattner113f4f42002-06-25 16:13:24 +000044 for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
Chris Lattner260ab202002-04-18 17:39:14 +000045 UI != UE; ++UI)
46 WorkList.push_back(cast<Instruction>(*UI));
47 }
48
49 public:
Chris Lattner113f4f42002-06-25 16:13:24 +000050 virtual bool runOnFunction(Function &F);
Chris Lattner260ab202002-04-18 17:39:14 +000051
Chris Lattnerf12cc842002-04-28 21:27:06 +000052 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
53 AU.preservesCFG();
54 }
55
Chris Lattner260ab202002-04-18 17:39:14 +000056 // Visitation implementation - Implement instruction combining for different
57 // instruction types. The semantics are as follows:
58 // Return Value:
59 // null - No change was made
Chris Lattnere6794492002-08-12 21:17:25 +000060 // I - Change was made, I is still valid, I may be dead though
Chris Lattner260ab202002-04-18 17:39:14 +000061 // otherwise - Change was made, replace I with returned instruction
62 //
Chris Lattner113f4f42002-06-25 16:13:24 +000063 Instruction *visitAdd(BinaryOperator &I);
64 Instruction *visitSub(BinaryOperator &I);
65 Instruction *visitMul(BinaryOperator &I);
66 Instruction *visitDiv(BinaryOperator &I);
67 Instruction *visitRem(BinaryOperator &I);
68 Instruction *visitAnd(BinaryOperator &I);
69 Instruction *visitOr (BinaryOperator &I);
70 Instruction *visitXor(BinaryOperator &I);
71 Instruction *visitSetCondInst(BinaryOperator &I);
72 Instruction *visitShiftInst(Instruction &I);
73 Instruction *visitCastInst(CastInst &CI);
74 Instruction *visitPHINode(PHINode &PN);
75 Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
Chris Lattner260ab202002-04-18 17:39:14 +000076
77 // visitInstruction - Specify what to return for unhandled instructions...
Chris Lattner113f4f42002-06-25 16:13:24 +000078 Instruction *visitInstruction(Instruction &I) { return 0; }
Chris Lattner6d14f2a2002-08-09 23:47:40 +000079
80 // InsertNewInstBefore - insert an instruction New before instruction Old
81 // in the program. Add the new instruction to the worklist.
82 //
83 void InsertNewInstBefore(Instruction *New, Instruction &Old) {
84 BasicBlock *BB = Old.getParent();
85 BB->getInstList().insert(&Old, New); // Insert inst
86 WorkList.push_back(New); // Add to worklist
87 }
88
89 // ReplaceInstUsesWith - This method is to be used when an instruction is
90 // found to be dead, replacable with another preexisting expression. Here
91 // we add all uses of I to the worklist, replace all uses of I with the new
92 // value, then return I, so that the inst combiner will know that I was
93 // modified.
94 //
95 Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
96 AddUsesToWorkList(I); // Add all modified instrs to worklist
97 I.replaceAllUsesWith(V);
98 return &I;
99 }
Chris Lattner260ab202002-04-18 17:39:14 +0000100 };
Chris Lattnerb28b6802002-07-23 18:06:35 +0000101
Chris Lattnerc8b70922002-07-26 21:12:46 +0000102 RegisterOpt<InstCombiner> X("instcombine", "Combine redundant instructions");
Chris Lattner260ab202002-04-18 17:39:14 +0000103}
104
105
Chris Lattner260ab202002-04-18 17:39:14 +0000106// Make sure that this instruction has a constant on the right hand side if it
107// has any constant arguments. If not, fix it an return true.
108//
Chris Lattner113f4f42002-06-25 16:13:24 +0000109static bool SimplifyBinOp(BinaryOperator &I) {
110 if (isa<Constant>(I.getOperand(0)) && !isa<Constant>(I.getOperand(1)))
111 return !I.swapOperands();
Chris Lattner260ab202002-04-18 17:39:14 +0000112 return false;
113}
Chris Lattnerca081252001-12-14 16:52:21 +0000114
Chris Lattner9fa53de2002-05-06 16:49:18 +0000115// dyn_castNegInst - Given a 'sub' instruction, return the RHS of the
116// instruction if the LHS is a constant zero (which is the 'negate' form).
117//
118static inline Value *dyn_castNegInst(Value *V) {
119 Instruction *I = dyn_cast<Instruction>(V);
120 if (!I || I->getOpcode() != Instruction::Sub) return 0;
121
122 if (I->getOperand(0) == Constant::getNullValue(I->getType()))
123 return I->getOperand(1);
124 return 0;
125}
126
Chris Lattner31ae8632002-08-14 17:51:49 +0000127static inline Value *dyn_castNotInst(Value *V) {
128 Instruction *I = dyn_cast<Instruction>(V);
129 if (!I || I->getOpcode() != Instruction::Xor) return 0;
130
131 if (ConstantIntegral *CI = dyn_cast<ConstantIntegral>(I->getOperand(1)))
132 if (CI->isAllOnesValue())
133 return I->getOperand(0);
134 return 0;
135}
136
Chris Lattner113f4f42002-06-25 16:13:24 +0000137Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
Chris Lattner260ab202002-04-18 17:39:14 +0000138 bool Changed = SimplifyBinOp(I);
Chris Lattner113f4f42002-06-25 16:13:24 +0000139 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
Chris Lattner9fa53de2002-05-06 16:49:18 +0000140
141 // Eliminate 'add int %X, 0'
Chris Lattnere6794492002-08-12 21:17:25 +0000142 if (RHS == Constant::getNullValue(I.getType()))
143 return ReplaceInstUsesWith(I, LHS);
Chris Lattner9fa53de2002-05-06 16:49:18 +0000144
Chris Lattner147e9752002-05-08 22:46:53 +0000145 // -A + B --> B - A
Chris Lattner9fa53de2002-05-06 16:49:18 +0000146 if (Value *V = dyn_castNegInst(LHS))
Chris Lattner147e9752002-05-08 22:46:53 +0000147 return BinaryOperator::create(Instruction::Sub, RHS, V);
Chris Lattner9fa53de2002-05-06 16:49:18 +0000148
149 // A + -B --> A - B
150 if (Value *V = dyn_castNegInst(RHS))
Chris Lattner147e9752002-05-08 22:46:53 +0000151 return BinaryOperator::create(Instruction::Sub, LHS, V);
Chris Lattner260ab202002-04-18 17:39:14 +0000152
153 // Simplify add instructions with a constant RHS...
Chris Lattner9fa53de2002-05-06 16:49:18 +0000154 if (Constant *Op2 = dyn_cast<Constant>(RHS)) {
155 if (BinaryOperator *ILHS = dyn_cast<BinaryOperator>(LHS)) {
156 if (ILHS->getOpcode() == Instruction::Add &&
157 isa<Constant>(ILHS->getOperand(1))) {
Chris Lattner260ab202002-04-18 17:39:14 +0000158 // Fold:
159 // %Y = add int %X, 1
160 // %Z = add int %Y, 1
161 // into:
162 // %Z = add int %X, 2
163 //
Chris Lattner9fa53de2002-05-06 16:49:18 +0000164 if (Constant *Val = *Op2 + *cast<Constant>(ILHS->getOperand(1))) {
Chris Lattner113f4f42002-06-25 16:13:24 +0000165 I.setOperand(0, ILHS->getOperand(0));
166 I.setOperand(1, Val);
167 return &I;
Chris Lattner04805fa2002-02-26 21:46:54 +0000168 }
Chris Lattnerca081252001-12-14 16:52:21 +0000169 }
170 }
Chris Lattnerca081252001-12-14 16:52:21 +0000171 }
172
Chris Lattner113f4f42002-06-25 16:13:24 +0000173 return Changed ? &I : 0;
Chris Lattner260ab202002-04-18 17:39:14 +0000174}
175
Chris Lattner113f4f42002-06-25 16:13:24 +0000176Instruction *InstCombiner::visitSub(BinaryOperator &I) {
Chris Lattner113f4f42002-06-25 16:13:24 +0000177 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000178
Chris Lattnere6794492002-08-12 21:17:25 +0000179 if (Op0 == Op1) // sub X, X -> 0
180 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner260ab202002-04-18 17:39:14 +0000181
182 // If this is a subtract instruction with a constant RHS, convert it to an add
183 // instruction of a negative constant
184 //
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000185 if (Constant *Op2 = dyn_cast<Constant>(Op1))
Chris Lattner113f4f42002-06-25 16:13:24 +0000186 if (Constant *RHS = *Constant::getNullValue(I.getType()) - *Op2) // 0 - RHS
187 return BinaryOperator::create(Instruction::Add, Op0, RHS, I.getName());
Chris Lattner260ab202002-04-18 17:39:14 +0000188
Chris Lattnere6794492002-08-12 21:17:25 +0000189 // If this is a 'B = x-(-A)', change to B = x+A...
Chris Lattner147e9752002-05-08 22:46:53 +0000190 if (Value *V = dyn_castNegInst(Op1))
191 return BinaryOperator::create(Instruction::Add, Op0, V);
Chris Lattner9fa53de2002-05-06 16:49:18 +0000192
Chris Lattnerad3c4952002-05-09 01:29:19 +0000193 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression is
194 // not used by anyone else...
195 //
196 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1))
Chris Lattner170ed7b2002-05-14 16:44:07 +0000197 if (Op1I->use_size() == 1 && Op1I->getOpcode() == Instruction::Sub) {
Chris Lattnerad3c4952002-05-09 01:29:19 +0000198 // Swap the two operands of the subexpr...
199 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
200 Op1I->setOperand(0, IIOp1);
201 Op1I->setOperand(1, IIOp0);
202
203 // Create the new top level add instruction...
204 return BinaryOperator::create(Instruction::Add, Op0, Op1);
205 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000206 return 0;
Chris Lattner260ab202002-04-18 17:39:14 +0000207}
208
Chris Lattner113f4f42002-06-25 16:13:24 +0000209Instruction *InstCombiner::visitMul(BinaryOperator &I) {
Chris Lattner260ab202002-04-18 17:39:14 +0000210 bool Changed = SimplifyBinOp(I);
Chris Lattner113f4f42002-06-25 16:13:24 +0000211 Value *Op1 = I.getOperand(0);
Chris Lattner260ab202002-04-18 17:39:14 +0000212
Chris Lattnere6794492002-08-12 21:17:25 +0000213 // Simplify mul instructions with a constant RHS...
Chris Lattner113f4f42002-06-25 16:13:24 +0000214 if (Constant *Op2 = dyn_cast<Constant>(I.getOperand(1))) {
Chris Lattnere6794492002-08-12 21:17:25 +0000215 if (I.getType()->isIntegral() && cast<ConstantInt>(Op2)->equalsInt(1))
216 return ReplaceInstUsesWith(I, Op1); // Eliminate 'mul int %X, 1'
Chris Lattner31ba1292002-04-29 22:24:47 +0000217
Chris Lattnere6794492002-08-12 21:17:25 +0000218 if (I.getType()->isIntegral() && cast<ConstantInt>(Op2)->equalsInt(2))
Chris Lattner31ba1292002-04-29 22:24:47 +0000219 // Convert 'mul int %X, 2' to 'add int %X, %X'
Chris Lattner113f4f42002-06-25 16:13:24 +0000220 return BinaryOperator::create(Instruction::Add, Op1, Op1, I.getName());
Chris Lattner31ba1292002-04-29 22:24:47 +0000221
Chris Lattnere6794492002-08-12 21:17:25 +0000222 if (Op2->isNullValue())
223 return ReplaceInstUsesWith(I, Op2); // Eliminate 'mul int %X, 0'
Chris Lattner260ab202002-04-18 17:39:14 +0000224 }
225
Chris Lattner113f4f42002-06-25 16:13:24 +0000226 return Changed ? &I : 0;
Chris Lattner260ab202002-04-18 17:39:14 +0000227}
228
229
Chris Lattner113f4f42002-06-25 16:13:24 +0000230Instruction *InstCombiner::visitDiv(BinaryOperator &I) {
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000231 // div X, 1 == X
Chris Lattner113f4f42002-06-25 16:13:24 +0000232 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I.getOperand(1)))
Chris Lattnere6794492002-08-12 21:17:25 +0000233 if (RHS->equalsInt(1))
234 return ReplaceInstUsesWith(I, I.getOperand(0));
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000235 return 0;
236}
237
238
Chris Lattner113f4f42002-06-25 16:13:24 +0000239Instruction *InstCombiner::visitRem(BinaryOperator &I) {
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000240 // rem X, 1 == 0
Chris Lattner113f4f42002-06-25 16:13:24 +0000241 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I.getOperand(1)))
Chris Lattnere6794492002-08-12 21:17:25 +0000242 if (RHS->equalsInt(1))
243 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
244
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000245 return 0;
246}
247
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000248// isMaxValueMinusOne - return true if this is Max-1
Chris Lattnere6794492002-08-12 21:17:25 +0000249static bool isMaxValueMinusOne(const ConstantInt *C) {
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000250 if (const ConstantUInt *CU = dyn_cast<ConstantUInt>(C)) {
251 // Calculate -1 casted to the right type...
252 unsigned TypeBits = C->getType()->getPrimitiveSize()*8;
253 uint64_t Val = ~0ULL; // All ones
254 Val >>= 64-TypeBits; // Shift out unwanted 1 bits...
255 return CU->getValue() == Val-1;
256 }
257
258 const ConstantSInt *CS = cast<ConstantSInt>(C);
259
260 // Calculate 0111111111..11111
261 unsigned TypeBits = C->getType()->getPrimitiveSize()*8;
262 int64_t Val = INT64_MAX; // All ones
263 Val >>= 64-TypeBits; // Shift out unwanted 1 bits...
264 return CS->getValue() == Val-1;
265}
266
267// isMinValuePlusOne - return true if this is Min+1
Chris Lattnere6794492002-08-12 21:17:25 +0000268static bool isMinValuePlusOne(const ConstantInt *C) {
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000269 if (const ConstantUInt *CU = dyn_cast<ConstantUInt>(C))
270 return CU->getValue() == 1;
271
272 const ConstantSInt *CS = cast<ConstantSInt>(C);
273
274 // Calculate 1111111111000000000000
275 unsigned TypeBits = C->getType()->getPrimitiveSize()*8;
276 int64_t Val = -1; // All ones
277 Val <<= TypeBits-1; // Shift over to the right spot
278 return CS->getValue() == Val+1;
279}
280
281
Chris Lattner113f4f42002-06-25 16:13:24 +0000282Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000283 bool Changed = SimplifyBinOp(I);
Chris Lattner113f4f42002-06-25 16:13:24 +0000284 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000285
286 // and X, X = X and X, 0 == 0
Chris Lattnere6794492002-08-12 21:17:25 +0000287 if (Op0 == Op1 || Op1 == Constant::getNullValue(I.getType()))
288 return ReplaceInstUsesWith(I, Op1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000289
290 // and X, -1 == X
Chris Lattner83282632002-08-13 17:50:24 +0000291 if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1))
Chris Lattnere6794492002-08-12 21:17:25 +0000292 if (RHS->isAllOnesValue())
293 return ReplaceInstUsesWith(I, Op0);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000294
Chris Lattner113f4f42002-06-25 16:13:24 +0000295 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000296}
297
298
299
Chris Lattner113f4f42002-06-25 16:13:24 +0000300Instruction *InstCombiner::visitOr(BinaryOperator &I) {
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000301 bool Changed = SimplifyBinOp(I);
Chris Lattner113f4f42002-06-25 16:13:24 +0000302 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000303
304 // or X, X = X or X, 0 == X
Chris Lattnere6794492002-08-12 21:17:25 +0000305 if (Op0 == Op1 || Op1 == Constant::getNullValue(I.getType()))
306 return ReplaceInstUsesWith(I, Op0);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000307
308 // or X, -1 == -1
Chris Lattner83282632002-08-13 17:50:24 +0000309 if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1))
Chris Lattnere6794492002-08-12 21:17:25 +0000310 if (RHS->isAllOnesValue())
311 return ReplaceInstUsesWith(I, Op1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000312
Chris Lattner113f4f42002-06-25 16:13:24 +0000313 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000314}
315
316
317
Chris Lattner113f4f42002-06-25 16:13:24 +0000318Instruction *InstCombiner::visitXor(BinaryOperator &I) {
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000319 bool Changed = SimplifyBinOp(I);
Chris Lattner113f4f42002-06-25 16:13:24 +0000320 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000321
322 // xor X, X = 0
Chris Lattnere6794492002-08-12 21:17:25 +0000323 if (Op0 == Op1)
324 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000325
Chris Lattner83282632002-08-13 17:50:24 +0000326 if (ConstantIntegral *Op1C = dyn_cast<ConstantIntegral>(Op1)) {
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000327 // xor X, 0 == X
Chris Lattnere6794492002-08-12 21:17:25 +0000328 if (Op1C->isNullValue())
329 return ReplaceInstUsesWith(I, Op0);
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000330
Chris Lattnerb8d6e402002-08-20 18:24:26 +0000331 // Is this a "NOT" instruction?
332 if (Op1C->isAllOnesValue()) {
333 // xor (xor X, -1), -1 = not (not X) = X
Chris Lattner31ae8632002-08-14 17:51:49 +0000334 if (Value *X = dyn_castNotInst(Op0))
335 return ReplaceInstUsesWith(I, X);
Chris Lattnerb8d6e402002-08-20 18:24:26 +0000336
337 // xor (setcc A, B), true = not (setcc A, B) = setncc A, B
338 if (SetCondInst *SCI = dyn_cast<SetCondInst>(Op0))
339 if (SCI->use_size() == 1)
340 return new SetCondInst(SCI->getInverseCondition(),
341 SCI->getOperand(0), SCI->getOperand(1));
342 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000343 }
344
Chris Lattner113f4f42002-06-25 16:13:24 +0000345 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000346}
347
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000348// AddOne, SubOne - Add or subtract a constant one from an integer constant...
349static Constant *AddOne(ConstantInt *C) {
350 Constant *Result = *C + *ConstantInt::get(C->getType(), 1);
351 assert(Result && "Constant folding integer addition failed!");
352 return Result;
353}
354static Constant *SubOne(ConstantInt *C) {
355 Constant *Result = *C - *ConstantInt::get(C->getType(), 1);
356 assert(Result && "Constant folding integer addition failed!");
357 return Result;
358}
359
Chris Lattner1fc23f32002-05-09 20:11:54 +0000360// isTrueWhenEqual - Return true if the specified setcondinst instruction is
361// true when both operands are equal...
362//
Chris Lattner113f4f42002-06-25 16:13:24 +0000363static bool isTrueWhenEqual(Instruction &I) {
364 return I.getOpcode() == Instruction::SetEQ ||
365 I.getOpcode() == Instruction::SetGE ||
366 I.getOpcode() == Instruction::SetLE;
Chris Lattner1fc23f32002-05-09 20:11:54 +0000367}
368
Chris Lattner113f4f42002-06-25 16:13:24 +0000369Instruction *InstCombiner::visitSetCondInst(BinaryOperator &I) {
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000370 bool Changed = SimplifyBinOp(I);
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000371 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
372 const Type *Ty = Op0->getType();
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000373
374 // setcc X, X
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000375 if (Op0 == Op1)
376 return ReplaceInstUsesWith(I, ConstantBool::get(isTrueWhenEqual(I)));
Chris Lattner1fc23f32002-05-09 20:11:54 +0000377
378 // setcc <global*>, 0 - Global value addresses are never null!
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000379 if (isa<GlobalValue>(Op0) && isa<ConstantPointerNull>(Op1))
380 return ReplaceInstUsesWith(I, ConstantBool::get(!isTrueWhenEqual(I)));
381
382 // setcc's with boolean values can always be turned into bitwise operations
383 if (Ty == Type::BoolTy) {
384 // If this is <, >, or !=, we can change this into a simple xor instruction
385 if (!isTrueWhenEqual(I))
386 return BinaryOperator::create(Instruction::Xor, Op0, Op1, I.getName());
387
388 // Otherwise we need to make a temporary intermediate instruction and insert
389 // it into the instruction stream. This is what we are after:
390 //
391 // seteq bool %A, %B -> ~(A^B)
392 // setle bool %A, %B -> ~A | B
393 // setge bool %A, %B -> A | ~B
394 //
395 if (I.getOpcode() == Instruction::SetEQ) { // seteq case
396 Instruction *Xor = BinaryOperator::create(Instruction::Xor, Op0, Op1,
397 I.getName()+"tmp");
398 InsertNewInstBefore(Xor, I);
Chris Lattner31ae8632002-08-14 17:51:49 +0000399 return BinaryOperator::createNot(Xor, I.getName());
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000400 }
401
402 // Handle the setXe cases...
403 assert(I.getOpcode() == Instruction::SetGE ||
404 I.getOpcode() == Instruction::SetLE);
405
406 if (I.getOpcode() == Instruction::SetGE)
407 std::swap(Op0, Op1); // Change setge -> setle
408
409 // Now we just have the SetLE case.
Chris Lattner31ae8632002-08-14 17:51:49 +0000410 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000411 InsertNewInstBefore(Not, I);
412 return BinaryOperator::create(Instruction::Or, Not, Op1, I.getName());
413 }
414
415 // Check to see if we are doing one of many comparisons against constant
416 // integers at the end of their ranges...
417 //
418 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
419 // Check to see if we are comparing against the minimum or maximum value...
Chris Lattnere6794492002-08-12 21:17:25 +0000420 if (CI->isMinValue()) {
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000421 if (I.getOpcode() == Instruction::SetLT) // A < MIN -> FALSE
422 return ReplaceInstUsesWith(I, ConstantBool::False);
423 if (I.getOpcode() == Instruction::SetGE) // A >= MIN -> TRUE
424 return ReplaceInstUsesWith(I, ConstantBool::True);
425 if (I.getOpcode() == Instruction::SetLE) // A <= MIN -> A == MIN
426 return BinaryOperator::create(Instruction::SetEQ, Op0,Op1, I.getName());
427 if (I.getOpcode() == Instruction::SetGT) // A > MIN -> A != MIN
428 return BinaryOperator::create(Instruction::SetNE, Op0,Op1, I.getName());
429
Chris Lattnere6794492002-08-12 21:17:25 +0000430 } else if (CI->isMaxValue()) {
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000431 if (I.getOpcode() == Instruction::SetGT) // A > MAX -> FALSE
432 return ReplaceInstUsesWith(I, ConstantBool::False);
433 if (I.getOpcode() == Instruction::SetLE) // A <= MAX -> TRUE
434 return ReplaceInstUsesWith(I, ConstantBool::True);
435 if (I.getOpcode() == Instruction::SetGE) // A >= MAX -> A == MAX
436 return BinaryOperator::create(Instruction::SetEQ, Op0,Op1, I.getName());
437 if (I.getOpcode() == Instruction::SetLT) // A < MAX -> A != MAX
438 return BinaryOperator::create(Instruction::SetNE, Op0,Op1, I.getName());
439
440 // Comparing against a value really close to min or max?
441 } else if (isMinValuePlusOne(CI)) {
442 if (I.getOpcode() == Instruction::SetLT) // A < MIN+1 -> A == MIN
443 return BinaryOperator::create(Instruction::SetEQ, Op0,
444 SubOne(CI), I.getName());
445 if (I.getOpcode() == Instruction::SetGE) // A >= MIN-1 -> A != MIN
446 return BinaryOperator::create(Instruction::SetNE, Op0,
447 SubOne(CI), I.getName());
448
449 } else if (isMaxValueMinusOne(CI)) {
450 if (I.getOpcode() == Instruction::SetGT) // A > MAX-1 -> A == MAX
451 return BinaryOperator::create(Instruction::SetEQ, Op0,
452 AddOne(CI), I.getName());
453 if (I.getOpcode() == Instruction::SetLE) // A <= MAX-1 -> A != MAX
454 return BinaryOperator::create(Instruction::SetNE, Op0,
455 AddOne(CI), I.getName());
456 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000457 }
458
Chris Lattner113f4f42002-06-25 16:13:24 +0000459 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000460}
461
462
463
Chris Lattner113f4f42002-06-25 16:13:24 +0000464Instruction *InstCombiner::visitShiftInst(Instruction &I) {
Chris Lattner113f4f42002-06-25 16:13:24 +0000465 assert(I.getOperand(1)->getType() == Type::UByteTy);
466 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000467
468 // shl X, 0 == X and shr X, 0 == X
469 // shl 0, X == 0 and shr 0, X == 0
470 if (Op1 == Constant::getNullValue(Type::UByteTy) ||
Chris Lattnere6794492002-08-12 21:17:25 +0000471 Op0 == Constant::getNullValue(Op0->getType()))
472 return ReplaceInstUsesWith(I, Op0);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000473
Chris Lattnere6794492002-08-12 21:17:25 +0000474 // shl uint X, 32 = 0 and shr ubyte Y, 9 = 0, ... just don't eliminate shr of
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000475 // a signed value.
476 //
477 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(Op1)) {
478 unsigned TypeBits = Op0->getType()->getPrimitiveSize()*8;
479 if (CUI->getValue() >= TypeBits &&
Chris Lattnere6794492002-08-12 21:17:25 +0000480 !(Op0->getType()->isSigned() && I.getOpcode() == Instruction::Shr))
481 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000482 }
483 return 0;
484}
485
486
Chris Lattner0bb75912002-08-14 23:21:10 +0000487// isCIntegral - For the purposes of casting, we allow conversion of sizes and
488// stuff as long as the value type acts basically integral like.
489//
490static bool isCIntegral(const Type *Ty) {
491 return Ty->isIntegral() || Ty == Type::BoolTy;
492}
493
Chris Lattner48a44f72002-05-02 17:06:02 +0000494// isEliminableCastOfCast - Return true if it is valid to eliminate the CI
495// instruction.
496//
Chris Lattner113f4f42002-06-25 16:13:24 +0000497static inline bool isEliminableCastOfCast(const CastInst &CI,
Chris Lattner48a44f72002-05-02 17:06:02 +0000498 const CastInst *CSrc) {
Chris Lattner113f4f42002-06-25 16:13:24 +0000499 assert(CI.getOperand(0) == CSrc);
Chris Lattner48a44f72002-05-02 17:06:02 +0000500 const Type *SrcTy = CSrc->getOperand(0)->getType();
501 const Type *MidTy = CSrc->getType();
Chris Lattner113f4f42002-06-25 16:13:24 +0000502 const Type *DstTy = CI.getType();
Chris Lattner48a44f72002-05-02 17:06:02 +0000503
Chris Lattner650b6da2002-08-02 20:00:25 +0000504 // It is legal to eliminate the instruction if casting A->B->A if the sizes
505 // are identical and the bits don't get reinterpreted (for example
Chris Lattner0bb75912002-08-14 23:21:10 +0000506 // int->float->int would not be allowed)
Chris Lattner650b6da2002-08-02 20:00:25 +0000507 if (SrcTy == DstTy && SrcTy->isLosslesslyConvertableTo(MidTy))
508 return true;
Chris Lattner48a44f72002-05-02 17:06:02 +0000509
510 // Allow free casting and conversion of sizes as long as the sign doesn't
511 // change...
Chris Lattner3732aca2002-08-15 16:15:25 +0000512 if (isCIntegral(SrcTy) && isCIntegral(MidTy) && isCIntegral(DstTy)) {
Chris Lattner650b6da2002-08-02 20:00:25 +0000513 unsigned SrcSize = SrcTy->getPrimitiveSize();
514 unsigned MidSize = MidTy->getPrimitiveSize();
515 unsigned DstSize = DstTy->getPrimitiveSize();
Chris Lattner650b6da2002-08-02 20:00:25 +0000516
Chris Lattner3732aca2002-08-15 16:15:25 +0000517 // Cases where we are monotonically decreasing the size of the type are
518 // always ok, regardless of what sign changes are going on.
519 //
Chris Lattner0bb75912002-08-14 23:21:10 +0000520 if (SrcSize >= MidSize && MidSize >= DstSize)
Chris Lattner650b6da2002-08-02 20:00:25 +0000521 return true;
Chris Lattner3732aca2002-08-15 16:15:25 +0000522
523 // If we are monotonically growing, things are more complex.
524 //
525 if (SrcSize <= MidSize && MidSize <= DstSize) {
526 // We have eight combinations of signedness to worry about. Here's the
527 // table:
528 static const int SignTable[8] = {
529 // CODE, SrcSigned, MidSigned, DstSigned, Comment
530 1, // U U U Always ok
531 1, // U U S Always ok
532 3, // U S U Ok iff SrcSize != MidSize
533 3, // U S S Ok iff SrcSize != MidSize
534 0, // S U U Never ok
535 2, // S U S Ok iff MidSize == DstSize
536 1, // S S U Always ok
537 1, // S S S Always ok
538 };
539
540 // Choose an action based on the current entry of the signtable that this
541 // cast of cast refers to...
542 unsigned Row = SrcTy->isSigned()*4+MidTy->isSigned()*2+DstTy->isSigned();
543 switch (SignTable[Row]) {
544 case 0: return false; // Never ok
545 case 1: return true; // Always ok
546 case 2: return MidSize == DstSize; // Ok iff MidSize == DstSize
547 case 3: // Ok iff SrcSize != MidSize
548 return SrcSize != MidSize || SrcTy == Type::BoolTy;
549 default: assert(0 && "Bad entry in sign table!");
550 }
Chris Lattner3732aca2002-08-15 16:15:25 +0000551 }
Chris Lattner650b6da2002-08-02 20:00:25 +0000552 }
Chris Lattner48a44f72002-05-02 17:06:02 +0000553
554 // Otherwise, we cannot succeed. Specifically we do not want to allow things
555 // like: short -> ushort -> uint, because this can create wrong results if
556 // the input short is negative!
557 //
558 return false;
559}
560
561
562// CastInst simplification
Chris Lattner260ab202002-04-18 17:39:14 +0000563//
Chris Lattner113f4f42002-06-25 16:13:24 +0000564Instruction *InstCombiner::visitCastInst(CastInst &CI) {
Chris Lattner48a44f72002-05-02 17:06:02 +0000565 // If the user is casting a value to the same type, eliminate this cast
566 // instruction...
Chris Lattnere6794492002-08-12 21:17:25 +0000567 if (CI.getType() == CI.getOperand(0)->getType())
568 return ReplaceInstUsesWith(CI, CI.getOperand(0));
Chris Lattner48a44f72002-05-02 17:06:02 +0000569
Chris Lattner48a44f72002-05-02 17:06:02 +0000570 // If casting the result of another cast instruction, try to eliminate this
571 // one!
572 //
Chris Lattner650b6da2002-08-02 20:00:25 +0000573 if (CastInst *CSrc = dyn_cast<CastInst>(CI.getOperand(0))) {
Chris Lattner48a44f72002-05-02 17:06:02 +0000574 if (isEliminableCastOfCast(CI, CSrc)) {
575 // This instruction now refers directly to the cast's src operand. This
576 // has a good chance of making CSrc dead.
Chris Lattner113f4f42002-06-25 16:13:24 +0000577 CI.setOperand(0, CSrc->getOperand(0));
578 return &CI;
Chris Lattner48a44f72002-05-02 17:06:02 +0000579 }
580
Chris Lattner650b6da2002-08-02 20:00:25 +0000581 // If this is an A->B->A cast, and we are dealing with integral types, try
582 // to convert this into a logical 'and' instruction.
583 //
584 if (CSrc->getOperand(0)->getType() == CI.getType() &&
585 CI.getType()->isIntegral() && CSrc->getType()->isIntegral() &&
586 CI.getType()->isUnsigned() && CSrc->getType()->isUnsigned() &&
587 CSrc->getType()->getPrimitiveSize() < CI.getType()->getPrimitiveSize()){
588 assert(CSrc->getType() != Type::ULongTy &&
589 "Cannot have type bigger than ulong!");
590 unsigned AndValue = (1U << CSrc->getType()->getPrimitiveSize()*8)-1;
591 Constant *AndOp = ConstantUInt::get(CI.getType(), AndValue);
592 return BinaryOperator::create(Instruction::And, CSrc->getOperand(0),
593 AndOp);
594 }
595 }
596
Chris Lattner260ab202002-04-18 17:39:14 +0000597 return 0;
Chris Lattnerca081252001-12-14 16:52:21 +0000598}
599
Chris Lattner48a44f72002-05-02 17:06:02 +0000600
Chris Lattnerbbbdd852002-05-06 18:06:38 +0000601// PHINode simplification
602//
Chris Lattner113f4f42002-06-25 16:13:24 +0000603Instruction *InstCombiner::visitPHINode(PHINode &PN) {
Chris Lattnerbbbdd852002-05-06 18:06:38 +0000604 // If the PHI node only has one incoming value, eliminate the PHI node...
Chris Lattner9cd1e662002-08-20 15:35:35 +0000605 if (PN.getNumIncomingValues() == 0)
606 return ReplaceInstUsesWith(PN, Constant::getNullValue(PN.getType()));
Chris Lattnere6794492002-08-12 21:17:25 +0000607 if (PN.getNumIncomingValues() == 1)
608 return ReplaceInstUsesWith(PN, PN.getIncomingValue(0));
Chris Lattner9cd1e662002-08-20 15:35:35 +0000609
610 // Otherwise if all of the incoming values are the same for the PHI, replace
611 // the PHI node with the incoming value.
612 //
613 Value *InVal = PN.getIncomingValue(0);
614 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i)
615 if (PN.getIncomingValue(i) != InVal)
616 return 0; // Not the same, bail out.
Chris Lattnerbbbdd852002-05-06 18:06:38 +0000617
Chris Lattner9cd1e662002-08-20 15:35:35 +0000618 // All of the incoming values are the same, replace the PHI node now.
619 return ReplaceInstUsesWith(PN, InVal);
Chris Lattnerbbbdd852002-05-06 18:06:38 +0000620}
621
Chris Lattner48a44f72002-05-02 17:06:02 +0000622
Chris Lattner113f4f42002-06-25 16:13:24 +0000623Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
Chris Lattnerae7a0d32002-08-02 19:29:35 +0000624 // Is it 'getelementptr %P, uint 0' or 'getelementptr %P'
Chris Lattner113f4f42002-06-25 16:13:24 +0000625 // If so, eliminate the noop.
Chris Lattnerae7a0d32002-08-02 19:29:35 +0000626 if ((GEP.getNumOperands() == 2 &&
627 GEP.getOperand(1) == Constant::getNullValue(Type::UIntTy)) ||
Chris Lattnere6794492002-08-12 21:17:25 +0000628 GEP.getNumOperands() == 1)
629 return ReplaceInstUsesWith(GEP, GEP.getOperand(0));
Chris Lattner48a44f72002-05-02 17:06:02 +0000630
Chris Lattnerae7a0d32002-08-02 19:29:35 +0000631 // Combine Indices - If the source pointer to this getelementptr instruction
632 // is a getelementptr instruction, combine the indices of the two
633 // getelementptr instructions into a single instruction.
634 //
Chris Lattnerc59af1d2002-08-17 22:21:59 +0000635 if (GetElementPtrInst *Src = dyn_cast<GetElementPtrInst>(GEP.getOperand(0))) {
Chris Lattnerae7a0d32002-08-02 19:29:35 +0000636 std::vector<Value *> Indices;
Chris Lattnerca081252001-12-14 16:52:21 +0000637
Chris Lattnerae7a0d32002-08-02 19:29:35 +0000638 // Can we combine the two pointer arithmetics offsets?
639 if (Src->getNumOperands() == 2 && isa<Constant>(Src->getOperand(1)) &&
640 isa<Constant>(GEP.getOperand(1))) {
641 // Replace the index list on this GEP with the index on the getelementptr
642 Indices.insert(Indices.end(), GEP.idx_begin(), GEP.idx_end());
643 Indices[0] = *cast<Constant>(Src->getOperand(1)) +
644 *cast<Constant>(GEP.getOperand(1));
645 assert(Indices[0] != 0 && "Constant folding of uint's failed!?");
646
647 } else if (*GEP.idx_begin() == ConstantUInt::get(Type::UIntTy, 0)) {
648 // Otherwise we can do the fold if the first index of the GEP is a zero
649 Indices.insert(Indices.end(), Src->idx_begin(), Src->idx_end());
650 Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
651 }
652
653 if (!Indices.empty())
654 return new GetElementPtrInst(Src->getOperand(0), Indices, GEP.getName());
Chris Lattnerc59af1d2002-08-17 22:21:59 +0000655
656 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(GEP.getOperand(0))) {
657 // GEP of global variable. If all of the indices for this GEP are
658 // constants, we can promote this to a constexpr instead of an instruction.
659
660 // Scan for nonconstants...
661 std::vector<Constant*> Indices;
662 User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
663 for (; I != E && isa<Constant>(*I); ++I)
664 Indices.push_back(cast<Constant>(*I));
665
666 if (I == E) { // If they are all constants...
667 ConstantExpr *CE =
668 ConstantExpr::getGetElementPtr(ConstantPointerRef::get(GV), Indices);
669
670 // Replace all uses of the GEP with the new constexpr...
671 return ReplaceInstUsesWith(GEP, CE);
672 }
Chris Lattnerca081252001-12-14 16:52:21 +0000673 }
674
Chris Lattnerca081252001-12-14 16:52:21 +0000675 return 0;
676}
677
Chris Lattnerca081252001-12-14 16:52:21 +0000678
Chris Lattner113f4f42002-06-25 16:13:24 +0000679bool InstCombiner::runOnFunction(Function &F) {
Chris Lattner260ab202002-04-18 17:39:14 +0000680 bool Changed = false;
Chris Lattnerca081252001-12-14 16:52:21 +0000681
Chris Lattner260ab202002-04-18 17:39:14 +0000682 WorkList.insert(WorkList.end(), inst_begin(F), inst_end(F));
Chris Lattnerca081252001-12-14 16:52:21 +0000683
684 while (!WorkList.empty()) {
685 Instruction *I = WorkList.back(); // Get an instruction from the worklist
686 WorkList.pop_back();
687
688 // Now that we have an instruction, try combining it to simplify it...
Chris Lattnerae7a0d32002-08-02 19:29:35 +0000689 if (Instruction *Result = visit(*I)) {
Chris Lattner0b18c1d2002-05-10 15:38:35 +0000690 ++NumCombined;
Chris Lattner260ab202002-04-18 17:39:14 +0000691 // Should we replace the old instruction with a new one?
Chris Lattner053c0932002-05-14 15:24:07 +0000692 if (Result != I) {
693 // Instructions can end up on the worklist more than once. Make sure
694 // we do not process an instruction that has been deleted.
Chris Lattnerae7a0d32002-08-02 19:29:35 +0000695 WorkList.erase(std::remove(WorkList.begin(), WorkList.end(), I),
696 WorkList.end());
Chris Lattner053c0932002-05-14 15:24:07 +0000697
Chris Lattner260ab202002-04-18 17:39:14 +0000698 ReplaceInstWithInst(I, Result);
Chris Lattner113f4f42002-06-25 16:13:24 +0000699 } else {
Chris Lattnerae7a0d32002-08-02 19:29:35 +0000700 BasicBlock::iterator II = I;
701
702 // If the instruction was modified, it's possible that it is now dead.
703 // if so, remove it.
704 if (dceInstruction(II)) {
705 // Instructions may end up in the worklist more than once. Erase them
706 // all.
707 WorkList.erase(std::remove(WorkList.begin(), WorkList.end(), I),
708 WorkList.end());
709 Result = 0;
710 }
Chris Lattner053c0932002-05-14 15:24:07 +0000711 }
Chris Lattner260ab202002-04-18 17:39:14 +0000712
Chris Lattnerae7a0d32002-08-02 19:29:35 +0000713 if (Result) {
714 WorkList.push_back(Result);
715 AddUsesToWorkList(*Result);
716 }
Chris Lattner260ab202002-04-18 17:39:14 +0000717 Changed = true;
Chris Lattnerca081252001-12-14 16:52:21 +0000718 }
719 }
720
Chris Lattner260ab202002-04-18 17:39:14 +0000721 return Changed;
Chris Lattner04805fa2002-02-26 21:46:54 +0000722}
723
724Pass *createInstructionCombiningPass() {
Chris Lattner260ab202002-04-18 17:39:14 +0000725 return new InstCombiner();
Chris Lattner04805fa2002-02-26 21:46:54 +0000726}