blob: cc00093c78a84bb93c4437888258ecc8b06b1046 [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 Lattner31ae8632002-08-14 17:51:49 +0000331 // xor (xor X, -1), -1 = not (not X) = X
Chris Lattnere6794492002-08-12 21:17:25 +0000332 if (Op1C->isAllOnesValue())
Chris Lattner31ae8632002-08-14 17:51:49 +0000333 if (Value *X = dyn_castNotInst(Op0))
334 return ReplaceInstUsesWith(I, X);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000335 }
336
Chris Lattner113f4f42002-06-25 16:13:24 +0000337 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000338}
339
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000340// AddOne, SubOne - Add or subtract a constant one from an integer constant...
341static Constant *AddOne(ConstantInt *C) {
342 Constant *Result = *C + *ConstantInt::get(C->getType(), 1);
343 assert(Result && "Constant folding integer addition failed!");
344 return Result;
345}
346static Constant *SubOne(ConstantInt *C) {
347 Constant *Result = *C - *ConstantInt::get(C->getType(), 1);
348 assert(Result && "Constant folding integer addition failed!");
349 return Result;
350}
351
Chris Lattner1fc23f32002-05-09 20:11:54 +0000352// isTrueWhenEqual - Return true if the specified setcondinst instruction is
353// true when both operands are equal...
354//
Chris Lattner113f4f42002-06-25 16:13:24 +0000355static bool isTrueWhenEqual(Instruction &I) {
356 return I.getOpcode() == Instruction::SetEQ ||
357 I.getOpcode() == Instruction::SetGE ||
358 I.getOpcode() == Instruction::SetLE;
Chris Lattner1fc23f32002-05-09 20:11:54 +0000359}
360
Chris Lattner113f4f42002-06-25 16:13:24 +0000361Instruction *InstCombiner::visitSetCondInst(BinaryOperator &I) {
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000362 bool Changed = SimplifyBinOp(I);
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000363 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
364 const Type *Ty = Op0->getType();
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000365
366 // setcc X, X
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000367 if (Op0 == Op1)
368 return ReplaceInstUsesWith(I, ConstantBool::get(isTrueWhenEqual(I)));
Chris Lattner1fc23f32002-05-09 20:11:54 +0000369
370 // setcc <global*>, 0 - Global value addresses are never null!
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000371 if (isa<GlobalValue>(Op0) && isa<ConstantPointerNull>(Op1))
372 return ReplaceInstUsesWith(I, ConstantBool::get(!isTrueWhenEqual(I)));
373
374 // setcc's with boolean values can always be turned into bitwise operations
375 if (Ty == Type::BoolTy) {
376 // If this is <, >, or !=, we can change this into a simple xor instruction
377 if (!isTrueWhenEqual(I))
378 return BinaryOperator::create(Instruction::Xor, Op0, Op1, I.getName());
379
380 // Otherwise we need to make a temporary intermediate instruction and insert
381 // it into the instruction stream. This is what we are after:
382 //
383 // seteq bool %A, %B -> ~(A^B)
384 // setle bool %A, %B -> ~A | B
385 // setge bool %A, %B -> A | ~B
386 //
387 if (I.getOpcode() == Instruction::SetEQ) { // seteq case
388 Instruction *Xor = BinaryOperator::create(Instruction::Xor, Op0, Op1,
389 I.getName()+"tmp");
390 InsertNewInstBefore(Xor, I);
Chris Lattner31ae8632002-08-14 17:51:49 +0000391 return BinaryOperator::createNot(Xor, I.getName());
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000392 }
393
394 // Handle the setXe cases...
395 assert(I.getOpcode() == Instruction::SetGE ||
396 I.getOpcode() == Instruction::SetLE);
397
398 if (I.getOpcode() == Instruction::SetGE)
399 std::swap(Op0, Op1); // Change setge -> setle
400
401 // Now we just have the SetLE case.
Chris Lattner31ae8632002-08-14 17:51:49 +0000402 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000403 InsertNewInstBefore(Not, I);
404 return BinaryOperator::create(Instruction::Or, Not, Op1, I.getName());
405 }
406
407 // Check to see if we are doing one of many comparisons against constant
408 // integers at the end of their ranges...
409 //
410 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
411 // Check to see if we are comparing against the minimum or maximum value...
Chris Lattnere6794492002-08-12 21:17:25 +0000412 if (CI->isMinValue()) {
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000413 if (I.getOpcode() == Instruction::SetLT) // A < MIN -> FALSE
414 return ReplaceInstUsesWith(I, ConstantBool::False);
415 if (I.getOpcode() == Instruction::SetGE) // A >= MIN -> TRUE
416 return ReplaceInstUsesWith(I, ConstantBool::True);
417 if (I.getOpcode() == Instruction::SetLE) // A <= MIN -> A == MIN
418 return BinaryOperator::create(Instruction::SetEQ, Op0,Op1, I.getName());
419 if (I.getOpcode() == Instruction::SetGT) // A > MIN -> A != MIN
420 return BinaryOperator::create(Instruction::SetNE, Op0,Op1, I.getName());
421
Chris Lattnere6794492002-08-12 21:17:25 +0000422 } else if (CI->isMaxValue()) {
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000423 if (I.getOpcode() == Instruction::SetGT) // A > MAX -> FALSE
424 return ReplaceInstUsesWith(I, ConstantBool::False);
425 if (I.getOpcode() == Instruction::SetLE) // A <= MAX -> TRUE
426 return ReplaceInstUsesWith(I, ConstantBool::True);
427 if (I.getOpcode() == Instruction::SetGE) // A >= MAX -> A == MAX
428 return BinaryOperator::create(Instruction::SetEQ, Op0,Op1, I.getName());
429 if (I.getOpcode() == Instruction::SetLT) // A < MAX -> A != MAX
430 return BinaryOperator::create(Instruction::SetNE, Op0,Op1, I.getName());
431
432 // Comparing against a value really close to min or max?
433 } else if (isMinValuePlusOne(CI)) {
434 if (I.getOpcode() == Instruction::SetLT) // A < MIN+1 -> A == MIN
435 return BinaryOperator::create(Instruction::SetEQ, Op0,
436 SubOne(CI), I.getName());
437 if (I.getOpcode() == Instruction::SetGE) // A >= MIN-1 -> A != MIN
438 return BinaryOperator::create(Instruction::SetNE, Op0,
439 SubOne(CI), I.getName());
440
441 } else if (isMaxValueMinusOne(CI)) {
442 if (I.getOpcode() == Instruction::SetGT) // A > MAX-1 -> A == MAX
443 return BinaryOperator::create(Instruction::SetEQ, Op0,
444 AddOne(CI), I.getName());
445 if (I.getOpcode() == Instruction::SetLE) // A <= MAX-1 -> A != MAX
446 return BinaryOperator::create(Instruction::SetNE, Op0,
447 AddOne(CI), I.getName());
448 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000449 }
450
Chris Lattner113f4f42002-06-25 16:13:24 +0000451 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000452}
453
454
455
Chris Lattner113f4f42002-06-25 16:13:24 +0000456Instruction *InstCombiner::visitShiftInst(Instruction &I) {
Chris Lattner113f4f42002-06-25 16:13:24 +0000457 assert(I.getOperand(1)->getType() == Type::UByteTy);
458 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000459
460 // shl X, 0 == X and shr X, 0 == X
461 // shl 0, X == 0 and shr 0, X == 0
462 if (Op1 == Constant::getNullValue(Type::UByteTy) ||
Chris Lattnere6794492002-08-12 21:17:25 +0000463 Op0 == Constant::getNullValue(Op0->getType()))
464 return ReplaceInstUsesWith(I, Op0);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000465
Chris Lattnere6794492002-08-12 21:17:25 +0000466 // shl uint X, 32 = 0 and shr ubyte Y, 9 = 0, ... just don't eliminate shr of
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000467 // a signed value.
468 //
469 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(Op1)) {
470 unsigned TypeBits = Op0->getType()->getPrimitiveSize()*8;
471 if (CUI->getValue() >= TypeBits &&
Chris Lattnere6794492002-08-12 21:17:25 +0000472 !(Op0->getType()->isSigned() && I.getOpcode() == Instruction::Shr))
473 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000474 }
475 return 0;
476}
477
478
Chris Lattner0bb75912002-08-14 23:21:10 +0000479// isCIntegral - For the purposes of casting, we allow conversion of sizes and
480// stuff as long as the value type acts basically integral like.
481//
482static bool isCIntegral(const Type *Ty) {
483 return Ty->isIntegral() || Ty == Type::BoolTy;
484}
485
Chris Lattner48a44f72002-05-02 17:06:02 +0000486// isEliminableCastOfCast - Return true if it is valid to eliminate the CI
487// instruction.
488//
Chris Lattner113f4f42002-06-25 16:13:24 +0000489static inline bool isEliminableCastOfCast(const CastInst &CI,
Chris Lattner48a44f72002-05-02 17:06:02 +0000490 const CastInst *CSrc) {
Chris Lattner113f4f42002-06-25 16:13:24 +0000491 assert(CI.getOperand(0) == CSrc);
Chris Lattner48a44f72002-05-02 17:06:02 +0000492 const Type *SrcTy = CSrc->getOperand(0)->getType();
493 const Type *MidTy = CSrc->getType();
Chris Lattner113f4f42002-06-25 16:13:24 +0000494 const Type *DstTy = CI.getType();
Chris Lattner48a44f72002-05-02 17:06:02 +0000495
Chris Lattner650b6da2002-08-02 20:00:25 +0000496 // It is legal to eliminate the instruction if casting A->B->A if the sizes
497 // are identical and the bits don't get reinterpreted (for example
Chris Lattner0bb75912002-08-14 23:21:10 +0000498 // int->float->int would not be allowed)
Chris Lattner650b6da2002-08-02 20:00:25 +0000499 if (SrcTy == DstTy && SrcTy->isLosslesslyConvertableTo(MidTy))
500 return true;
Chris Lattner48a44f72002-05-02 17:06:02 +0000501
502 // Allow free casting and conversion of sizes as long as the sign doesn't
503 // change...
Chris Lattner0bb75912002-08-14 23:21:10 +0000504 if (isCIntegral(SrcTy) && isCIntegral(MidTy) && isCIntegral(DstTy) &&
Chris Lattner650b6da2002-08-02 20:00:25 +0000505 SrcTy->isSigned() == MidTy->isSigned() &&
506 MidTy->isSigned() == DstTy->isSigned()) {
507 // Only accept cases where we are either monotonically increasing the type
508 // size, or monotonically decreasing it.
509 //
510 unsigned SrcSize = SrcTy->getPrimitiveSize();
511 unsigned MidSize = MidTy->getPrimitiveSize();
512 unsigned DstSize = DstTy->getPrimitiveSize();
Chris Lattner0bb75912002-08-14 23:21:10 +0000513 if (SrcSize <= MidSize && MidSize <= DstSize)
Chris Lattner650b6da2002-08-02 20:00:25 +0000514 return true;
515
Chris Lattner0bb75912002-08-14 23:21:10 +0000516 if (SrcSize >= MidSize && MidSize >= DstSize)
Chris Lattner650b6da2002-08-02 20:00:25 +0000517 return true;
518 }
Chris Lattner48a44f72002-05-02 17:06:02 +0000519
520 // Otherwise, we cannot succeed. Specifically we do not want to allow things
521 // like: short -> ushort -> uint, because this can create wrong results if
522 // the input short is negative!
523 //
524 return false;
525}
526
527
528// CastInst simplification
Chris Lattner260ab202002-04-18 17:39:14 +0000529//
Chris Lattner113f4f42002-06-25 16:13:24 +0000530Instruction *InstCombiner::visitCastInst(CastInst &CI) {
Chris Lattner48a44f72002-05-02 17:06:02 +0000531 // If the user is casting a value to the same type, eliminate this cast
532 // instruction...
Chris Lattnere6794492002-08-12 21:17:25 +0000533 if (CI.getType() == CI.getOperand(0)->getType())
534 return ReplaceInstUsesWith(CI, CI.getOperand(0));
Chris Lattner48a44f72002-05-02 17:06:02 +0000535
Chris Lattner48a44f72002-05-02 17:06:02 +0000536 // If casting the result of another cast instruction, try to eliminate this
537 // one!
538 //
Chris Lattner650b6da2002-08-02 20:00:25 +0000539 if (CastInst *CSrc = dyn_cast<CastInst>(CI.getOperand(0))) {
Chris Lattner48a44f72002-05-02 17:06:02 +0000540 if (isEliminableCastOfCast(CI, CSrc)) {
541 // This instruction now refers directly to the cast's src operand. This
542 // has a good chance of making CSrc dead.
Chris Lattner113f4f42002-06-25 16:13:24 +0000543 CI.setOperand(0, CSrc->getOperand(0));
544 return &CI;
Chris Lattner48a44f72002-05-02 17:06:02 +0000545 }
546
Chris Lattner650b6da2002-08-02 20:00:25 +0000547 // If this is an A->B->A cast, and we are dealing with integral types, try
548 // to convert this into a logical 'and' instruction.
549 //
550 if (CSrc->getOperand(0)->getType() == CI.getType() &&
551 CI.getType()->isIntegral() && CSrc->getType()->isIntegral() &&
552 CI.getType()->isUnsigned() && CSrc->getType()->isUnsigned() &&
553 CSrc->getType()->getPrimitiveSize() < CI.getType()->getPrimitiveSize()){
554 assert(CSrc->getType() != Type::ULongTy &&
555 "Cannot have type bigger than ulong!");
556 unsigned AndValue = (1U << CSrc->getType()->getPrimitiveSize()*8)-1;
557 Constant *AndOp = ConstantUInt::get(CI.getType(), AndValue);
558 return BinaryOperator::create(Instruction::And, CSrc->getOperand(0),
559 AndOp);
560 }
561 }
562
Chris Lattner260ab202002-04-18 17:39:14 +0000563 return 0;
Chris Lattnerca081252001-12-14 16:52:21 +0000564}
565
Chris Lattner48a44f72002-05-02 17:06:02 +0000566
Chris Lattnerbbbdd852002-05-06 18:06:38 +0000567// PHINode simplification
568//
Chris Lattner113f4f42002-06-25 16:13:24 +0000569Instruction *InstCombiner::visitPHINode(PHINode &PN) {
Chris Lattnerbbbdd852002-05-06 18:06:38 +0000570 // If the PHI node only has one incoming value, eliminate the PHI node...
Chris Lattnere6794492002-08-12 21:17:25 +0000571 if (PN.getNumIncomingValues() == 1)
572 return ReplaceInstUsesWith(PN, PN.getIncomingValue(0));
Chris Lattnerbbbdd852002-05-06 18:06:38 +0000573
574 return 0;
575}
576
Chris Lattner48a44f72002-05-02 17:06:02 +0000577
Chris Lattner113f4f42002-06-25 16:13:24 +0000578Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
Chris Lattnerae7a0d32002-08-02 19:29:35 +0000579 // Is it 'getelementptr %P, uint 0' or 'getelementptr %P'
Chris Lattner113f4f42002-06-25 16:13:24 +0000580 // If so, eliminate the noop.
Chris Lattnerae7a0d32002-08-02 19:29:35 +0000581 if ((GEP.getNumOperands() == 2 &&
582 GEP.getOperand(1) == Constant::getNullValue(Type::UIntTy)) ||
Chris Lattnere6794492002-08-12 21:17:25 +0000583 GEP.getNumOperands() == 1)
584 return ReplaceInstUsesWith(GEP, GEP.getOperand(0));
Chris Lattner48a44f72002-05-02 17:06:02 +0000585
Chris Lattnerae7a0d32002-08-02 19:29:35 +0000586 // Combine Indices - If the source pointer to this getelementptr instruction
587 // is a getelementptr instruction, combine the indices of the two
588 // getelementptr instructions into a single instruction.
589 //
590 if (GetElementPtrInst *Src =
591 dyn_cast<GetElementPtrInst>(GEP.getPointerOperand())) {
592 std::vector<Value *> Indices;
Chris Lattnerca081252001-12-14 16:52:21 +0000593
Chris Lattnerae7a0d32002-08-02 19:29:35 +0000594 // Can we combine the two pointer arithmetics offsets?
595 if (Src->getNumOperands() == 2 && isa<Constant>(Src->getOperand(1)) &&
596 isa<Constant>(GEP.getOperand(1))) {
597 // Replace the index list on this GEP with the index on the getelementptr
598 Indices.insert(Indices.end(), GEP.idx_begin(), GEP.idx_end());
599 Indices[0] = *cast<Constant>(Src->getOperand(1)) +
600 *cast<Constant>(GEP.getOperand(1));
601 assert(Indices[0] != 0 && "Constant folding of uint's failed!?");
602
603 } else if (*GEP.idx_begin() == ConstantUInt::get(Type::UIntTy, 0)) {
604 // Otherwise we can do the fold if the first index of the GEP is a zero
605 Indices.insert(Indices.end(), Src->idx_begin(), Src->idx_end());
606 Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
607 }
608
609 if (!Indices.empty())
610 return new GetElementPtrInst(Src->getOperand(0), Indices, GEP.getName());
Chris Lattnerca081252001-12-14 16:52:21 +0000611 }
612
Chris Lattnerca081252001-12-14 16:52:21 +0000613 return 0;
614}
615
Chris Lattnerca081252001-12-14 16:52:21 +0000616
Chris Lattner113f4f42002-06-25 16:13:24 +0000617bool InstCombiner::runOnFunction(Function &F) {
Chris Lattner260ab202002-04-18 17:39:14 +0000618 bool Changed = false;
Chris Lattnerca081252001-12-14 16:52:21 +0000619
Chris Lattner260ab202002-04-18 17:39:14 +0000620 WorkList.insert(WorkList.end(), inst_begin(F), inst_end(F));
Chris Lattnerca081252001-12-14 16:52:21 +0000621
622 while (!WorkList.empty()) {
623 Instruction *I = WorkList.back(); // Get an instruction from the worklist
624 WorkList.pop_back();
625
626 // Now that we have an instruction, try combining it to simplify it...
Chris Lattnerae7a0d32002-08-02 19:29:35 +0000627 if (Instruction *Result = visit(*I)) {
Chris Lattner0b18c1d2002-05-10 15:38:35 +0000628 ++NumCombined;
Chris Lattner260ab202002-04-18 17:39:14 +0000629 // Should we replace the old instruction with a new one?
Chris Lattner053c0932002-05-14 15:24:07 +0000630 if (Result != I) {
631 // Instructions can end up on the worklist more than once. Make sure
632 // we do not process an instruction that has been deleted.
Chris Lattnerae7a0d32002-08-02 19:29:35 +0000633 WorkList.erase(std::remove(WorkList.begin(), WorkList.end(), I),
634 WorkList.end());
Chris Lattner053c0932002-05-14 15:24:07 +0000635
Chris Lattner260ab202002-04-18 17:39:14 +0000636 ReplaceInstWithInst(I, Result);
Chris Lattner113f4f42002-06-25 16:13:24 +0000637 } else {
Chris Lattnerae7a0d32002-08-02 19:29:35 +0000638 BasicBlock::iterator II = I;
639
640 // If the instruction was modified, it's possible that it is now dead.
641 // if so, remove it.
642 if (dceInstruction(II)) {
643 // Instructions may end up in the worklist more than once. Erase them
644 // all.
645 WorkList.erase(std::remove(WorkList.begin(), WorkList.end(), I),
646 WorkList.end());
647 Result = 0;
648 }
Chris Lattner053c0932002-05-14 15:24:07 +0000649 }
Chris Lattner260ab202002-04-18 17:39:14 +0000650
Chris Lattnerae7a0d32002-08-02 19:29:35 +0000651 if (Result) {
652 WorkList.push_back(Result);
653 AddUsesToWorkList(*Result);
654 }
Chris Lattner260ab202002-04-18 17:39:14 +0000655 Changed = true;
Chris Lattnerca081252001-12-14 16:52:21 +0000656 }
657 }
658
Chris Lattner260ab202002-04-18 17:39:14 +0000659 return Changed;
Chris Lattner04805fa2002-02-26 21:46:54 +0000660}
661
662Pass *createInstructionCombiningPass() {
Chris Lattner260ab202002-04-18 17:39:14 +0000663 return new InstCombiner();
Chris Lattner04805fa2002-02-26 21:46:54 +0000664}