blob: f652e2bbc712e606eab6163ca57bd6e846369871 [file] [log] [blame]
Chris Lattner233f7dc2002-08-12 21:17:25 +00001//===- InstructionCombining.cpp - Combine multiple instructions -----------===//
Chris Lattner8a2a3112001-12-14 16:52:21 +00002//
3// InstructionCombining - Combine instructions to form fewer, simple
Chris Lattner62b14df2002-09-02 04:59:56 +00004// instructions. This pass does not modify the CFG This pass is where algebraic
5// simplification happens.
Chris Lattner8a2a3112001-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 Lattner022103b2002-05-07 20:03:00 +000017#include "llvm/Transforms/Scalar.h"
Chris Lattner497c60c2002-05-07 18:12:18 +000018#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Chris Lattner90ac28c2002-08-02 19:29:35 +000019#include "llvm/Transforms/Utils/Local.h"
Chris Lattner968ddc92002-04-08 20:18:09 +000020#include "llvm/ConstantHandling.h"
Chris Lattner8a2a3112001-12-14 16:52:21 +000021#include "llvm/iMemory.h"
Chris Lattner8d70cd92002-04-15 19:45:29 +000022#include "llvm/iOther.h"
Chris Lattner473945d2002-05-06 18:06:38 +000023#include "llvm/iPHINode.h"
Chris Lattnerdd841ae2002-04-18 17:39:14 +000024#include "llvm/iOperators.h"
Chris Lattnerbd0ef772002-02-26 21:46:54 +000025#include "llvm/Pass.h"
Chris Lattner0864acf2002-11-04 16:18:53 +000026#include "llvm/DerivedTypes.h"
Chris Lattner221d6882002-02-12 21:07:25 +000027#include "llvm/Support/InstIterator.h"
Chris Lattnerdd841ae2002-04-18 17:39:14 +000028#include "llvm/Support/InstVisitor.h"
Chris Lattnera92f6962002-10-01 22:38:41 +000029#include "Support/Statistic.h"
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +000030#include <algorithm>
Chris Lattner8a2a3112001-12-14 16:52:21 +000031
Chris Lattnerdd841ae2002-04-18 17:39:14 +000032namespace {
Chris Lattnera92f6962002-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 Lattnerf57b8452002-04-27 06:56:12 +000037 class InstCombiner : public FunctionPass,
Chris Lattnerdd841ae2002-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 Lattner7e708292002-06-25 16:13:24 +000042 void AddUsesToWorkList(Instruction &I) {
Chris Lattnerdd841ae2002-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 Lattner7e708292002-06-25 16:13:24 +000046 for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
Chris Lattnerdd841ae2002-04-18 17:39:14 +000047 UI != UE; ++UI)
48 WorkList.push_back(cast<Instruction>(*UI));
49 }
50
Chris Lattner62b14df2002-09-02 04:59:56 +000051 // removeFromWorkList - remove all instances of I from the worklist.
52 void removeFromWorkList(Instruction *I);
Chris Lattnerdd841ae2002-04-18 17:39:14 +000053 public:
Chris Lattner7e708292002-06-25 16:13:24 +000054 virtual bool runOnFunction(Function &F);
Chris Lattnerdd841ae2002-04-18 17:39:14 +000055
Chris Lattner97e52e42002-04-28 21:27:06 +000056 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Chris Lattnercb2610e2002-10-21 20:00:28 +000057 AU.setPreservesCFG();
Chris Lattner97e52e42002-04-28 21:27:06 +000058 }
59
Chris Lattnerdd841ae2002-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 Lattner233f7dc2002-08-12 21:17:25 +000064 // I - Change was made, I is still valid, I may be dead though
Chris Lattnerdd841ae2002-04-18 17:39:14 +000065 // otherwise - Change was made, replace I with returned instruction
66 //
Chris Lattner7e708292002-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);
76 Instruction *visitShiftInst(Instruction &I);
77 Instruction *visitCastInst(CastInst &CI);
78 Instruction *visitPHINode(PHINode &PN);
79 Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
Chris Lattner0864acf2002-11-04 16:18:53 +000080 Instruction *visitAllocationInst(AllocationInst &AI);
Chris Lattnerdd841ae2002-04-18 17:39:14 +000081
82 // visitInstruction - Specify what to return for unhandled instructions...
Chris Lattner7e708292002-06-25 16:13:24 +000083 Instruction *visitInstruction(Instruction &I) { return 0; }
Chris Lattner8b170942002-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 Lattnere6f9a912002-08-23 18:32:43 +000089 assert(New && New->getParent() == 0 &&
90 "New instruction already inserted into a basic block!");
Chris Lattner8b170942002-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 Lattnerdd841ae2002-04-18 17:39:14 +0000107 };
Chris Lattnerf6293092002-07-23 18:06:35 +0000108
Chris Lattnera6275cc2002-07-26 21:12:46 +0000109 RegisterOpt<InstCombiner> X("instcombine", "Combine redundant instructions");
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000110}
111
112
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000113// Make sure that this instruction has a constant on the right hand side if it
114// has any constant arguments. If not, fix it an return true.
115//
Chris Lattner7e708292002-06-25 16:13:24 +0000116static bool SimplifyBinOp(BinaryOperator &I) {
117 if (isa<Constant>(I.getOperand(0)) && !isa<Constant>(I.getOperand(1)))
118 return !I.swapOperands();
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000119 return false;
120}
Chris Lattner8a2a3112001-12-14 16:52:21 +0000121
Chris Lattnerb35dde12002-05-06 16:49:18 +0000122// dyn_castNegInst - Given a 'sub' instruction, return the RHS of the
123// instruction if the LHS is a constant zero (which is the 'negate' form).
124//
125static inline Value *dyn_castNegInst(Value *V) {
Chris Lattnera2881962003-02-18 19:28:33 +0000126 return BinaryOperator::isNeg(V) ?
127 BinaryOperator::getNegArgument(cast<BinaryOperator>(V)) : 0;
Chris Lattnerb35dde12002-05-06 16:49:18 +0000128}
129
Chris Lattneraf2930e2002-08-14 17:51:49 +0000130static inline Value *dyn_castNotInst(Value *V) {
Chris Lattnera2881962003-02-18 19:28:33 +0000131 return BinaryOperator::isNot(V) ?
132 BinaryOperator::getNotArgument(cast<BinaryOperator>(V)) : 0;
133}
Chris Lattneraf2930e2002-08-14 17:51:49 +0000134
Chris Lattnera2881962003-02-18 19:28:33 +0000135
136// Log2 - Calculate the log base 2 for the specified value if it is exactly a
137// power of 2.
138static unsigned Log2(uint64_t Val) {
139 assert(Val > 1 && "Values 0 and 1 should be handled elsewhere!");
140 unsigned Count = 0;
141 while (Val != 1) {
142 if (Val & 1) return 0; // Multiple bits set?
143 Val >>= 1;
144 ++Count;
145 }
146 return Count;
Chris Lattneraf2930e2002-08-14 17:51:49 +0000147}
148
Chris Lattnerad3448c2003-02-18 19:57:07 +0000149static inline Value *dyn_castFoldableMul(Value *V) {
150 if (V->use_size() == 1 && V->getType()->isInteger())
151 if (Instruction *I = dyn_cast<Instruction>(V))
152 if (I->getOpcode() == Instruction::Mul)
153 if (isa<Constant>(I->getOperand(1)))
154 return I->getOperand(0);
155 return 0;
156}
157
158
Chris Lattner7e708292002-06-25 16:13:24 +0000159Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000160 bool Changed = SimplifyBinOp(I);
Chris Lattner7e708292002-06-25 16:13:24 +0000161 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
Chris Lattnerb35dde12002-05-06 16:49:18 +0000162
163 // Eliminate 'add int %X, 0'
Chris Lattner233f7dc2002-08-12 21:17:25 +0000164 if (RHS == Constant::getNullValue(I.getType()))
165 return ReplaceInstUsesWith(I, LHS);
Chris Lattnerb35dde12002-05-06 16:49:18 +0000166
Chris Lattner5c4afb92002-05-08 22:46:53 +0000167 // -A + B --> B - A
Chris Lattnerb35dde12002-05-06 16:49:18 +0000168 if (Value *V = dyn_castNegInst(LHS))
Chris Lattner5c4afb92002-05-08 22:46:53 +0000169 return BinaryOperator::create(Instruction::Sub, RHS, V);
Chris Lattnerb35dde12002-05-06 16:49:18 +0000170
171 // A + -B --> A - B
172 if (Value *V = dyn_castNegInst(RHS))
Chris Lattner5c4afb92002-05-08 22:46:53 +0000173 return BinaryOperator::create(Instruction::Sub, LHS, V);
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000174
175 // Simplify add instructions with a constant RHS...
Chris Lattnerb35dde12002-05-06 16:49:18 +0000176 if (Constant *Op2 = dyn_cast<Constant>(RHS)) {
177 if (BinaryOperator *ILHS = dyn_cast<BinaryOperator>(LHS)) {
178 if (ILHS->getOpcode() == Instruction::Add &&
179 isa<Constant>(ILHS->getOperand(1))) {
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000180 // Fold:
181 // %Y = add int %X, 1
182 // %Z = add int %Y, 1
183 // into:
184 // %Z = add int %X, 2
185 //
Chris Lattnerb35dde12002-05-06 16:49:18 +0000186 if (Constant *Val = *Op2 + *cast<Constant>(ILHS->getOperand(1))) {
Chris Lattner7e708292002-06-25 16:13:24 +0000187 I.setOperand(0, ILHS->getOperand(0));
188 I.setOperand(1, Val);
189 return &I;
Chris Lattnerbd0ef772002-02-26 21:46:54 +0000190 }
Chris Lattner8a2a3112001-12-14 16:52:21 +0000191 }
192 }
Chris Lattner8a2a3112001-12-14 16:52:21 +0000193 }
194
Chris Lattnerad3448c2003-02-18 19:57:07 +0000195 // X*C + X --> X * (C+1)
196 if (dyn_castFoldableMul(LHS) == RHS) {
197 Constant *CP1 = *cast<Constant>(cast<Instruction>(LHS)->getOperand(1)) +
198 *ConstantInt::get(I.getType(), 1);
199 assert(CP1 && "Couldn't constant fold C + 1?");
200 return BinaryOperator::create(Instruction::Mul, RHS, CP1);
201 }
202
203 // X + X*C --> X * (C+1)
204 if (dyn_castFoldableMul(RHS) == LHS) {
205 Constant *CP1 = *cast<Constant>(cast<Instruction>(RHS)->getOperand(1)) +
206 *ConstantInt::get(I.getType(), 1);
207 assert(CP1 && "Couldn't constant fold C + 1?");
208 return BinaryOperator::create(Instruction::Mul, LHS, CP1);
209 }
210
Chris Lattner7e708292002-06-25 16:13:24 +0000211 return Changed ? &I : 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000212}
213
Chris Lattner7e708292002-06-25 16:13:24 +0000214Instruction *InstCombiner::visitSub(BinaryOperator &I) {
Chris Lattner7e708292002-06-25 16:13:24 +0000215 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +0000216
Chris Lattner233f7dc2002-08-12 21:17:25 +0000217 if (Op0 == Op1) // sub X, X -> 0
218 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000219
220 // If this is a subtract instruction with a constant RHS, convert it to an add
221 // instruction of a negative constant
222 //
Chris Lattner3f5b8772002-05-06 16:14:14 +0000223 if (Constant *Op2 = dyn_cast<Constant>(Op1))
Chris Lattner7e708292002-06-25 16:13:24 +0000224 if (Constant *RHS = *Constant::getNullValue(I.getType()) - *Op2) // 0 - RHS
225 return BinaryOperator::create(Instruction::Add, Op0, RHS, I.getName());
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000226
Chris Lattner233f7dc2002-08-12 21:17:25 +0000227 // If this is a 'B = x-(-A)', change to B = x+A...
Chris Lattner5c4afb92002-05-08 22:46:53 +0000228 if (Value *V = dyn_castNegInst(Op1))
229 return BinaryOperator::create(Instruction::Add, Op0, V);
Chris Lattnerb35dde12002-05-06 16:49:18 +0000230
Chris Lattnera2881962003-02-18 19:28:33 +0000231 // Replace (-1 - A) with (~A)...
232 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0))
233 if (C->isAllOnesValue())
234 return BinaryOperator::createNot(Op1);
Chris Lattner40371712002-05-09 01:29:19 +0000235
Chris Lattnera2881962003-02-18 19:28:33 +0000236 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1))
237 if (Op1I->use_size() == 1) {
238 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
239 // is not used by anyone else...
240 //
241 if (Op1I->getOpcode() == Instruction::Sub) {
242 // Swap the two operands of the subexpr...
243 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
244 Op1I->setOperand(0, IIOp1);
245 Op1I->setOperand(1, IIOp0);
246
247 // Create the new top level add instruction...
248 return BinaryOperator::create(Instruction::Add, Op0, Op1);
249 }
250
251 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
252 //
253 if (Op1I->getOpcode() == Instruction::And &&
254 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
255 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
256
257 Instruction *NewNot = BinaryOperator::createNot(OtherOp, "B.not", &I);
258 return BinaryOperator::create(Instruction::And, Op0, NewNot);
259 }
Chris Lattnerad3448c2003-02-18 19:57:07 +0000260
261 // X - X*C --> X * (1-C)
262 if (dyn_castFoldableMul(Op1I) == Op0) {
263 Constant *CP1 = *ConstantInt::get(I.getType(), 1) -
264 *cast<Constant>(cast<Instruction>(Op1)->getOperand(1));
265 assert(CP1 && "Couldn't constant fold 1-C?");
266 return BinaryOperator::create(Instruction::Mul, Op0, CP1);
267 }
Chris Lattner40371712002-05-09 01:29:19 +0000268 }
Chris Lattnera2881962003-02-18 19:28:33 +0000269
Chris Lattnerad3448c2003-02-18 19:57:07 +0000270 // X*C - X --> X * (C-1)
271 if (dyn_castFoldableMul(Op0) == Op1) {
272 Constant *CP1 = *cast<Constant>(cast<Instruction>(Op0)->getOperand(1)) -
273 *ConstantInt::get(I.getType(), 1);
274 assert(CP1 && "Couldn't constant fold C - 1?");
275 return BinaryOperator::create(Instruction::Mul, Op1, CP1);
276 }
277
Chris Lattner3f5b8772002-05-06 16:14:14 +0000278 return 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000279}
280
Chris Lattner7e708292002-06-25 16:13:24 +0000281Instruction *InstCombiner::visitMul(BinaryOperator &I) {
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000282 bool Changed = SimplifyBinOp(I);
Chris Lattnera2881962003-02-18 19:28:33 +0000283 Value *Op0 = I.getOperand(0);
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000284
Chris Lattner233f7dc2002-08-12 21:17:25 +0000285 // Simplify mul instructions with a constant RHS...
Chris Lattnera2881962003-02-18 19:28:33 +0000286 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
287 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
288 const Type *Ty = CI->getType();
289 uint64_t Val = Ty->isSigned() ?
290 (uint64_t)cast<ConstantSInt>(CI)->getValue() :
291 cast<ConstantUInt>(CI)->getValue();
292 switch (Val) {
293 case 0:
294 return ReplaceInstUsesWith(I, Op1); // Eliminate 'mul double %X, 0'
295 case 1:
296 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul int %X, 1'
297 case 2: // Convert 'mul int %X, 2' to 'add int %X, %X'
298 return BinaryOperator::create(Instruction::Add, Op0, Op0, I.getName());
299 }
Chris Lattner6c1ce212002-04-29 22:24:47 +0000300
Chris Lattnera2881962003-02-18 19:28:33 +0000301 if (uint64_t C = Log2(Val)) // Replace X*(2^C) with X << C
302 return new ShiftInst(Instruction::Shl, Op0,
303 ConstantUInt::get(Type::UByteTy, C));
304 } else {
305 ConstantFP *Op1F = cast<ConstantFP>(Op1);
306 if (Op1F->isNullValue())
307 return ReplaceInstUsesWith(I, Op1);
Chris Lattner6c1ce212002-04-29 22:24:47 +0000308
Chris Lattnera2881962003-02-18 19:28:33 +0000309 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
310 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
311 if (Op1F->getValue() == 1.0)
312 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0'
313 }
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000314 }
315
Chris Lattner7e708292002-06-25 16:13:24 +0000316 return Changed ? &I : 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000317}
318
Chris Lattner7e708292002-06-25 16:13:24 +0000319Instruction *InstCombiner::visitDiv(BinaryOperator &I) {
Chris Lattner3f5b8772002-05-06 16:14:14 +0000320 // div X, 1 == X
Chris Lattnera2881962003-02-18 19:28:33 +0000321 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I.getOperand(1))) {
Chris Lattner233f7dc2002-08-12 21:17:25 +0000322 if (RHS->equalsInt(1))
323 return ReplaceInstUsesWith(I, I.getOperand(0));
Chris Lattnera2881962003-02-18 19:28:33 +0000324
325 // Check to see if this is an unsigned division with an exact power of 2,
326 // if so, convert to a right shift.
327 if (ConstantUInt *C = dyn_cast<ConstantUInt>(RHS))
328 if (uint64_t Val = C->getValue()) // Don't break X / 0
329 if (uint64_t C = Log2(Val))
330 return new ShiftInst(Instruction::Shr, I.getOperand(0),
331 ConstantUInt::get(Type::UByteTy, C));
332 }
333
334 // 0 / X == 0, we don't need to preserve faults!
335 if (ConstantInt *LHS = dyn_cast<ConstantInt>(I.getOperand(0)))
336 if (LHS->equalsInt(0))
337 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
338
Chris Lattner3f5b8772002-05-06 16:14:14 +0000339 return 0;
340}
341
342
Chris Lattner7e708292002-06-25 16:13:24 +0000343Instruction *InstCombiner::visitRem(BinaryOperator &I) {
Chris Lattnera2881962003-02-18 19:28:33 +0000344 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I.getOperand(1))) {
345 if (RHS->equalsInt(1)) // X % 1 == 0
346 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
347
348 // Check to see if this is an unsigned remainder with an exact power of 2,
349 // if so, convert to a bitwise and.
350 if (ConstantUInt *C = dyn_cast<ConstantUInt>(RHS))
351 if (uint64_t Val = C->getValue()) // Don't break X % 0 (divide by zero)
352 if (Log2(Val))
353 return BinaryOperator::create(Instruction::And, I.getOperand(0),
354 ConstantUInt::get(I.getType(), Val-1));
355 }
356
357 // 0 % X == 0, we don't need to preserve faults!
358 if (ConstantInt *LHS = dyn_cast<ConstantInt>(I.getOperand(0)))
359 if (LHS->equalsInt(0))
Chris Lattner233f7dc2002-08-12 21:17:25 +0000360 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
361
Chris Lattner3f5b8772002-05-06 16:14:14 +0000362 return 0;
363}
364
Chris Lattner8b170942002-08-09 23:47:40 +0000365// isMaxValueMinusOne - return true if this is Max-1
Chris Lattner233f7dc2002-08-12 21:17:25 +0000366static bool isMaxValueMinusOne(const ConstantInt *C) {
Chris Lattner8b170942002-08-09 23:47:40 +0000367 if (const ConstantUInt *CU = dyn_cast<ConstantUInt>(C)) {
368 // Calculate -1 casted to the right type...
369 unsigned TypeBits = C->getType()->getPrimitiveSize()*8;
370 uint64_t Val = ~0ULL; // All ones
371 Val >>= 64-TypeBits; // Shift out unwanted 1 bits...
372 return CU->getValue() == Val-1;
373 }
374
375 const ConstantSInt *CS = cast<ConstantSInt>(C);
376
377 // Calculate 0111111111..11111
378 unsigned TypeBits = C->getType()->getPrimitiveSize()*8;
379 int64_t Val = INT64_MAX; // All ones
380 Val >>= 64-TypeBits; // Shift out unwanted 1 bits...
381 return CS->getValue() == Val-1;
382}
383
384// isMinValuePlusOne - return true if this is Min+1
Chris Lattner233f7dc2002-08-12 21:17:25 +0000385static bool isMinValuePlusOne(const ConstantInt *C) {
Chris Lattner8b170942002-08-09 23:47:40 +0000386 if (const ConstantUInt *CU = dyn_cast<ConstantUInt>(C))
387 return CU->getValue() == 1;
388
389 const ConstantSInt *CS = cast<ConstantSInt>(C);
390
391 // Calculate 1111111111000000000000
392 unsigned TypeBits = C->getType()->getPrimitiveSize()*8;
393 int64_t Val = -1; // All ones
394 Val <<= TypeBits-1; // Shift over to the right spot
395 return CS->getValue() == Val+1;
396}
397
398
Chris Lattner7e708292002-06-25 16:13:24 +0000399Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
Chris Lattner3f5b8772002-05-06 16:14:14 +0000400 bool Changed = SimplifyBinOp(I);
Chris Lattner7e708292002-06-25 16:13:24 +0000401 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +0000402
403 // and X, X = X and X, 0 == 0
Chris Lattner233f7dc2002-08-12 21:17:25 +0000404 if (Op0 == Op1 || Op1 == Constant::getNullValue(I.getType()))
405 return ReplaceInstUsesWith(I, Op1);
Chris Lattner3f5b8772002-05-06 16:14:14 +0000406
407 // and X, -1 == X
Chris Lattner572f4a02002-08-13 17:50:24 +0000408 if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1))
Chris Lattner233f7dc2002-08-12 21:17:25 +0000409 if (RHS->isAllOnesValue())
410 return ReplaceInstUsesWith(I, Op0);
Chris Lattner3f5b8772002-05-06 16:14:14 +0000411
Chris Lattnera2881962003-02-18 19:28:33 +0000412 Value *Op0NotVal = dyn_castNotInst(Op0);
413 Value *Op1NotVal = dyn_castNotInst(Op1);
414
415 // (~A & ~B) == (~(A | B)) - Demorgan's Law
416 if (Op0->use_size() == 1 && Op1->use_size() == 1 && Op0NotVal && Op1NotVal) {
417 Instruction *Or = BinaryOperator::create(Instruction::Or, Op0NotVal,
418 Op1NotVal,I.getName()+".demorgan",
419 &I);
420 return BinaryOperator::createNot(Or);
421 }
422
423 if (Op0NotVal == Op1 || Op1NotVal == Op0) // A & ~A == ~A & A == 0
424 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnere6f9a912002-08-23 18:32:43 +0000425
Chris Lattner7e708292002-06-25 16:13:24 +0000426 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +0000427}
428
429
430
Chris Lattner7e708292002-06-25 16:13:24 +0000431Instruction *InstCombiner::visitOr(BinaryOperator &I) {
Chris Lattner3f5b8772002-05-06 16:14:14 +0000432 bool Changed = SimplifyBinOp(I);
Chris Lattner7e708292002-06-25 16:13:24 +0000433 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +0000434
435 // or X, X = X or X, 0 == X
Chris Lattner233f7dc2002-08-12 21:17:25 +0000436 if (Op0 == Op1 || Op1 == Constant::getNullValue(I.getType()))
437 return ReplaceInstUsesWith(I, Op0);
Chris Lattner3f5b8772002-05-06 16:14:14 +0000438
439 // or X, -1 == -1
Chris Lattner572f4a02002-08-13 17:50:24 +0000440 if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1))
Chris Lattner233f7dc2002-08-12 21:17:25 +0000441 if (RHS->isAllOnesValue())
442 return ReplaceInstUsesWith(I, Op1);
Chris Lattner3f5b8772002-05-06 16:14:14 +0000443
Chris Lattnera2881962003-02-18 19:28:33 +0000444 if (Value *X = dyn_castNotInst(Op0)) // ~A | A == -1
445 if (X == Op1)
446 return ReplaceInstUsesWith(I,
447 ConstantIntegral::getAllOnesValue(I.getType()));
448
449 if (Value *X = dyn_castNotInst(Op1)) // A | ~A == -1
450 if (X == Op0)
451 return ReplaceInstUsesWith(I,
452 ConstantIntegral::getAllOnesValue(I.getType()));
453
Chris Lattner7e708292002-06-25 16:13:24 +0000454 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +0000455}
456
457
458
Chris Lattner7e708292002-06-25 16:13:24 +0000459Instruction *InstCombiner::visitXor(BinaryOperator &I) {
Chris Lattner3f5b8772002-05-06 16:14:14 +0000460 bool Changed = SimplifyBinOp(I);
Chris Lattner7e708292002-06-25 16:13:24 +0000461 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +0000462
463 // xor X, X = 0
Chris Lattner233f7dc2002-08-12 21:17:25 +0000464 if (Op0 == Op1)
465 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner3f5b8772002-05-06 16:14:14 +0000466
Chris Lattner572f4a02002-08-13 17:50:24 +0000467 if (ConstantIntegral *Op1C = dyn_cast<ConstantIntegral>(Op1)) {
Chris Lattner8b170942002-08-09 23:47:40 +0000468 // xor X, 0 == X
Chris Lattner233f7dc2002-08-12 21:17:25 +0000469 if (Op1C->isNullValue())
470 return ReplaceInstUsesWith(I, Op0);
Chris Lattner8b170942002-08-09 23:47:40 +0000471
Chris Lattner05bd1b22002-08-20 18:24:26 +0000472 // Is this a "NOT" instruction?
473 if (Op1C->isAllOnesValue()) {
474 // xor (xor X, -1), -1 = not (not X) = X
Chris Lattneraf2930e2002-08-14 17:51:49 +0000475 if (Value *X = dyn_castNotInst(Op0))
476 return ReplaceInstUsesWith(I, X);
Chris Lattner05bd1b22002-08-20 18:24:26 +0000477
478 // xor (setcc A, B), true = not (setcc A, B) = setncc A, B
479 if (SetCondInst *SCI = dyn_cast<SetCondInst>(Op0))
480 if (SCI->use_size() == 1)
481 return new SetCondInst(SCI->getInverseCondition(),
482 SCI->getOperand(0), SCI->getOperand(1));
483 }
Chris Lattner3f5b8772002-05-06 16:14:14 +0000484 }
485
Chris Lattnera2881962003-02-18 19:28:33 +0000486 if (Value *X = dyn_castNotInst(Op0)) // ~A ^ A == -1
487 if (X == Op1)
488 return ReplaceInstUsesWith(I,
489 ConstantIntegral::getAllOnesValue(I.getType()));
490
491 if (Value *X = dyn_castNotInst(Op1)) // A ^ ~A == -1
492 if (X == Op0)
493 return ReplaceInstUsesWith(I,
494 ConstantIntegral::getAllOnesValue(I.getType()));
495
Chris Lattner7e708292002-06-25 16:13:24 +0000496 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +0000497}
498
Chris Lattner8b170942002-08-09 23:47:40 +0000499// AddOne, SubOne - Add or subtract a constant one from an integer constant...
500static Constant *AddOne(ConstantInt *C) {
501 Constant *Result = *C + *ConstantInt::get(C->getType(), 1);
502 assert(Result && "Constant folding integer addition failed!");
503 return Result;
504}
505static Constant *SubOne(ConstantInt *C) {
506 Constant *Result = *C - *ConstantInt::get(C->getType(), 1);
507 assert(Result && "Constant folding integer addition failed!");
508 return Result;
509}
510
Chris Lattner53a5b572002-05-09 20:11:54 +0000511// isTrueWhenEqual - Return true if the specified setcondinst instruction is
512// true when both operands are equal...
513//
Chris Lattner7e708292002-06-25 16:13:24 +0000514static bool isTrueWhenEqual(Instruction &I) {
515 return I.getOpcode() == Instruction::SetEQ ||
516 I.getOpcode() == Instruction::SetGE ||
517 I.getOpcode() == Instruction::SetLE;
Chris Lattner53a5b572002-05-09 20:11:54 +0000518}
519
Chris Lattner7e708292002-06-25 16:13:24 +0000520Instruction *InstCombiner::visitSetCondInst(BinaryOperator &I) {
Chris Lattner3f5b8772002-05-06 16:14:14 +0000521 bool Changed = SimplifyBinOp(I);
Chris Lattner8b170942002-08-09 23:47:40 +0000522 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
523 const Type *Ty = Op0->getType();
Chris Lattner3f5b8772002-05-06 16:14:14 +0000524
525 // setcc X, X
Chris Lattner8b170942002-08-09 23:47:40 +0000526 if (Op0 == Op1)
527 return ReplaceInstUsesWith(I, ConstantBool::get(isTrueWhenEqual(I)));
Chris Lattner53a5b572002-05-09 20:11:54 +0000528
529 // setcc <global*>, 0 - Global value addresses are never null!
Chris Lattner8b170942002-08-09 23:47:40 +0000530 if (isa<GlobalValue>(Op0) && isa<ConstantPointerNull>(Op1))
531 return ReplaceInstUsesWith(I, ConstantBool::get(!isTrueWhenEqual(I)));
532
533 // setcc's with boolean values can always be turned into bitwise operations
534 if (Ty == Type::BoolTy) {
535 // If this is <, >, or !=, we can change this into a simple xor instruction
536 if (!isTrueWhenEqual(I))
537 return BinaryOperator::create(Instruction::Xor, Op0, Op1, I.getName());
538
539 // Otherwise we need to make a temporary intermediate instruction and insert
540 // it into the instruction stream. This is what we are after:
541 //
542 // seteq bool %A, %B -> ~(A^B)
543 // setle bool %A, %B -> ~A | B
544 // setge bool %A, %B -> A | ~B
545 //
546 if (I.getOpcode() == Instruction::SetEQ) { // seteq case
547 Instruction *Xor = BinaryOperator::create(Instruction::Xor, Op0, Op1,
548 I.getName()+"tmp");
549 InsertNewInstBefore(Xor, I);
Chris Lattneraf2930e2002-08-14 17:51:49 +0000550 return BinaryOperator::createNot(Xor, I.getName());
Chris Lattner8b170942002-08-09 23:47:40 +0000551 }
552
553 // Handle the setXe cases...
554 assert(I.getOpcode() == Instruction::SetGE ||
555 I.getOpcode() == Instruction::SetLE);
556
557 if (I.getOpcode() == Instruction::SetGE)
558 std::swap(Op0, Op1); // Change setge -> setle
559
560 // Now we just have the SetLE case.
Chris Lattneraf2930e2002-08-14 17:51:49 +0000561 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
Chris Lattner8b170942002-08-09 23:47:40 +0000562 InsertNewInstBefore(Not, I);
563 return BinaryOperator::create(Instruction::Or, Not, Op1, I.getName());
564 }
565
566 // Check to see if we are doing one of many comparisons against constant
567 // integers at the end of their ranges...
568 //
569 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
570 // Check to see if we are comparing against the minimum or maximum value...
Chris Lattner233f7dc2002-08-12 21:17:25 +0000571 if (CI->isMinValue()) {
Chris Lattner8b170942002-08-09 23:47:40 +0000572 if (I.getOpcode() == Instruction::SetLT) // A < MIN -> FALSE
573 return ReplaceInstUsesWith(I, ConstantBool::False);
574 if (I.getOpcode() == Instruction::SetGE) // A >= MIN -> TRUE
575 return ReplaceInstUsesWith(I, ConstantBool::True);
576 if (I.getOpcode() == Instruction::SetLE) // A <= MIN -> A == MIN
577 return BinaryOperator::create(Instruction::SetEQ, Op0,Op1, I.getName());
578 if (I.getOpcode() == Instruction::SetGT) // A > MIN -> A != MIN
579 return BinaryOperator::create(Instruction::SetNE, Op0,Op1, I.getName());
580
Chris Lattner233f7dc2002-08-12 21:17:25 +0000581 } else if (CI->isMaxValue()) {
Chris Lattner8b170942002-08-09 23:47:40 +0000582 if (I.getOpcode() == Instruction::SetGT) // A > MAX -> FALSE
583 return ReplaceInstUsesWith(I, ConstantBool::False);
584 if (I.getOpcode() == Instruction::SetLE) // A <= MAX -> TRUE
585 return ReplaceInstUsesWith(I, ConstantBool::True);
586 if (I.getOpcode() == Instruction::SetGE) // A >= MAX -> A == MAX
587 return BinaryOperator::create(Instruction::SetEQ, Op0,Op1, I.getName());
588 if (I.getOpcode() == Instruction::SetLT) // A < MAX -> A != MAX
589 return BinaryOperator::create(Instruction::SetNE, Op0,Op1, I.getName());
590
591 // Comparing against a value really close to min or max?
592 } else if (isMinValuePlusOne(CI)) {
593 if (I.getOpcode() == Instruction::SetLT) // A < MIN+1 -> A == MIN
594 return BinaryOperator::create(Instruction::SetEQ, Op0,
595 SubOne(CI), I.getName());
596 if (I.getOpcode() == Instruction::SetGE) // A >= MIN-1 -> A != MIN
597 return BinaryOperator::create(Instruction::SetNE, Op0,
598 SubOne(CI), I.getName());
599
600 } else if (isMaxValueMinusOne(CI)) {
601 if (I.getOpcode() == Instruction::SetGT) // A > MAX-1 -> A == MAX
602 return BinaryOperator::create(Instruction::SetEQ, Op0,
603 AddOne(CI), I.getName());
604 if (I.getOpcode() == Instruction::SetLE) // A <= MAX-1 -> A != MAX
605 return BinaryOperator::create(Instruction::SetNE, Op0,
606 AddOne(CI), I.getName());
607 }
Chris Lattner3f5b8772002-05-06 16:14:14 +0000608 }
609
Chris Lattner7e708292002-06-25 16:13:24 +0000610 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +0000611}
612
613
614
Chris Lattner7e708292002-06-25 16:13:24 +0000615Instruction *InstCombiner::visitShiftInst(Instruction &I) {
Chris Lattner7e708292002-06-25 16:13:24 +0000616 assert(I.getOperand(1)->getType() == Type::UByteTy);
617 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +0000618
619 // shl X, 0 == X and shr X, 0 == X
620 // shl 0, X == 0 and shr 0, X == 0
621 if (Op1 == Constant::getNullValue(Type::UByteTy) ||
Chris Lattner233f7dc2002-08-12 21:17:25 +0000622 Op0 == Constant::getNullValue(Op0->getType()))
623 return ReplaceInstUsesWith(I, Op0);
Chris Lattner3f5b8772002-05-06 16:14:14 +0000624
Chris Lattner233f7dc2002-08-12 21:17:25 +0000625 // shl uint X, 32 = 0 and shr ubyte Y, 9 = 0, ... just don't eliminate shr of
Chris Lattner3f5b8772002-05-06 16:14:14 +0000626 // a signed value.
627 //
628 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(Op1)) {
Chris Lattnerf2836082002-09-10 23:04:09 +0000629 if (I.getOpcode() == Instruction::Shr) {
630 unsigned TypeBits = Op0->getType()->getPrimitiveSize()*8;
631 if (CUI->getValue() >= TypeBits && !(Op0->getType()->isSigned()))
632 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
633 }
634
635 // Check to see if we are shifting left by 1. If so, turn it into an add
636 // instruction.
637 if (I.getOpcode() == Instruction::Shl && CUI->equalsInt(1))
Chris Lattnera2881962003-02-18 19:28:33 +0000638 // Convert 'shl int %X, 1' to 'add int %X, %X'
Chris Lattnerf2836082002-09-10 23:04:09 +0000639 return BinaryOperator::create(Instruction::Add, Op0, Op0, I.getName());
640
Chris Lattner3f5b8772002-05-06 16:14:14 +0000641 }
Chris Lattner6eaeb572002-10-08 16:16:40 +0000642
643 // shr int -1, X = -1 (for any arithmetic shift rights of ~0)
644 if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(Op0))
645 if (I.getOpcode() == Instruction::Shr && CSI->isAllOnesValue())
646 return ReplaceInstUsesWith(I, CSI);
647
Chris Lattner3f5b8772002-05-06 16:14:14 +0000648 return 0;
649}
650
651
Chris Lattnera1be5662002-05-02 17:06:02 +0000652// isEliminableCastOfCast - Return true if it is valid to eliminate the CI
653// instruction.
654//
Chris Lattner7e708292002-06-25 16:13:24 +0000655static inline bool isEliminableCastOfCast(const CastInst &CI,
Chris Lattnera1be5662002-05-02 17:06:02 +0000656 const CastInst *CSrc) {
Chris Lattner7e708292002-06-25 16:13:24 +0000657 assert(CI.getOperand(0) == CSrc);
Chris Lattnera1be5662002-05-02 17:06:02 +0000658 const Type *SrcTy = CSrc->getOperand(0)->getType();
659 const Type *MidTy = CSrc->getType();
Chris Lattner7e708292002-06-25 16:13:24 +0000660 const Type *DstTy = CI.getType();
Chris Lattnera1be5662002-05-02 17:06:02 +0000661
Chris Lattner8fd217c2002-08-02 20:00:25 +0000662 // It is legal to eliminate the instruction if casting A->B->A if the sizes
663 // are identical and the bits don't get reinterpreted (for example
Chris Lattner5cf6f112002-08-14 23:21:10 +0000664 // int->float->int would not be allowed)
Chris Lattner8fd217c2002-08-02 20:00:25 +0000665 if (SrcTy == DstTy && SrcTy->isLosslesslyConvertableTo(MidTy))
666 return true;
Chris Lattnera1be5662002-05-02 17:06:02 +0000667
668 // Allow free casting and conversion of sizes as long as the sign doesn't
669 // change...
Chris Lattner0c4e8862002-09-03 01:08:28 +0000670 if (SrcTy->isIntegral() && MidTy->isIntegral() && DstTy->isIntegral()) {
Chris Lattner8fd217c2002-08-02 20:00:25 +0000671 unsigned SrcSize = SrcTy->getPrimitiveSize();
672 unsigned MidSize = MidTy->getPrimitiveSize();
673 unsigned DstSize = DstTy->getPrimitiveSize();
Chris Lattner8fd217c2002-08-02 20:00:25 +0000674
Chris Lattner3ecce662002-08-15 16:15:25 +0000675 // Cases where we are monotonically decreasing the size of the type are
676 // always ok, regardless of what sign changes are going on.
677 //
Chris Lattner5cf6f112002-08-14 23:21:10 +0000678 if (SrcSize >= MidSize && MidSize >= DstSize)
Chris Lattner8fd217c2002-08-02 20:00:25 +0000679 return true;
Chris Lattner3ecce662002-08-15 16:15:25 +0000680
Chris Lattnerd06451f2002-09-23 23:39:43 +0000681 // Cases where the source and destination type are the same, but the middle
682 // type is bigger are noops.
683 //
684 if (SrcSize == DstSize && MidSize > SrcSize)
685 return true;
686
Chris Lattner3ecce662002-08-15 16:15:25 +0000687 // If we are monotonically growing, things are more complex.
688 //
689 if (SrcSize <= MidSize && MidSize <= DstSize) {
690 // We have eight combinations of signedness to worry about. Here's the
691 // table:
692 static const int SignTable[8] = {
693 // CODE, SrcSigned, MidSigned, DstSigned, Comment
694 1, // U U U Always ok
695 1, // U U S Always ok
696 3, // U S U Ok iff SrcSize != MidSize
697 3, // U S S Ok iff SrcSize != MidSize
698 0, // S U U Never ok
699 2, // S U S Ok iff MidSize == DstSize
700 1, // S S U Always ok
701 1, // S S S Always ok
702 };
703
704 // Choose an action based on the current entry of the signtable that this
705 // cast of cast refers to...
706 unsigned Row = SrcTy->isSigned()*4+MidTy->isSigned()*2+DstTy->isSigned();
707 switch (SignTable[Row]) {
708 case 0: return false; // Never ok
709 case 1: return true; // Always ok
710 case 2: return MidSize == DstSize; // Ok iff MidSize == DstSize
711 case 3: // Ok iff SrcSize != MidSize
712 return SrcSize != MidSize || SrcTy == Type::BoolTy;
713 default: assert(0 && "Bad entry in sign table!");
714 }
Chris Lattner3ecce662002-08-15 16:15:25 +0000715 }
Chris Lattner8fd217c2002-08-02 20:00:25 +0000716 }
Chris Lattnera1be5662002-05-02 17:06:02 +0000717
718 // Otherwise, we cannot succeed. Specifically we do not want to allow things
719 // like: short -> ushort -> uint, because this can create wrong results if
720 // the input short is negative!
721 //
722 return false;
723}
724
725
726// CastInst simplification
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000727//
Chris Lattner7e708292002-06-25 16:13:24 +0000728Instruction *InstCombiner::visitCastInst(CastInst &CI) {
Chris Lattnera1be5662002-05-02 17:06:02 +0000729 // If the user is casting a value to the same type, eliminate this cast
730 // instruction...
Chris Lattner233f7dc2002-08-12 21:17:25 +0000731 if (CI.getType() == CI.getOperand(0)->getType())
732 return ReplaceInstUsesWith(CI, CI.getOperand(0));
Chris Lattnera1be5662002-05-02 17:06:02 +0000733
Chris Lattnera1be5662002-05-02 17:06:02 +0000734 // If casting the result of another cast instruction, try to eliminate this
735 // one!
736 //
Chris Lattner8fd217c2002-08-02 20:00:25 +0000737 if (CastInst *CSrc = dyn_cast<CastInst>(CI.getOperand(0))) {
Chris Lattnera1be5662002-05-02 17:06:02 +0000738 if (isEliminableCastOfCast(CI, CSrc)) {
739 // This instruction now refers directly to the cast's src operand. This
740 // has a good chance of making CSrc dead.
Chris Lattner7e708292002-06-25 16:13:24 +0000741 CI.setOperand(0, CSrc->getOperand(0));
742 return &CI;
Chris Lattnera1be5662002-05-02 17:06:02 +0000743 }
744
Chris Lattner8fd217c2002-08-02 20:00:25 +0000745 // If this is an A->B->A cast, and we are dealing with integral types, try
746 // to convert this into a logical 'and' instruction.
747 //
748 if (CSrc->getOperand(0)->getType() == CI.getType() &&
Chris Lattner0c4e8862002-09-03 01:08:28 +0000749 CI.getType()->isInteger() && CSrc->getType()->isInteger() &&
Chris Lattner8fd217c2002-08-02 20:00:25 +0000750 CI.getType()->isUnsigned() && CSrc->getType()->isUnsigned() &&
751 CSrc->getType()->getPrimitiveSize() < CI.getType()->getPrimitiveSize()){
752 assert(CSrc->getType() != Type::ULongTy &&
753 "Cannot have type bigger than ulong!");
754 unsigned AndValue = (1U << CSrc->getType()->getPrimitiveSize()*8)-1;
755 Constant *AndOp = ConstantUInt::get(CI.getType(), AndValue);
756 return BinaryOperator::create(Instruction::And, CSrc->getOperand(0),
757 AndOp);
758 }
759 }
760
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000761 return 0;
Chris Lattner8a2a3112001-12-14 16:52:21 +0000762}
763
Chris Lattnera1be5662002-05-02 17:06:02 +0000764
Chris Lattner473945d2002-05-06 18:06:38 +0000765// PHINode simplification
766//
Chris Lattner7e708292002-06-25 16:13:24 +0000767Instruction *InstCombiner::visitPHINode(PHINode &PN) {
Chris Lattner473945d2002-05-06 18:06:38 +0000768 // If the PHI node only has one incoming value, eliminate the PHI node...
Chris Lattner233f7dc2002-08-12 21:17:25 +0000769 if (PN.getNumIncomingValues() == 1)
770 return ReplaceInstUsesWith(PN, PN.getIncomingValue(0));
Chris Lattnerf02c4682002-08-20 15:35:35 +0000771
772 // Otherwise if all of the incoming values are the same for the PHI, replace
773 // the PHI node with the incoming value.
774 //
Chris Lattnerc20e2452002-08-22 20:22:01 +0000775 Value *InVal = 0;
776 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
777 if (PN.getIncomingValue(i) != &PN) // Not the PHI node itself...
778 if (InVal && PN.getIncomingValue(i) != InVal)
779 return 0; // Not the same, bail out.
780 else
781 InVal = PN.getIncomingValue(i);
782
783 // The only case that could cause InVal to be null is if we have a PHI node
784 // that only has entries for itself. In this case, there is no entry into the
785 // loop, so kill the PHI.
786 //
787 if (InVal == 0) InVal = Constant::getNullValue(PN.getType());
Chris Lattner473945d2002-05-06 18:06:38 +0000788
Chris Lattnerf02c4682002-08-20 15:35:35 +0000789 // All of the incoming values are the same, replace the PHI node now.
790 return ReplaceInstUsesWith(PN, InVal);
Chris Lattner473945d2002-05-06 18:06:38 +0000791}
792
Chris Lattnera1be5662002-05-02 17:06:02 +0000793
Chris Lattner7e708292002-06-25 16:13:24 +0000794Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
Chris Lattner90ac28c2002-08-02 19:29:35 +0000795 // Is it 'getelementptr %P, uint 0' or 'getelementptr %P'
Chris Lattner7e708292002-06-25 16:13:24 +0000796 // If so, eliminate the noop.
Chris Lattner90ac28c2002-08-02 19:29:35 +0000797 if ((GEP.getNumOperands() == 2 &&
Chris Lattner3cac88a2002-09-11 01:21:33 +0000798 GEP.getOperand(1) == Constant::getNullValue(Type::LongTy)) ||
Chris Lattner233f7dc2002-08-12 21:17:25 +0000799 GEP.getNumOperands() == 1)
800 return ReplaceInstUsesWith(GEP, GEP.getOperand(0));
Chris Lattnera1be5662002-05-02 17:06:02 +0000801
Chris Lattner90ac28c2002-08-02 19:29:35 +0000802 // Combine Indices - If the source pointer to this getelementptr instruction
803 // is a getelementptr instruction, combine the indices of the two
804 // getelementptr instructions into a single instruction.
805 //
Chris Lattner9b761232002-08-17 22:21:59 +0000806 if (GetElementPtrInst *Src = dyn_cast<GetElementPtrInst>(GEP.getOperand(0))) {
Chris Lattner90ac28c2002-08-02 19:29:35 +0000807 std::vector<Value *> Indices;
Chris Lattner8a2a3112001-12-14 16:52:21 +0000808
Chris Lattner90ac28c2002-08-02 19:29:35 +0000809 // Can we combine the two pointer arithmetics offsets?
810 if (Src->getNumOperands() == 2 && isa<Constant>(Src->getOperand(1)) &&
811 isa<Constant>(GEP.getOperand(1))) {
812 // Replace the index list on this GEP with the index on the getelementptr
813 Indices.insert(Indices.end(), GEP.idx_begin(), GEP.idx_end());
814 Indices[0] = *cast<Constant>(Src->getOperand(1)) +
815 *cast<Constant>(GEP.getOperand(1));
816 assert(Indices[0] != 0 && "Constant folding of uint's failed!?");
817
Chris Lattner01885342002-11-04 16:43:32 +0000818 } else if (*GEP.idx_begin() == Constant::getNullValue(Type::LongTy) &&
Chris Lattnerdfcbf012002-09-17 21:05:42 +0000819 Src->getNumOperands() != 1) {
Chris Lattner90ac28c2002-08-02 19:29:35 +0000820 // Otherwise we can do the fold if the first index of the GEP is a zero
821 Indices.insert(Indices.end(), Src->idx_begin(), Src->idx_end());
822 Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
Chris Lattner01885342002-11-04 16:43:32 +0000823 } else if (Src->getOperand(Src->getNumOperands()-1) ==
824 Constant::getNullValue(Type::LongTy)) {
825 // If the src gep ends with a constant array index, merge this get into
826 // it, even if we have a non-zero array index.
827 Indices.insert(Indices.end(), Src->idx_begin(), Src->idx_end()-1);
828 Indices.insert(Indices.end(), GEP.idx_begin(), GEP.idx_end());
Chris Lattner90ac28c2002-08-02 19:29:35 +0000829 }
830
831 if (!Indices.empty())
832 return new GetElementPtrInst(Src->getOperand(0), Indices, GEP.getName());
Chris Lattner9b761232002-08-17 22:21:59 +0000833
834 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(GEP.getOperand(0))) {
835 // GEP of global variable. If all of the indices for this GEP are
836 // constants, we can promote this to a constexpr instead of an instruction.
837
838 // Scan for nonconstants...
839 std::vector<Constant*> Indices;
840 User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
841 for (; I != E && isa<Constant>(*I); ++I)
842 Indices.push_back(cast<Constant>(*I));
843
844 if (I == E) { // If they are all constants...
845 ConstantExpr *CE =
846 ConstantExpr::getGetElementPtr(ConstantPointerRef::get(GV), Indices);
847
848 // Replace all uses of the GEP with the new constexpr...
849 return ReplaceInstUsesWith(GEP, CE);
850 }
Chris Lattner8a2a3112001-12-14 16:52:21 +0000851 }
852
Chris Lattner8a2a3112001-12-14 16:52:21 +0000853 return 0;
854}
855
Chris Lattner0864acf2002-11-04 16:18:53 +0000856Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
857 // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
858 if (AI.isArrayAllocation()) // Check C != 1
859 if (const ConstantUInt *C = dyn_cast<ConstantUInt>(AI.getArraySize())) {
860 const Type *NewTy = ArrayType::get(AI.getAllocatedType(), C->getValue());
Chris Lattner0006bd72002-11-09 00:49:43 +0000861 AllocationInst *New = 0;
Chris Lattner0864acf2002-11-04 16:18:53 +0000862
863 // Create and insert the replacement instruction...
864 if (isa<MallocInst>(AI))
865 New = new MallocInst(NewTy, 0, AI.getName(), &AI);
Chris Lattner0006bd72002-11-09 00:49:43 +0000866 else {
867 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
Chris Lattner0864acf2002-11-04 16:18:53 +0000868 New = new AllocaInst(NewTy, 0, AI.getName(), &AI);
Chris Lattner0006bd72002-11-09 00:49:43 +0000869 }
Chris Lattner0864acf2002-11-04 16:18:53 +0000870
871 // Scan to the end of the allocation instructions, to skip over a block of
872 // allocas if possible...
873 //
874 BasicBlock::iterator It = New;
875 while (isa<AllocationInst>(*It)) ++It;
876
877 // Now that I is pointing to the first non-allocation-inst in the block,
878 // insert our getelementptr instruction...
879 //
880 std::vector<Value*> Idx(2, Constant::getNullValue(Type::LongTy));
881 Value *V = new GetElementPtrInst(New, Idx, New->getName()+".sub", It);
882
883 // Now make everything use the getelementptr instead of the original
884 // allocation.
885 ReplaceInstUsesWith(AI, V);
886 return &AI;
887 }
888 return 0;
889}
890
891
Chris Lattner8a2a3112001-12-14 16:52:21 +0000892
Chris Lattner62b14df2002-09-02 04:59:56 +0000893void InstCombiner::removeFromWorkList(Instruction *I) {
894 WorkList.erase(std::remove(WorkList.begin(), WorkList.end(), I),
895 WorkList.end());
896}
897
Chris Lattner7e708292002-06-25 16:13:24 +0000898bool InstCombiner::runOnFunction(Function &F) {
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000899 bool Changed = false;
Chris Lattner8a2a3112001-12-14 16:52:21 +0000900
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000901 WorkList.insert(WorkList.end(), inst_begin(F), inst_end(F));
Chris Lattner8a2a3112001-12-14 16:52:21 +0000902
903 while (!WorkList.empty()) {
904 Instruction *I = WorkList.back(); // Get an instruction from the worklist
905 WorkList.pop_back();
906
Misha Brukmana3bbcb52002-10-29 23:06:16 +0000907 // Check to see if we can DCE or ConstantPropagate the instruction...
Chris Lattner62b14df2002-09-02 04:59:56 +0000908 // Check to see if we can DIE the instruction...
909 if (isInstructionTriviallyDead(I)) {
910 // Add operands to the worklist...
911 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
912 if (Instruction *Op = dyn_cast<Instruction>(I->getOperand(i)))
913 WorkList.push_back(Op);
914
915 ++NumDeadInst;
916 BasicBlock::iterator BBI = I;
917 if (dceInstruction(BBI)) {
918 removeFromWorkList(I);
919 continue;
920 }
921 }
922
Misha Brukmana3bbcb52002-10-29 23:06:16 +0000923 // Instruction isn't dead, see if we can constant propagate it...
Chris Lattner62b14df2002-09-02 04:59:56 +0000924 if (Constant *C = ConstantFoldInstruction(I)) {
925 // Add operands to the worklist...
926 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
927 if (Instruction *Op = dyn_cast<Instruction>(I->getOperand(i)))
928 WorkList.push_back(Op);
Chris Lattnerc736d562002-12-05 22:41:53 +0000929 ReplaceInstUsesWith(*I, C);
930
Chris Lattner62b14df2002-09-02 04:59:56 +0000931 ++NumConstProp;
932 BasicBlock::iterator BBI = I;
933 if (dceInstruction(BBI)) {
934 removeFromWorkList(I);
935 continue;
936 }
937 }
938
Chris Lattner8a2a3112001-12-14 16:52:21 +0000939 // Now that we have an instruction, try combining it to simplify it...
Chris Lattner90ac28c2002-08-02 19:29:35 +0000940 if (Instruction *Result = visit(*I)) {
Chris Lattner3dec1f22002-05-10 15:38:35 +0000941 ++NumCombined;
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000942 // Should we replace the old instruction with a new one?
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +0000943 if (Result != I) {
944 // Instructions can end up on the worklist more than once. Make sure
945 // we do not process an instruction that has been deleted.
Chris Lattner62b14df2002-09-02 04:59:56 +0000946 removeFromWorkList(I);
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000947 ReplaceInstWithInst(I, Result);
Chris Lattner7e708292002-06-25 16:13:24 +0000948 } else {
Chris Lattner90ac28c2002-08-02 19:29:35 +0000949 BasicBlock::iterator II = I;
950
951 // If the instruction was modified, it's possible that it is now dead.
952 // if so, remove it.
953 if (dceInstruction(II)) {
954 // Instructions may end up in the worklist more than once. Erase them
955 // all.
Chris Lattner62b14df2002-09-02 04:59:56 +0000956 removeFromWorkList(I);
Chris Lattner90ac28c2002-08-02 19:29:35 +0000957 Result = 0;
958 }
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +0000959 }
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000960
Chris Lattner90ac28c2002-08-02 19:29:35 +0000961 if (Result) {
962 WorkList.push_back(Result);
963 AddUsesToWorkList(*Result);
964 }
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000965 Changed = true;
Chris Lattner8a2a3112001-12-14 16:52:21 +0000966 }
967 }
968
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000969 return Changed;
Chris Lattnerbd0ef772002-02-26 21:46:54 +0000970}
971
972Pass *createInstructionCombiningPass() {
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000973 return new InstCombiner();
Chris Lattnerbd0ef772002-02-26 21:46:54 +0000974}