blob: 8975322b6f5e41191ccbf59005ba0c87be308af7 [file] [log] [blame]
Chris Lattnere6794492002-08-12 21:17:25 +00001//===- InstructionCombining.cpp - Combine multiple instructions -----------===//
Chris Lattnerca081252001-12-14 16:52:21 +00002//
3// InstructionCombining - Combine instructions to form fewer, simple
Chris Lattner99f48c62002-09-02 04:59:56 +00004// instructions. This pass does not modify the CFG This pass is where algebraic
5// simplification happens.
Chris Lattnerca081252001-12-14 16:52:21 +00006//
7// This pass combines things like:
8// %Y = add int 1, %X
9// %Z = add int 1, %Y
10// into:
11// %Z = add int 2, %X
12//
13// This is a simple worklist driven algorithm.
14//
Chris Lattnerbfb1d032003-07-23 21:41:57 +000015// This pass guarantees that the following cannonicalizations are performed on
16// the program:
17// 1. If a binary operator has a constant operand, it is moved to the RHS
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +000018// 2. Bitwise operators with constant operands are always grouped so that
19// shifts are performed first, then or's, then and's, then xor's.
Chris Lattnerbfb1d032003-07-23 21:41:57 +000020// 3. SetCC instructions are converted from <,>,<=,>= to ==,!= if possible
21// 4. All SetCC instructions on boolean values are replaced with logical ops
22// N. This list is incomplete
23//
Chris Lattnerca081252001-12-14 16:52:21 +000024//===----------------------------------------------------------------------===//
25
Chris Lattnerb4cfa7f2002-05-07 20:03:00 +000026#include "llvm/Transforms/Scalar.h"
Chris Lattner9b55e5a2002-05-07 18:12:18 +000027#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Chris Lattnerae7a0d32002-08-02 19:29:35 +000028#include "llvm/Transforms/Utils/Local.h"
Chris Lattner471bd762003-05-22 19:07:21 +000029#include "llvm/Instructions.h"
Chris Lattner04805fa2002-02-26 21:46:54 +000030#include "llvm/Pass.h"
Chris Lattner34428442003-05-27 16:40:51 +000031#include "llvm/Constants.h"
32#include "llvm/ConstantHandling.h"
Chris Lattner1085bdf2002-11-04 16:18:53 +000033#include "llvm/DerivedTypes.h"
Chris Lattner0f1d8a32003-06-26 05:06:25 +000034#include "llvm/GlobalVariable.h"
Chris Lattner60a65912002-02-12 21:07:25 +000035#include "llvm/Support/InstIterator.h"
Chris Lattner260ab202002-04-18 17:39:14 +000036#include "llvm/Support/InstVisitor.h"
Chris Lattner970c33a2003-06-19 17:00:31 +000037#include "llvm/Support/CallSite.h"
Chris Lattnerbf3a0992002-10-01 22:38:41 +000038#include "Support/Statistic.h"
Chris Lattner053c0932002-05-14 15:24:07 +000039#include <algorithm>
Chris Lattnerca081252001-12-14 16:52:21 +000040
Chris Lattner260ab202002-04-18 17:39:14 +000041namespace {
Chris Lattnerbf3a0992002-10-01 22:38:41 +000042 Statistic<> NumCombined ("instcombine", "Number of insts combined");
43 Statistic<> NumConstProp("instcombine", "Number of constant folds");
44 Statistic<> NumDeadInst ("instcombine", "Number of dead inst eliminated");
45
Chris Lattnerc8e66542002-04-27 06:56:12 +000046 class InstCombiner : public FunctionPass,
Chris Lattner260ab202002-04-18 17:39:14 +000047 public InstVisitor<InstCombiner, Instruction*> {
48 // Worklist of all of the instructions that need to be simplified.
49 std::vector<Instruction*> WorkList;
50
Chris Lattner113f4f42002-06-25 16:13:24 +000051 void AddUsesToWorkList(Instruction &I) {
Chris Lattner260ab202002-04-18 17:39:14 +000052 // The instruction was simplified, add all users of the instruction to
53 // the work lists because they might get more simplified now...
54 //
Chris Lattner113f4f42002-06-25 16:13:24 +000055 for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
Chris Lattner260ab202002-04-18 17:39:14 +000056 UI != UE; ++UI)
57 WorkList.push_back(cast<Instruction>(*UI));
58 }
59
Chris Lattner99f48c62002-09-02 04:59:56 +000060 // removeFromWorkList - remove all instances of I from the worklist.
61 void removeFromWorkList(Instruction *I);
Chris Lattner260ab202002-04-18 17:39:14 +000062 public:
Chris Lattner113f4f42002-06-25 16:13:24 +000063 virtual bool runOnFunction(Function &F);
Chris Lattner260ab202002-04-18 17:39:14 +000064
Chris Lattnerf12cc842002-04-28 21:27:06 +000065 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Chris Lattner820d9712002-10-21 20:00:28 +000066 AU.setPreservesCFG();
Chris Lattnerf12cc842002-04-28 21:27:06 +000067 }
68
Chris Lattner260ab202002-04-18 17:39:14 +000069 // Visitation implementation - Implement instruction combining for different
70 // instruction types. The semantics are as follows:
71 // Return Value:
72 // null - No change was made
Chris Lattnere6794492002-08-12 21:17:25 +000073 // I - Change was made, I is still valid, I may be dead though
Chris Lattner260ab202002-04-18 17:39:14 +000074 // otherwise - Change was made, replace I with returned instruction
75 //
Chris Lattner113f4f42002-06-25 16:13:24 +000076 Instruction *visitAdd(BinaryOperator &I);
77 Instruction *visitSub(BinaryOperator &I);
78 Instruction *visitMul(BinaryOperator &I);
79 Instruction *visitDiv(BinaryOperator &I);
80 Instruction *visitRem(BinaryOperator &I);
81 Instruction *visitAnd(BinaryOperator &I);
82 Instruction *visitOr (BinaryOperator &I);
83 Instruction *visitXor(BinaryOperator &I);
84 Instruction *visitSetCondInst(BinaryOperator &I);
Chris Lattnere8d6c602003-03-10 19:16:08 +000085 Instruction *visitShiftInst(ShiftInst &I);
Chris Lattner113f4f42002-06-25 16:13:24 +000086 Instruction *visitCastInst(CastInst &CI);
Chris Lattner970c33a2003-06-19 17:00:31 +000087 Instruction *visitCallInst(CallInst &CI);
88 Instruction *visitInvokeInst(InvokeInst &II);
Chris Lattner113f4f42002-06-25 16:13:24 +000089 Instruction *visitPHINode(PHINode &PN);
90 Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
Chris Lattner1085bdf2002-11-04 16:18:53 +000091 Instruction *visitAllocationInst(AllocationInst &AI);
Chris Lattner0f1d8a32003-06-26 05:06:25 +000092 Instruction *visitLoadInst(LoadInst &LI);
Chris Lattner9eef8a72003-06-04 04:46:00 +000093 Instruction *visitBranchInst(BranchInst &BI);
Chris Lattner260ab202002-04-18 17:39:14 +000094
95 // visitInstruction - Specify what to return for unhandled instructions...
Chris Lattner113f4f42002-06-25 16:13:24 +000096 Instruction *visitInstruction(Instruction &I) { return 0; }
Chris Lattner6d14f2a2002-08-09 23:47:40 +000097
Chris Lattner970c33a2003-06-19 17:00:31 +000098 private:
99 bool transformConstExprCastCall(CallSite CS);
100
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000101 // InsertNewInstBefore - insert an instruction New before instruction Old
102 // in the program. Add the new instruction to the worklist.
103 //
104 void InsertNewInstBefore(Instruction *New, Instruction &Old) {
Chris Lattner65217ff2002-08-23 18:32:43 +0000105 assert(New && New->getParent() == 0 &&
106 "New instruction already inserted into a basic block!");
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000107 BasicBlock *BB = Old.getParent();
108 BB->getInstList().insert(&Old, New); // Insert inst
109 WorkList.push_back(New); // Add to worklist
110 }
111
112 // ReplaceInstUsesWith - This method is to be used when an instruction is
113 // found to be dead, replacable with another preexisting expression. Here
114 // we add all uses of I to the worklist, replace all uses of I with the new
115 // value, then return I, so that the inst combiner will know that I was
116 // modified.
117 //
118 Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
119 AddUsesToWorkList(I); // Add all modified instrs to worklist
120 I.replaceAllUsesWith(V);
121 return &I;
122 }
Chris Lattner7fb29e12003-03-11 00:12:48 +0000123
Chris Lattnerdfae8be2003-07-24 17:35:25 +0000124 /// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
125 /// InsertBefore instruction. This is specialized a bit to avoid inserting
126 /// casts that are known to not do anything...
127 ///
128 Value *InsertOperandCastBefore(Value *V, const Type *DestTy,
129 Instruction *InsertBefore);
130
Chris Lattner7fb29e12003-03-11 00:12:48 +0000131 // SimplifyCommutative - This performs a few simplifications for commutative
132 // operators...
133 bool SimplifyCommutative(BinaryOperator &I);
Chris Lattner260ab202002-04-18 17:39:14 +0000134 };
Chris Lattnerb28b6802002-07-23 18:06:35 +0000135
Chris Lattnerc8b70922002-07-26 21:12:46 +0000136 RegisterOpt<InstCombiner> X("instcombine", "Combine redundant instructions");
Chris Lattner260ab202002-04-18 17:39:14 +0000137}
138
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000139// getComplexity: Assign a complexity or rank value to LLVM Values...
140// 0 -> Constant, 1 -> Other, 2 -> Argument, 2 -> Unary, 3 -> OtherInst
141static unsigned getComplexity(Value *V) {
142 if (isa<Instruction>(V)) {
143 if (BinaryOperator::isNeg(V) || BinaryOperator::isNot(V))
144 return 2;
145 return 3;
146 }
147 if (isa<Argument>(V)) return 2;
148 return isa<Constant>(V) ? 0 : 1;
149}
Chris Lattner260ab202002-04-18 17:39:14 +0000150
Chris Lattner7fb29e12003-03-11 00:12:48 +0000151// isOnlyUse - Return true if this instruction will be deleted if we stop using
152// it.
153static bool isOnlyUse(Value *V) {
154 return V->use_size() == 1 || isa<Constant>(V);
155}
156
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000157// SimplifyCommutative - This performs a few simplifications for commutative
158// operators:
Chris Lattner260ab202002-04-18 17:39:14 +0000159//
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000160// 1. Order operands such that they are listed from right (least complex) to
161// left (most complex). This puts constants before unary operators before
162// binary operators.
163//
Chris Lattner7fb29e12003-03-11 00:12:48 +0000164// 2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
165// 3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000166//
Chris Lattner7fb29e12003-03-11 00:12:48 +0000167bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000168 bool Changed = false;
169 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
170 Changed = !I.swapOperands();
171
172 if (!I.isAssociative()) return Changed;
173 Instruction::BinaryOps Opcode = I.getOpcode();
Chris Lattner7fb29e12003-03-11 00:12:48 +0000174 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
175 if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
176 if (isa<Constant>(I.getOperand(1))) {
Chris Lattner34428442003-05-27 16:40:51 +0000177 Constant *Folded = ConstantExpr::get(I.getOpcode(),
178 cast<Constant>(I.getOperand(1)),
179 cast<Constant>(Op->getOperand(1)));
Chris Lattner7fb29e12003-03-11 00:12:48 +0000180 I.setOperand(0, Op->getOperand(0));
181 I.setOperand(1, Folded);
182 return true;
183 } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
184 if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
185 isOnlyUse(Op) && isOnlyUse(Op1)) {
186 Constant *C1 = cast<Constant>(Op->getOperand(1));
187 Constant *C2 = cast<Constant>(Op1->getOperand(1));
188
189 // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattner34428442003-05-27 16:40:51 +0000190 Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
Chris Lattner7fb29e12003-03-11 00:12:48 +0000191 Instruction *New = BinaryOperator::create(Opcode, Op->getOperand(0),
192 Op1->getOperand(0),
193 Op1->getName(), &I);
194 WorkList.push_back(New);
195 I.setOperand(0, New);
196 I.setOperand(1, Folded);
197 return true;
198 }
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000199 }
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000200 return Changed;
Chris Lattner260ab202002-04-18 17:39:14 +0000201}
Chris Lattnerca081252001-12-14 16:52:21 +0000202
Chris Lattnerbb74e222003-03-10 23:06:50 +0000203// dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
204// if the LHS is a constant zero (which is the 'negate' form).
Chris Lattner9fa53de2002-05-06 16:49:18 +0000205//
Chris Lattnerbb74e222003-03-10 23:06:50 +0000206static inline Value *dyn_castNegVal(Value *V) {
207 if (BinaryOperator::isNeg(V))
208 return BinaryOperator::getNegArgument(cast<BinaryOperator>(V));
209
Chris Lattner9244df62003-04-30 22:19:10 +0000210 // Constants can be considered to be negated values if they can be folded...
211 if (Constant *C = dyn_cast<Constant>(V))
Chris Lattner34428442003-05-27 16:40:51 +0000212 return ConstantExpr::get(Instruction::Sub,
213 Constant::getNullValue(V->getType()), C);
Chris Lattnerbb74e222003-03-10 23:06:50 +0000214 return 0;
Chris Lattner9fa53de2002-05-06 16:49:18 +0000215}
216
Chris Lattnerbb74e222003-03-10 23:06:50 +0000217static inline Value *dyn_castNotVal(Value *V) {
218 if (BinaryOperator::isNot(V))
219 return BinaryOperator::getNotArgument(cast<BinaryOperator>(V));
220
221 // Constants can be considered to be not'ed values...
Chris Lattnerdd65d862003-04-30 22:34:06 +0000222 if (ConstantIntegral *C = dyn_cast<ConstantIntegral>(V))
Chris Lattner34428442003-05-27 16:40:51 +0000223 return ConstantExpr::get(Instruction::Xor,
224 ConstantIntegral::getAllOnesValue(C->getType()),C);
Chris Lattnerbb74e222003-03-10 23:06:50 +0000225 return 0;
226}
227
Chris Lattner7fb29e12003-03-11 00:12:48 +0000228// dyn_castFoldableMul - If this value is a multiply that can be folded into
229// other computations (because it has a constant operand), return the
230// non-constant operand of the multiply.
231//
232static inline Value *dyn_castFoldableMul(Value *V) {
233 if (V->use_size() == 1 && V->getType()->isInteger())
234 if (Instruction *I = dyn_cast<Instruction>(V))
235 if (I->getOpcode() == Instruction::Mul)
236 if (isa<Constant>(I->getOperand(1)))
237 return I->getOperand(0);
238 return 0;
Chris Lattner3082c5a2003-02-18 19:28:33 +0000239}
Chris Lattner31ae8632002-08-14 17:51:49 +0000240
Chris Lattner7fb29e12003-03-11 00:12:48 +0000241// dyn_castMaskingAnd - If this value is an And instruction masking a value with
242// a constant, return the constant being anded with.
243//
Chris Lattner01d56392003-08-12 19:17:27 +0000244template<class ValueType>
245static inline Constant *dyn_castMaskingAnd(ValueType *V) {
Chris Lattner7fb29e12003-03-11 00:12:48 +0000246 if (Instruction *I = dyn_cast<Instruction>(V))
247 if (I->getOpcode() == Instruction::And)
248 return dyn_cast<Constant>(I->getOperand(1));
249
250 // If this is a constant, it acts just like we were masking with it.
251 return dyn_cast<Constant>(V);
252}
Chris Lattner3082c5a2003-02-18 19:28:33 +0000253
254// Log2 - Calculate the log base 2 for the specified value if it is exactly a
255// power of 2.
256static unsigned Log2(uint64_t Val) {
257 assert(Val > 1 && "Values 0 and 1 should be handled elsewhere!");
258 unsigned Count = 0;
259 while (Val != 1) {
260 if (Val & 1) return 0; // Multiple bits set?
261 Val >>= 1;
262 ++Count;
263 }
264 return Count;
Chris Lattner31ae8632002-08-14 17:51:49 +0000265}
266
Chris Lattner113f4f42002-06-25 16:13:24 +0000267Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000268 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +0000269 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
Chris Lattner9fa53de2002-05-06 16:49:18 +0000270
271 // Eliminate 'add int %X, 0'
Chris Lattnere6794492002-08-12 21:17:25 +0000272 if (RHS == Constant::getNullValue(I.getType()))
273 return ReplaceInstUsesWith(I, LHS);
Chris Lattner9fa53de2002-05-06 16:49:18 +0000274
Chris Lattner147e9752002-05-08 22:46:53 +0000275 // -A + B --> B - A
Chris Lattnerbb74e222003-03-10 23:06:50 +0000276 if (Value *V = dyn_castNegVal(LHS))
Chris Lattner147e9752002-05-08 22:46:53 +0000277 return BinaryOperator::create(Instruction::Sub, RHS, V);
Chris Lattner9fa53de2002-05-06 16:49:18 +0000278
279 // A + -B --> A - B
Chris Lattnerbb74e222003-03-10 23:06:50 +0000280 if (!isa<Constant>(RHS))
281 if (Value *V = dyn_castNegVal(RHS))
282 return BinaryOperator::create(Instruction::Sub, LHS, V);
Chris Lattner260ab202002-04-18 17:39:14 +0000283
Chris Lattner57c8d992003-02-18 19:57:07 +0000284 // X*C + X --> X * (C+1)
285 if (dyn_castFoldableMul(LHS) == RHS) {
Chris Lattner34428442003-05-27 16:40:51 +0000286 Constant *CP1 =
287 ConstantExpr::get(Instruction::Add,
288 cast<Constant>(cast<Instruction>(LHS)->getOperand(1)),
289 ConstantInt::get(I.getType(), 1));
Chris Lattner57c8d992003-02-18 19:57:07 +0000290 return BinaryOperator::create(Instruction::Mul, RHS, CP1);
291 }
292
293 // X + X*C --> X * (C+1)
294 if (dyn_castFoldableMul(RHS) == LHS) {
Chris Lattner34428442003-05-27 16:40:51 +0000295 Constant *CP1 =
296 ConstantExpr::get(Instruction::Add,
297 cast<Constant>(cast<Instruction>(RHS)->getOperand(1)),
298 ConstantInt::get(I.getType(), 1));
Chris Lattner57c8d992003-02-18 19:57:07 +0000299 return BinaryOperator::create(Instruction::Mul, LHS, CP1);
300 }
301
Chris Lattner7fb29e12003-03-11 00:12:48 +0000302 // (A & C1)+(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
303 if (Constant *C1 = dyn_castMaskingAnd(LHS))
304 if (Constant *C2 = dyn_castMaskingAnd(RHS))
Chris Lattner34428442003-05-27 16:40:51 +0000305 if (ConstantExpr::get(Instruction::And, C1, C2)->isNullValue())
Chris Lattner7fb29e12003-03-11 00:12:48 +0000306 return BinaryOperator::create(Instruction::Or, LHS, RHS);
307
Chris Lattner113f4f42002-06-25 16:13:24 +0000308 return Changed ? &I : 0;
Chris Lattner260ab202002-04-18 17:39:14 +0000309}
310
Chris Lattnerbdb0ce02003-07-22 21:46:59 +0000311// isSignBit - Return true if the value represented by the constant only has the
312// highest order bit set.
313static bool isSignBit(ConstantInt *CI) {
314 unsigned NumBits = CI->getType()->getPrimitiveSize()*8;
315 return (CI->getRawValue() & ~(-1LL << NumBits)) == (1ULL << (NumBits-1));
316}
317
Chris Lattnerdfae8be2003-07-24 17:35:25 +0000318static unsigned getTypeSizeInBits(const Type *Ty) {
319 return Ty == Type::BoolTy ? 1 : Ty->getPrimitiveSize()*8;
320}
321
Chris Lattner113f4f42002-06-25 16:13:24 +0000322Instruction *InstCombiner::visitSub(BinaryOperator &I) {
Chris Lattner113f4f42002-06-25 16:13:24 +0000323 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000324
Chris Lattnere6794492002-08-12 21:17:25 +0000325 if (Op0 == Op1) // sub X, X -> 0
326 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner260ab202002-04-18 17:39:14 +0000327
Chris Lattnere6794492002-08-12 21:17:25 +0000328 // If this is a 'B = x-(-A)', change to B = x+A...
Chris Lattnerbb74e222003-03-10 23:06:50 +0000329 if (Value *V = dyn_castNegVal(Op1))
Chris Lattner147e9752002-05-08 22:46:53 +0000330 return BinaryOperator::create(Instruction::Add, Op0, V);
Chris Lattner9fa53de2002-05-06 16:49:18 +0000331
Chris Lattner3082c5a2003-02-18 19:28:33 +0000332 // Replace (-1 - A) with (~A)...
333 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0))
334 if (C->isAllOnesValue())
335 return BinaryOperator::createNot(Op1);
Chris Lattnerad3c4952002-05-09 01:29:19 +0000336
Chris Lattner3082c5a2003-02-18 19:28:33 +0000337 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1))
338 if (Op1I->use_size() == 1) {
339 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
340 // is not used by anyone else...
341 //
342 if (Op1I->getOpcode() == Instruction::Sub) {
343 // Swap the two operands of the subexpr...
344 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
345 Op1I->setOperand(0, IIOp1);
346 Op1I->setOperand(1, IIOp0);
347
348 // Create the new top level add instruction...
349 return BinaryOperator::create(Instruction::Add, Op0, Op1);
350 }
351
352 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
353 //
354 if (Op1I->getOpcode() == Instruction::And &&
355 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
356 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
357
358 Instruction *NewNot = BinaryOperator::createNot(OtherOp, "B.not", &I);
359 return BinaryOperator::create(Instruction::And, Op0, NewNot);
360 }
Chris Lattner57c8d992003-02-18 19:57:07 +0000361
362 // X - X*C --> X * (1-C)
363 if (dyn_castFoldableMul(Op1I) == Op0) {
Chris Lattner34428442003-05-27 16:40:51 +0000364 Constant *CP1 =
365 ConstantExpr::get(Instruction::Sub,
366 ConstantInt::get(I.getType(), 1),
367 cast<Constant>(cast<Instruction>(Op1)->getOperand(1)));
Chris Lattner57c8d992003-02-18 19:57:07 +0000368 assert(CP1 && "Couldn't constant fold 1-C?");
369 return BinaryOperator::create(Instruction::Mul, Op0, CP1);
370 }
Chris Lattnerad3c4952002-05-09 01:29:19 +0000371 }
Chris Lattner3082c5a2003-02-18 19:28:33 +0000372
Chris Lattner57c8d992003-02-18 19:57:07 +0000373 // X*C - X --> X * (C-1)
374 if (dyn_castFoldableMul(Op0) == Op1) {
Chris Lattner34428442003-05-27 16:40:51 +0000375 Constant *CP1 =
376 ConstantExpr::get(Instruction::Sub,
377 cast<Constant>(cast<Instruction>(Op0)->getOperand(1)),
378 ConstantInt::get(I.getType(), 1));
Chris Lattner57c8d992003-02-18 19:57:07 +0000379 assert(CP1 && "Couldn't constant fold C - 1?");
380 return BinaryOperator::create(Instruction::Mul, Op1, CP1);
381 }
382
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000383 return 0;
Chris Lattner260ab202002-04-18 17:39:14 +0000384}
385
Chris Lattner113f4f42002-06-25 16:13:24 +0000386Instruction *InstCombiner::visitMul(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000387 bool Changed = SimplifyCommutative(I);
Chris Lattner3082c5a2003-02-18 19:28:33 +0000388 Value *Op0 = I.getOperand(0);
Chris Lattner260ab202002-04-18 17:39:14 +0000389
Chris Lattnere6794492002-08-12 21:17:25 +0000390 // Simplify mul instructions with a constant RHS...
Chris Lattner3082c5a2003-02-18 19:28:33 +0000391 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
392 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
393 const Type *Ty = CI->getType();
Chris Lattner6077c312003-07-23 15:22:26 +0000394 int64_t Val = (int64_t)cast<ConstantInt>(CI)->getRawValue();
Chris Lattner3082c5a2003-02-18 19:28:33 +0000395 switch (Val) {
Chris Lattner35236d82003-06-25 17:09:20 +0000396 case -1: // X * -1 -> -X
397 return BinaryOperator::createNeg(Op0, I.getName());
Chris Lattner3082c5a2003-02-18 19:28:33 +0000398 case 0:
399 return ReplaceInstUsesWith(I, Op1); // Eliminate 'mul double %X, 0'
400 case 1:
401 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul int %X, 1'
402 case 2: // Convert 'mul int %X, 2' to 'add int %X, %X'
403 return BinaryOperator::create(Instruction::Add, Op0, Op0, I.getName());
404 }
Chris Lattner31ba1292002-04-29 22:24:47 +0000405
Chris Lattner3082c5a2003-02-18 19:28:33 +0000406 if (uint64_t C = Log2(Val)) // Replace X*(2^C) with X << C
407 return new ShiftInst(Instruction::Shl, Op0,
408 ConstantUInt::get(Type::UByteTy, C));
409 } else {
410 ConstantFP *Op1F = cast<ConstantFP>(Op1);
411 if (Op1F->isNullValue())
412 return ReplaceInstUsesWith(I, Op1);
Chris Lattner31ba1292002-04-29 22:24:47 +0000413
Chris Lattner3082c5a2003-02-18 19:28:33 +0000414 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
415 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
416 if (Op1F->getValue() == 1.0)
417 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0'
418 }
Chris Lattner260ab202002-04-18 17:39:14 +0000419 }
420
Chris Lattner934a64cf2003-03-10 23:23:04 +0000421 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
422 if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
423 return BinaryOperator::create(Instruction::Mul, Op0v, Op1v);
424
Chris Lattner113f4f42002-06-25 16:13:24 +0000425 return Changed ? &I : 0;
Chris Lattner260ab202002-04-18 17:39:14 +0000426}
427
Chris Lattner113f4f42002-06-25 16:13:24 +0000428Instruction *InstCombiner::visitDiv(BinaryOperator &I) {
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000429 // div X, 1 == X
Chris Lattner3082c5a2003-02-18 19:28:33 +0000430 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I.getOperand(1))) {
Chris Lattnere6794492002-08-12 21:17:25 +0000431 if (RHS->equalsInt(1))
432 return ReplaceInstUsesWith(I, I.getOperand(0));
Chris Lattner3082c5a2003-02-18 19:28:33 +0000433
434 // Check to see if this is an unsigned division with an exact power of 2,
435 // if so, convert to a right shift.
436 if (ConstantUInt *C = dyn_cast<ConstantUInt>(RHS))
437 if (uint64_t Val = C->getValue()) // Don't break X / 0
438 if (uint64_t C = Log2(Val))
439 return new ShiftInst(Instruction::Shr, I.getOperand(0),
440 ConstantUInt::get(Type::UByteTy, C));
441 }
442
443 // 0 / X == 0, we don't need to preserve faults!
444 if (ConstantInt *LHS = dyn_cast<ConstantInt>(I.getOperand(0)))
445 if (LHS->equalsInt(0))
446 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
447
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000448 return 0;
449}
450
451
Chris Lattner113f4f42002-06-25 16:13:24 +0000452Instruction *InstCombiner::visitRem(BinaryOperator &I) {
Chris Lattner3082c5a2003-02-18 19:28:33 +0000453 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I.getOperand(1))) {
454 if (RHS->equalsInt(1)) // X % 1 == 0
455 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
456
457 // Check to see if this is an unsigned remainder with an exact power of 2,
458 // if so, convert to a bitwise and.
459 if (ConstantUInt *C = dyn_cast<ConstantUInt>(RHS))
460 if (uint64_t Val = C->getValue()) // Don't break X % 0 (divide by zero)
461 if (Log2(Val))
462 return BinaryOperator::create(Instruction::And, I.getOperand(0),
463 ConstantUInt::get(I.getType(), Val-1));
464 }
465
466 // 0 % X == 0, we don't need to preserve faults!
467 if (ConstantInt *LHS = dyn_cast<ConstantInt>(I.getOperand(0)))
468 if (LHS->equalsInt(0))
Chris Lattnere6794492002-08-12 21:17:25 +0000469 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
470
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000471 return 0;
472}
473
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000474// isMaxValueMinusOne - return true if this is Max-1
Chris Lattnere6794492002-08-12 21:17:25 +0000475static bool isMaxValueMinusOne(const ConstantInt *C) {
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000476 if (const ConstantUInt *CU = dyn_cast<ConstantUInt>(C)) {
477 // Calculate -1 casted to the right type...
478 unsigned TypeBits = C->getType()->getPrimitiveSize()*8;
479 uint64_t Val = ~0ULL; // All ones
480 Val >>= 64-TypeBits; // Shift out unwanted 1 bits...
481 return CU->getValue() == Val-1;
482 }
483
484 const ConstantSInt *CS = cast<ConstantSInt>(C);
485
486 // Calculate 0111111111..11111
487 unsigned TypeBits = C->getType()->getPrimitiveSize()*8;
488 int64_t Val = INT64_MAX; // All ones
489 Val >>= 64-TypeBits; // Shift out unwanted 1 bits...
490 return CS->getValue() == Val-1;
491}
492
493// isMinValuePlusOne - return true if this is Min+1
Chris Lattnere6794492002-08-12 21:17:25 +0000494static bool isMinValuePlusOne(const ConstantInt *C) {
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000495 if (const ConstantUInt *CU = dyn_cast<ConstantUInt>(C))
496 return CU->getValue() == 1;
497
498 const ConstantSInt *CS = cast<ConstantSInt>(C);
499
500 // Calculate 1111111111000000000000
501 unsigned TypeBits = C->getType()->getPrimitiveSize()*8;
502 int64_t Val = -1; // All ones
503 Val <<= TypeBits-1; // Shift over to the right spot
504 return CS->getValue() == Val+1;
505}
506
507
Chris Lattner113f4f42002-06-25 16:13:24 +0000508Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000509 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +0000510 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000511
512 // and X, X = X and X, 0 == 0
Chris Lattnere6794492002-08-12 21:17:25 +0000513 if (Op0 == Op1 || Op1 == Constant::getNullValue(I.getType()))
514 return ReplaceInstUsesWith(I, Op1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000515
516 // and X, -1 == X
Chris Lattner49b47ae2003-07-23 17:57:01 +0000517 if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
Chris Lattnere6794492002-08-12 21:17:25 +0000518 if (RHS->isAllOnesValue())
519 return ReplaceInstUsesWith(I, Op0);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000520
Chris Lattner33217db2003-07-23 19:36:21 +0000521 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
522 Value *X = Op0I->getOperand(0);
Chris Lattner16464b32003-07-23 19:25:52 +0000523 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
524 if (Op0I->getOpcode() == Instruction::Xor) {
Chris Lattner33217db2003-07-23 19:36:21 +0000525 if ((*RHS & *Op0CI)->isNullValue()) {
526 // (X ^ C1) & C2 --> (X & C2) iff (C1&C2) == 0
527 return BinaryOperator::create(Instruction::And, X, RHS);
528 } else if (isOnlyUse(Op0)) {
Chris Lattner16464b32003-07-23 19:25:52 +0000529 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
530 std::string Op0Name = Op0I->getName(); Op0I->setName("");
531 Instruction *And = BinaryOperator::create(Instruction::And,
Chris Lattner33217db2003-07-23 19:36:21 +0000532 X, RHS, Op0Name);
Chris Lattner16464b32003-07-23 19:25:52 +0000533 InsertNewInstBefore(And, I);
534 return BinaryOperator::create(Instruction::Xor, And, *RHS & *Op0CI);
535 }
536 } else if (Op0I->getOpcode() == Instruction::Or) {
537 // (X | C1) & C2 --> X & C2 iff C1 & C1 == 0
538 if ((*RHS & *Op0CI)->isNullValue())
Chris Lattner33217db2003-07-23 19:36:21 +0000539 return BinaryOperator::create(Instruction::And, X, RHS);
Chris Lattner16464b32003-07-23 19:25:52 +0000540
541 Constant *Together = *RHS & *Op0CI;
542 if (Together == RHS) // (X | C) & C --> C
543 return ReplaceInstUsesWith(I, RHS);
544
545 if (isOnlyUse(Op0)) {
546 if (Together != Op0CI) {
547 // (X | C1) & C2 --> (X | (C1&C2)) & C2
548 std::string Op0Name = Op0I->getName(); Op0I->setName("");
Chris Lattner33217db2003-07-23 19:36:21 +0000549 Instruction *Or = BinaryOperator::create(Instruction::Or, X,
550 Together, Op0Name);
Chris Lattner16464b32003-07-23 19:25:52 +0000551 InsertNewInstBefore(Or, I);
552 return BinaryOperator::create(Instruction::And, Or, RHS);
553 }
554 }
Chris Lattner49b47ae2003-07-23 17:57:01 +0000555 }
Chris Lattner33217db2003-07-23 19:36:21 +0000556 }
Chris Lattner49b47ae2003-07-23 17:57:01 +0000557 }
558
Chris Lattnerbb74e222003-03-10 23:06:50 +0000559 Value *Op0NotVal = dyn_castNotVal(Op0);
560 Value *Op1NotVal = dyn_castNotVal(Op1);
Chris Lattner3082c5a2003-02-18 19:28:33 +0000561
562 // (~A & ~B) == (~(A | B)) - Demorgan's Law
Chris Lattnerbb74e222003-03-10 23:06:50 +0000563 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Chris Lattner3082c5a2003-02-18 19:28:33 +0000564 Instruction *Or = BinaryOperator::create(Instruction::Or, Op0NotVal,
Chris Lattner49b47ae2003-07-23 17:57:01 +0000565 Op1NotVal,I.getName()+".demorgan");
566 InsertNewInstBefore(Or, I);
Chris Lattner3082c5a2003-02-18 19:28:33 +0000567 return BinaryOperator::createNot(Or);
568 }
569
570 if (Op0NotVal == Op1 || Op1NotVal == Op0) // A & ~A == ~A & A == 0
571 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner65217ff2002-08-23 18:32:43 +0000572
Chris Lattner113f4f42002-06-25 16:13:24 +0000573 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000574}
575
576
577
Chris Lattner113f4f42002-06-25 16:13:24 +0000578Instruction *InstCombiner::visitOr(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000579 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +0000580 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000581
582 // or X, X = X or X, 0 == X
Chris Lattnere6794492002-08-12 21:17:25 +0000583 if (Op0 == Op1 || Op1 == Constant::getNullValue(I.getType()))
584 return ReplaceInstUsesWith(I, Op0);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000585
586 // or X, -1 == -1
Chris Lattner8f0d1562003-07-23 18:29:44 +0000587 if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
Chris Lattnere6794492002-08-12 21:17:25 +0000588 if (RHS->isAllOnesValue())
589 return ReplaceInstUsesWith(I, Op1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000590
Chris Lattner8f0d1562003-07-23 18:29:44 +0000591 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
592 // (X & C1) | C2 --> (X | C2) & (C1|C2)
593 if (Op0I->getOpcode() == Instruction::And && isOnlyUse(Op0))
594 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
595 std::string Op0Name = Op0I->getName(); Op0I->setName("");
596 Instruction *Or = BinaryOperator::create(Instruction::Or,
597 Op0I->getOperand(0), RHS,
598 Op0Name);
599 InsertNewInstBefore(Or, I);
600 return BinaryOperator::create(Instruction::And, Or, *RHS | *Op0CI);
601 }
602
603 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
604 if (Op0I->getOpcode() == Instruction::Xor && isOnlyUse(Op0))
605 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
606 std::string Op0Name = Op0I->getName(); Op0I->setName("");
607 Instruction *Or = BinaryOperator::create(Instruction::Or,
608 Op0I->getOperand(0), RHS,
609 Op0Name);
610 InsertNewInstBefore(Or, I);
611 return BinaryOperator::create(Instruction::Xor, Or, *Op0CI & *~*RHS);
612 }
613 }
614 }
615
Chris Lattner812aab72003-08-12 19:11:07 +0000616 // (A & C1)|(A & C2) == A & (C1|C2)
Chris Lattner01d56392003-08-12 19:17:27 +0000617 if (Instruction *LHS = dyn_cast<BinaryOperator>(Op0))
618 if (Instruction *RHS = dyn_cast<BinaryOperator>(Op1))
619 if (LHS->getOperand(0) == RHS->getOperand(0))
620 if (Constant *C0 = dyn_castMaskingAnd(LHS))
621 if (Constant *C1 = dyn_castMaskingAnd(RHS))
622 return BinaryOperator::create(Instruction::And, LHS->getOperand(0),
Chris Lattner812aab72003-08-12 19:11:07 +0000623 *C0 | *C1);
624
Chris Lattner3e327a42003-03-10 23:13:59 +0000625 Value *Op0NotVal = dyn_castNotVal(Op0);
626 Value *Op1NotVal = dyn_castNotVal(Op1);
Chris Lattner3082c5a2003-02-18 19:28:33 +0000627
Chris Lattner3e327a42003-03-10 23:13:59 +0000628 if (Op1 == Op0NotVal) // ~A | A == -1
629 return ReplaceInstUsesWith(I,
630 ConstantIntegral::getAllOnesValue(I.getType()));
631
632 if (Op0 == Op1NotVal) // A | ~A == -1
633 return ReplaceInstUsesWith(I,
634 ConstantIntegral::getAllOnesValue(I.getType()));
635
636 // (~A | ~B) == (~(A & B)) - Demorgan's Law
637 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
638 Instruction *And = BinaryOperator::create(Instruction::And, Op0NotVal,
639 Op1NotVal,I.getName()+".demorgan",
640 &I);
641 WorkList.push_back(And);
642 return BinaryOperator::createNot(And);
643 }
Chris Lattner3082c5a2003-02-18 19:28:33 +0000644
Chris Lattner113f4f42002-06-25 16:13:24 +0000645 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000646}
647
648
649
Chris Lattner113f4f42002-06-25 16:13:24 +0000650Instruction *InstCombiner::visitXor(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000651 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +0000652 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000653
654 // xor X, X = 0
Chris Lattnere6794492002-08-12 21:17:25 +0000655 if (Op0 == Op1)
656 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000657
Chris Lattner97638592003-07-23 21:37:07 +0000658 if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000659 // xor X, 0 == X
Chris Lattner97638592003-07-23 21:37:07 +0000660 if (RHS->isNullValue())
Chris Lattnere6794492002-08-12 21:17:25 +0000661 return ReplaceInstUsesWith(I, Op0);
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000662
Chris Lattner97638592003-07-23 21:37:07 +0000663 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Chris Lattnerb8d6e402002-08-20 18:24:26 +0000664 // xor (setcc A, B), true = not (setcc A, B) = setncc A, B
Chris Lattner97638592003-07-23 21:37:07 +0000665 if (SetCondInst *SCI = dyn_cast<SetCondInst>(Op0I))
666 if (RHS == ConstantBool::True && SCI->use_size() == 1)
Chris Lattnerb8d6e402002-08-20 18:24:26 +0000667 return new SetCondInst(SCI->getInverseCondition(),
668 SCI->getOperand(0), SCI->getOperand(1));
Chris Lattner97638592003-07-23 21:37:07 +0000669
670 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
671 if (Op0I->getOpcode() == Instruction::And) {
672 // (X & C1) ^ C2 --> (X & C1) | C2 iff (C1&C2) == 0
673 if ((*RHS & *Op0CI)->isNullValue())
674 return BinaryOperator::create(Instruction::Or, Op0, RHS);
675 } else if (Op0I->getOpcode() == Instruction::Or) {
676 // (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
677 if ((*RHS & *Op0CI) == RHS)
678 return BinaryOperator::create(Instruction::And, Op0, ~*RHS);
679 }
Chris Lattnerb8d6e402002-08-20 18:24:26 +0000680 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000681 }
682
Chris Lattnerbb74e222003-03-10 23:06:50 +0000683 if (Value *X = dyn_castNotVal(Op0)) // ~A ^ A == -1
Chris Lattner3082c5a2003-02-18 19:28:33 +0000684 if (X == Op1)
685 return ReplaceInstUsesWith(I,
686 ConstantIntegral::getAllOnesValue(I.getType()));
687
Chris Lattnerbb74e222003-03-10 23:06:50 +0000688 if (Value *X = dyn_castNotVal(Op1)) // A ^ ~A == -1
Chris Lattner3082c5a2003-02-18 19:28:33 +0000689 if (X == Op0)
690 return ReplaceInstUsesWith(I,
691 ConstantIntegral::getAllOnesValue(I.getType()));
692
Chris Lattner1bbb7b62003-03-10 18:24:17 +0000693 if (Instruction *Op1I = dyn_cast<Instruction>(Op1))
694 if (Op1I->getOpcode() == Instruction::Or)
695 if (Op1I->getOperand(0) == Op0) { // B^(B|A) == (A|B)^B
696 cast<BinaryOperator>(Op1I)->swapOperands();
697 I.swapOperands();
698 std::swap(Op0, Op1);
699 } else if (Op1I->getOperand(1) == Op0) { // B^(A|B) == (A|B)^B
700 I.swapOperands();
701 std::swap(Op0, Op1);
702 }
703
704 if (Instruction *Op0I = dyn_cast<Instruction>(Op0))
705 if (Op0I->getOpcode() == Instruction::Or && Op0I->use_size() == 1) {
706 if (Op0I->getOperand(0) == Op1) // (B|A)^B == (A|B)^B
707 cast<BinaryOperator>(Op0I)->swapOperands();
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000708 if (Op0I->getOperand(1) == Op1) { // (A|B)^B == A & ~B
Chris Lattner1bbb7b62003-03-10 18:24:17 +0000709 Value *NotB = BinaryOperator::createNot(Op1, Op1->getName()+".not", &I);
710 WorkList.push_back(cast<Instruction>(NotB));
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000711 return BinaryOperator::create(Instruction::And, Op0I->getOperand(0),
712 NotB);
Chris Lattner1bbb7b62003-03-10 18:24:17 +0000713 }
714 }
715
Chris Lattner7fb29e12003-03-11 00:12:48 +0000716 // (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1^C2 == 0
717 if (Constant *C1 = dyn_castMaskingAnd(Op0))
718 if (Constant *C2 = dyn_castMaskingAnd(Op1))
Chris Lattner34428442003-05-27 16:40:51 +0000719 if (ConstantExpr::get(Instruction::And, C1, C2)->isNullValue())
Chris Lattner7fb29e12003-03-11 00:12:48 +0000720 return BinaryOperator::create(Instruction::Or, Op0, Op1);
721
Chris Lattner113f4f42002-06-25 16:13:24 +0000722 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000723}
724
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000725// AddOne, SubOne - Add or subtract a constant one from an integer constant...
726static Constant *AddOne(ConstantInt *C) {
Chris Lattner34428442003-05-27 16:40:51 +0000727 Constant *Result = ConstantExpr::get(Instruction::Add, C,
728 ConstantInt::get(C->getType(), 1));
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000729 assert(Result && "Constant folding integer addition failed!");
730 return Result;
731}
732static Constant *SubOne(ConstantInt *C) {
Chris Lattner34428442003-05-27 16:40:51 +0000733 Constant *Result = ConstantExpr::get(Instruction::Sub, C,
734 ConstantInt::get(C->getType(), 1));
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000735 assert(Result && "Constant folding integer addition failed!");
736 return Result;
737}
738
Chris Lattner1fc23f32002-05-09 20:11:54 +0000739// isTrueWhenEqual - Return true if the specified setcondinst instruction is
740// true when both operands are equal...
741//
Chris Lattner113f4f42002-06-25 16:13:24 +0000742static bool isTrueWhenEqual(Instruction &I) {
743 return I.getOpcode() == Instruction::SetEQ ||
744 I.getOpcode() == Instruction::SetGE ||
745 I.getOpcode() == Instruction::SetLE;
Chris Lattner1fc23f32002-05-09 20:11:54 +0000746}
747
Chris Lattner113f4f42002-06-25 16:13:24 +0000748Instruction *InstCombiner::visitSetCondInst(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000749 bool Changed = SimplifyCommutative(I);
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000750 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
751 const Type *Ty = Op0->getType();
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000752
753 // setcc X, X
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000754 if (Op0 == Op1)
755 return ReplaceInstUsesWith(I, ConstantBool::get(isTrueWhenEqual(I)));
Chris Lattner1fc23f32002-05-09 20:11:54 +0000756
757 // setcc <global*>, 0 - Global value addresses are never null!
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000758 if (isa<GlobalValue>(Op0) && isa<ConstantPointerNull>(Op1))
759 return ReplaceInstUsesWith(I, ConstantBool::get(!isTrueWhenEqual(I)));
760
761 // setcc's with boolean values can always be turned into bitwise operations
762 if (Ty == Type::BoolTy) {
763 // If this is <, >, or !=, we can change this into a simple xor instruction
764 if (!isTrueWhenEqual(I))
765 return BinaryOperator::create(Instruction::Xor, Op0, Op1, I.getName());
766
767 // Otherwise we need to make a temporary intermediate instruction and insert
768 // it into the instruction stream. This is what we are after:
769 //
770 // seteq bool %A, %B -> ~(A^B)
771 // setle bool %A, %B -> ~A | B
772 // setge bool %A, %B -> A | ~B
773 //
774 if (I.getOpcode() == Instruction::SetEQ) { // seteq case
775 Instruction *Xor = BinaryOperator::create(Instruction::Xor, Op0, Op1,
776 I.getName()+"tmp");
777 InsertNewInstBefore(Xor, I);
Chris Lattner31ae8632002-08-14 17:51:49 +0000778 return BinaryOperator::createNot(Xor, I.getName());
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000779 }
780
781 // Handle the setXe cases...
782 assert(I.getOpcode() == Instruction::SetGE ||
783 I.getOpcode() == Instruction::SetLE);
784
785 if (I.getOpcode() == Instruction::SetGE)
786 std::swap(Op0, Op1); // Change setge -> setle
787
788 // Now we just have the SetLE case.
Chris Lattner31ae8632002-08-14 17:51:49 +0000789 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000790 InsertNewInstBefore(Not, I);
791 return BinaryOperator::create(Instruction::Or, Not, Op1, I.getName());
792 }
793
794 // Check to see if we are doing one of many comparisons against constant
795 // integers at the end of their ranges...
796 //
797 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnerd492a0b2003-07-23 17:02:11 +0000798 // Simplify seteq and setne instructions...
799 if (I.getOpcode() == Instruction::SetEQ ||
800 I.getOpcode() == Instruction::SetNE) {
801 bool isSetNE = I.getOpcode() == Instruction::SetNE;
802
803 if (CI->isNullValue()) { // Simplify [seteq|setne] X, 0
804 CastInst *Val = new CastInst(Op0, Type::BoolTy, I.getName()+".not");
805 if (isSetNE) return Val;
806
Chris Lattnere967b342003-06-04 05:10:11 +0000807 // seteq X, 0 -> not (cast X to bool)
Chris Lattnere967b342003-06-04 05:10:11 +0000808 InsertNewInstBefore(Val, I);
809 return BinaryOperator::createNot(Val, I.getName());
810 }
Chris Lattnerd492a0b2003-07-23 17:02:11 +0000811
Chris Lattnercfbce7c2003-07-23 17:26:36 +0000812 // If the first operand is (and|or|xor) with a constant, and the second
Chris Lattnerd492a0b2003-07-23 17:02:11 +0000813 // operand is a constant, simplify a bit.
814 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
815 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1)))
816 if (BO->getOpcode() == Instruction::Or) {
817 // If bits are being or'd in that are not present in the constant we
818 // are comparing against, then the comparison could never succeed!
819 if (!(*BOC & *~*CI)->isNullValue())
820 return ReplaceInstUsesWith(I, ConstantBool::get(isSetNE));
821 } else if (BO->getOpcode() == Instruction::And) {
822 // If bits are being compared against that are and'd out, then the
823 // comparison can never succeed!
824 if (!(*CI & *~*BOC)->isNullValue())
825 return ReplaceInstUsesWith(I, ConstantBool::get(isSetNE));
Chris Lattnercfbce7c2003-07-23 17:26:36 +0000826 } else if (BO->getOpcode() == Instruction::Xor) {
827 // For the xor case, we can always just xor the two constants
828 // together, potentially eliminating the explicit xor.
829 return BinaryOperator::create(I.getOpcode(), BO->getOperand(0),
830 *CI ^ *BOC);
Chris Lattnerd492a0b2003-07-23 17:02:11 +0000831 }
Chris Lattnere967b342003-06-04 05:10:11 +0000832 }
Chris Lattner791ac1a2003-06-01 03:35:25 +0000833
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000834 // Check to see if we are comparing against the minimum or maximum value...
Chris Lattnere6794492002-08-12 21:17:25 +0000835 if (CI->isMinValue()) {
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000836 if (I.getOpcode() == Instruction::SetLT) // A < MIN -> FALSE
837 return ReplaceInstUsesWith(I, ConstantBool::False);
838 if (I.getOpcode() == Instruction::SetGE) // A >= MIN -> TRUE
839 return ReplaceInstUsesWith(I, ConstantBool::True);
840 if (I.getOpcode() == Instruction::SetLE) // A <= MIN -> A == MIN
841 return BinaryOperator::create(Instruction::SetEQ, Op0,Op1, I.getName());
842 if (I.getOpcode() == Instruction::SetGT) // A > MIN -> A != MIN
843 return BinaryOperator::create(Instruction::SetNE, Op0,Op1, I.getName());
844
Chris Lattnere6794492002-08-12 21:17:25 +0000845 } else if (CI->isMaxValue()) {
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000846 if (I.getOpcode() == Instruction::SetGT) // A > MAX -> FALSE
847 return ReplaceInstUsesWith(I, ConstantBool::False);
848 if (I.getOpcode() == Instruction::SetLE) // A <= MAX -> TRUE
849 return ReplaceInstUsesWith(I, ConstantBool::True);
850 if (I.getOpcode() == Instruction::SetGE) // A >= MAX -> A == MAX
851 return BinaryOperator::create(Instruction::SetEQ, Op0,Op1, I.getName());
852 if (I.getOpcode() == Instruction::SetLT) // A < MAX -> A != MAX
853 return BinaryOperator::create(Instruction::SetNE, Op0,Op1, I.getName());
854
855 // Comparing against a value really close to min or max?
856 } else if (isMinValuePlusOne(CI)) {
857 if (I.getOpcode() == Instruction::SetLT) // A < MIN+1 -> A == MIN
858 return BinaryOperator::create(Instruction::SetEQ, Op0,
859 SubOne(CI), I.getName());
860 if (I.getOpcode() == Instruction::SetGE) // A >= MIN-1 -> A != MIN
861 return BinaryOperator::create(Instruction::SetNE, Op0,
862 SubOne(CI), I.getName());
863
864 } else if (isMaxValueMinusOne(CI)) {
865 if (I.getOpcode() == Instruction::SetGT) // A > MAX-1 -> A == MAX
866 return BinaryOperator::create(Instruction::SetEQ, Op0,
867 AddOne(CI), I.getName());
868 if (I.getOpcode() == Instruction::SetLE) // A <= MAX-1 -> A != MAX
869 return BinaryOperator::create(Instruction::SetNE, Op0,
870 AddOne(CI), I.getName());
871 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000872 }
873
Chris Lattner113f4f42002-06-25 16:13:24 +0000874 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000875}
876
877
878
Chris Lattnere8d6c602003-03-10 19:16:08 +0000879Instruction *InstCombiner::visitShiftInst(ShiftInst &I) {
Chris Lattner113f4f42002-06-25 16:13:24 +0000880 assert(I.getOperand(1)->getType() == Type::UByteTy);
881 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +0000882 bool isLeftShift = I.getOpcode() == Instruction::Shl;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000883
884 // shl X, 0 == X and shr X, 0 == X
885 // shl 0, X == 0 and shr 0, X == 0
886 if (Op1 == Constant::getNullValue(Type::UByteTy) ||
Chris Lattnere6794492002-08-12 21:17:25 +0000887 Op0 == Constant::getNullValue(Op0->getType()))
888 return ReplaceInstUsesWith(I, Op0);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000889
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +0000890 // shr int -1, X = -1 (for any arithmetic shift rights of ~0)
891 if (!isLeftShift)
892 if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(Op0))
893 if (CSI->isAllOnesValue())
894 return ReplaceInstUsesWith(I, CSI);
895
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000896 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(Op1)) {
Chris Lattner3204d4e2003-07-24 17:52:58 +0000897 // shl uint X, 32 = 0 and shr ubyte Y, 9 = 0, ... just don't eliminate shr
898 // of a signed value.
899 //
Chris Lattnere8d6c602003-03-10 19:16:08 +0000900 unsigned TypeBits = Op0->getType()->getPrimitiveSize()*8;
901 if (CUI->getValue() >= TypeBits &&
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +0000902 (!Op0->getType()->isSigned() || isLeftShift))
Chris Lattnere8d6c602003-03-10 19:16:08 +0000903 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
Chris Lattner55f3d942002-09-10 23:04:09 +0000904
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +0000905 // If the operand is an bitwise operator with a constant RHS, and the
906 // shift is the only use, we can pull it out of the shift.
907 if (Op0->use_size() == 1)
908 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0))
909 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
910 bool isValid = true; // Valid only for And, Or, Xor
911 bool highBitSet = false; // Transform if high bit of constant set?
912
913 switch (Op0BO->getOpcode()) {
914 default: isValid = false; break; // Do not perform transform!
915 case Instruction::Or:
916 case Instruction::Xor:
917 highBitSet = false;
918 break;
919 case Instruction::And:
920 highBitSet = true;
921 break;
922 }
923
924 // If this is a signed shift right, and the high bit is modified
925 // by the logical operation, do not perform the transformation.
926 // The highBitSet boolean indicates the value of the high bit of
927 // the constant which would cause it to be modified for this
928 // operation.
929 //
930 if (isValid && !isLeftShift && !I.getType()->isUnsigned()) {
931 uint64_t Val = Op0C->getRawValue();
932 isValid = ((Val & (1 << (TypeBits-1))) != 0) == highBitSet;
933 }
934
935 if (isValid) {
936 Constant *NewRHS =
937 ConstantFoldShiftInstruction(I.getOpcode(), Op0C, CUI);
938
939 Instruction *NewShift =
940 new ShiftInst(I.getOpcode(), Op0BO->getOperand(0), CUI,
941 Op0BO->getName());
942 Op0BO->setName("");
943 InsertNewInstBefore(NewShift, I);
944
945 return BinaryOperator::create(Op0BO->getOpcode(), NewShift,
946 NewRHS);
947 }
948 }
949
Chris Lattner3204d4e2003-07-24 17:52:58 +0000950 // If this is a shift of a shift, see if we can fold the two together...
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +0000951 if (ShiftInst *Op0SI = dyn_cast<ShiftInst>(Op0))
Chris Lattnerab780df2003-07-24 18:38:56 +0000952 if (ConstantUInt *ShiftAmt1C =
953 dyn_cast<ConstantUInt>(Op0SI->getOperand(1))) {
Chris Lattner3204d4e2003-07-24 17:52:58 +0000954 unsigned ShiftAmt1 = ShiftAmt1C->getValue();
955 unsigned ShiftAmt2 = CUI->getValue();
956
957 // Check for (A << c1) << c2 and (A >> c1) >> c2
958 if (I.getOpcode() == Op0SI->getOpcode()) {
959 unsigned Amt = ShiftAmt1+ShiftAmt2; // Fold into one big shift...
960 return new ShiftInst(I.getOpcode(), Op0SI->getOperand(0),
961 ConstantUInt::get(Type::UByteTy, Amt));
962 }
963
Chris Lattnerab780df2003-07-24 18:38:56 +0000964 // Check for (A << c1) >> c2 or visaversa. If we are dealing with
965 // signed types, we can only support the (A >> c1) << c2 configuration,
966 // because it can not turn an arbitrary bit of A into a sign bit.
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +0000967 if (I.getType()->isUnsigned() || isLeftShift) {
Chris Lattner3204d4e2003-07-24 17:52:58 +0000968 // Calculate bitmask for what gets shifted off the edge...
969 Constant *C = ConstantIntegral::getAllOnesValue(I.getType());
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +0000970 if (isLeftShift)
Chris Lattner3204d4e2003-07-24 17:52:58 +0000971 C = ConstantExpr::getShift(Instruction::Shl, C, ShiftAmt1C);
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +0000972 else
973 C = ConstantExpr::getShift(Instruction::Shr, C, ShiftAmt1C);
Chris Lattner3204d4e2003-07-24 17:52:58 +0000974
975 Instruction *Mask =
976 BinaryOperator::create(Instruction::And, Op0SI->getOperand(0),
977 C, Op0SI->getOperand(0)->getName()+".mask");
978 InsertNewInstBefore(Mask, I);
979
980 // Figure out what flavor of shift we should use...
981 if (ShiftAmt1 == ShiftAmt2)
982 return ReplaceInstUsesWith(I, Mask); // (A << c) >> c === A & c2
983 else if (ShiftAmt1 < ShiftAmt2) {
984 return new ShiftInst(I.getOpcode(), Mask,
985 ConstantUInt::get(Type::UByteTy, ShiftAmt2-ShiftAmt1));
986 } else {
987 return new ShiftInst(Op0SI->getOpcode(), Mask,
988 ConstantUInt::get(Type::UByteTy, ShiftAmt1-ShiftAmt2));
989 }
990 }
991 }
Chris Lattnerab780df2003-07-24 18:38:56 +0000992
993 // Check to see if we are shifting left by 1. If so, turn it into an add
994 // instruction.
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +0000995 if (isLeftShift && CUI->equalsInt(1))
Chris Lattnerab780df2003-07-24 18:38:56 +0000996 // Convert 'shl int %X, 1' to 'add int %X, %X'
997 return BinaryOperator::create(Instruction::Add, Op0, Op0, I.getName());
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000998 }
Chris Lattner2e0fb392002-10-08 16:16:40 +0000999
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001000 return 0;
1001}
1002
1003
Chris Lattner48a44f72002-05-02 17:06:02 +00001004// isEliminableCastOfCast - Return true if it is valid to eliminate the CI
1005// instruction.
1006//
Chris Lattnerdfae8be2003-07-24 17:35:25 +00001007static inline bool isEliminableCastOfCast(const Type *SrcTy, const Type *MidTy,
1008 const Type *DstTy) {
Chris Lattner48a44f72002-05-02 17:06:02 +00001009
Chris Lattner650b6da2002-08-02 20:00:25 +00001010 // It is legal to eliminate the instruction if casting A->B->A if the sizes
1011 // are identical and the bits don't get reinterpreted (for example
Chris Lattner0bb75912002-08-14 23:21:10 +00001012 // int->float->int would not be allowed)
Misha Brukmane5838c42003-05-20 18:45:36 +00001013 if (SrcTy == DstTy && SrcTy->isLosslesslyConvertibleTo(MidTy))
Chris Lattner650b6da2002-08-02 20:00:25 +00001014 return true;
Chris Lattner48a44f72002-05-02 17:06:02 +00001015
1016 // Allow free casting and conversion of sizes as long as the sign doesn't
1017 // change...
Chris Lattnerb0b412e2002-09-03 01:08:28 +00001018 if (SrcTy->isIntegral() && MidTy->isIntegral() && DstTy->isIntegral()) {
Chris Lattner650b6da2002-08-02 20:00:25 +00001019 unsigned SrcSize = SrcTy->getPrimitiveSize();
1020 unsigned MidSize = MidTy->getPrimitiveSize();
1021 unsigned DstSize = DstTy->getPrimitiveSize();
Chris Lattner650b6da2002-08-02 20:00:25 +00001022
Chris Lattner3732aca2002-08-15 16:15:25 +00001023 // Cases where we are monotonically decreasing the size of the type are
1024 // always ok, regardless of what sign changes are going on.
1025 //
Chris Lattner0bb75912002-08-14 23:21:10 +00001026 if (SrcSize >= MidSize && MidSize >= DstSize)
Chris Lattner650b6da2002-08-02 20:00:25 +00001027 return true;
Chris Lattner3732aca2002-08-15 16:15:25 +00001028
Chris Lattner555518c2002-09-23 23:39:43 +00001029 // Cases where the source and destination type are the same, but the middle
1030 // type is bigger are noops.
1031 //
1032 if (SrcSize == DstSize && MidSize > SrcSize)
1033 return true;
1034
Chris Lattner3732aca2002-08-15 16:15:25 +00001035 // If we are monotonically growing, things are more complex.
1036 //
1037 if (SrcSize <= MidSize && MidSize <= DstSize) {
1038 // We have eight combinations of signedness to worry about. Here's the
1039 // table:
1040 static const int SignTable[8] = {
1041 // CODE, SrcSigned, MidSigned, DstSigned, Comment
1042 1, // U U U Always ok
1043 1, // U U S Always ok
1044 3, // U S U Ok iff SrcSize != MidSize
1045 3, // U S S Ok iff SrcSize != MidSize
1046 0, // S U U Never ok
1047 2, // S U S Ok iff MidSize == DstSize
1048 1, // S S U Always ok
1049 1, // S S S Always ok
1050 };
1051
1052 // Choose an action based on the current entry of the signtable that this
1053 // cast of cast refers to...
1054 unsigned Row = SrcTy->isSigned()*4+MidTy->isSigned()*2+DstTy->isSigned();
1055 switch (SignTable[Row]) {
1056 case 0: return false; // Never ok
1057 case 1: return true; // Always ok
1058 case 2: return MidSize == DstSize; // Ok iff MidSize == DstSize
1059 case 3: // Ok iff SrcSize != MidSize
1060 return SrcSize != MidSize || SrcTy == Type::BoolTy;
1061 default: assert(0 && "Bad entry in sign table!");
1062 }
Chris Lattner3732aca2002-08-15 16:15:25 +00001063 }
Chris Lattner650b6da2002-08-02 20:00:25 +00001064 }
Chris Lattner48a44f72002-05-02 17:06:02 +00001065
1066 // Otherwise, we cannot succeed. Specifically we do not want to allow things
1067 // like: short -> ushort -> uint, because this can create wrong results if
1068 // the input short is negative!
1069 //
1070 return false;
1071}
1072
Chris Lattnerdfae8be2003-07-24 17:35:25 +00001073static bool ValueRequiresCast(const Value *V, const Type *Ty) {
1074 if (V->getType() == Ty || isa<Constant>(V)) return false;
1075 if (const CastInst *CI = dyn_cast<CastInst>(V))
1076 if (isEliminableCastOfCast(CI->getOperand(0)->getType(), CI->getType(), Ty))
1077 return false;
1078 return true;
1079}
1080
1081/// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
1082/// InsertBefore instruction. This is specialized a bit to avoid inserting
1083/// casts that are known to not do anything...
1084///
1085Value *InstCombiner::InsertOperandCastBefore(Value *V, const Type *DestTy,
1086 Instruction *InsertBefore) {
1087 if (V->getType() == DestTy) return V;
1088 if (Constant *C = dyn_cast<Constant>(V))
1089 return ConstantExpr::getCast(C, DestTy);
1090
1091 CastInst *CI = new CastInst(V, DestTy, V->getName());
1092 InsertNewInstBefore(CI, *InsertBefore);
1093 return CI;
1094}
Chris Lattner48a44f72002-05-02 17:06:02 +00001095
1096// CastInst simplification
Chris Lattner260ab202002-04-18 17:39:14 +00001097//
Chris Lattner113f4f42002-06-25 16:13:24 +00001098Instruction *InstCombiner::visitCastInst(CastInst &CI) {
Chris Lattner55d4bda2003-06-23 21:59:52 +00001099 Value *Src = CI.getOperand(0);
1100
Chris Lattner48a44f72002-05-02 17:06:02 +00001101 // If the user is casting a value to the same type, eliminate this cast
1102 // instruction...
Chris Lattner55d4bda2003-06-23 21:59:52 +00001103 if (CI.getType() == Src->getType())
1104 return ReplaceInstUsesWith(CI, Src);
Chris Lattner48a44f72002-05-02 17:06:02 +00001105
Chris Lattner48a44f72002-05-02 17:06:02 +00001106 // If casting the result of another cast instruction, try to eliminate this
1107 // one!
1108 //
Chris Lattner55d4bda2003-06-23 21:59:52 +00001109 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) {
Chris Lattnerdfae8be2003-07-24 17:35:25 +00001110 if (isEliminableCastOfCast(CSrc->getOperand(0)->getType(),
1111 CSrc->getType(), CI.getType())) {
Chris Lattner48a44f72002-05-02 17:06:02 +00001112 // This instruction now refers directly to the cast's src operand. This
1113 // has a good chance of making CSrc dead.
Chris Lattner113f4f42002-06-25 16:13:24 +00001114 CI.setOperand(0, CSrc->getOperand(0));
1115 return &CI;
Chris Lattner48a44f72002-05-02 17:06:02 +00001116 }
1117
Chris Lattner650b6da2002-08-02 20:00:25 +00001118 // If this is an A->B->A cast, and we are dealing with integral types, try
1119 // to convert this into a logical 'and' instruction.
1120 //
1121 if (CSrc->getOperand(0)->getType() == CI.getType() &&
Chris Lattnerb0b412e2002-09-03 01:08:28 +00001122 CI.getType()->isInteger() && CSrc->getType()->isInteger() &&
Chris Lattner650b6da2002-08-02 20:00:25 +00001123 CI.getType()->isUnsigned() && CSrc->getType()->isUnsigned() &&
1124 CSrc->getType()->getPrimitiveSize() < CI.getType()->getPrimitiveSize()){
1125 assert(CSrc->getType() != Type::ULongTy &&
1126 "Cannot have type bigger than ulong!");
Chris Lattner196897c2003-05-26 23:41:32 +00001127 uint64_t AndValue = (1ULL << CSrc->getType()->getPrimitiveSize()*8)-1;
Chris Lattner650b6da2002-08-02 20:00:25 +00001128 Constant *AndOp = ConstantUInt::get(CI.getType(), AndValue);
1129 return BinaryOperator::create(Instruction::And, CSrc->getOperand(0),
1130 AndOp);
1131 }
1132 }
1133
Chris Lattnerd0d51602003-06-21 23:12:02 +00001134 // If casting the result of a getelementptr instruction with no offset, turn
1135 // this into a cast of the original pointer!
1136 //
Chris Lattner55d4bda2003-06-23 21:59:52 +00001137 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
Chris Lattnerd0d51602003-06-21 23:12:02 +00001138 bool AllZeroOperands = true;
1139 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i)
1140 if (!isa<Constant>(GEP->getOperand(i)) ||
1141 !cast<Constant>(GEP->getOperand(i))->isNullValue()) {
1142 AllZeroOperands = false;
1143 break;
1144 }
1145 if (AllZeroOperands) {
1146 CI.setOperand(0, GEP->getOperand(0));
1147 return &CI;
1148 }
1149 }
1150
Chris Lattner55d4bda2003-06-23 21:59:52 +00001151 // If this is a cast to bool (which is effectively a "!=0" test), then we can
1152 // perform a few optimizations...
1153 //
1154 if (CI.getType() == Type::BoolTy) {
1155 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Src)) {
1156 Value *Op0 = BO->getOperand(0), *Op1 = BO->getOperand(1);
1157
Chris Lattnerbdb0ce02003-07-22 21:46:59 +00001158 switch (BO->getOpcode()) {
1159 case Instruction::Sub:
1160 case Instruction::Xor:
1161 // Replace (cast ([sub|xor] A, B) to bool) with (setne A, B)
Chris Lattner55d4bda2003-06-23 21:59:52 +00001162 return new SetCondInst(Instruction::SetNE, Op0, Op1);
1163
1164 // Replace (cast (add A, B) to bool) with (setne A, -B) if B is
1165 // efficiently invertible, or if the add has just this one use.
Chris Lattnerbdb0ce02003-07-22 21:46:59 +00001166 case Instruction::Add:
Chris Lattner55d4bda2003-06-23 21:59:52 +00001167 if (Value *NegVal = dyn_castNegVal(Op1))
1168 return new SetCondInst(Instruction::SetNE, Op0, NegVal);
1169 else if (Value *NegVal = dyn_castNegVal(Op0))
1170 return new SetCondInst(Instruction::SetNE, NegVal, Op1);
1171 else if (BO->use_size() == 1) {
1172 Instruction *Neg = BinaryOperator::createNeg(Op1, BO->getName());
1173 BO->setName("");
1174 InsertNewInstBefore(Neg, CI);
1175 return new SetCondInst(Instruction::SetNE, Op0, Neg);
1176 }
Chris Lattnerbdb0ce02003-07-22 21:46:59 +00001177 break;
1178
1179 case Instruction::And:
1180 // Replace (cast (and X, (1 << size(X)-1)) to bool) with x < 0,
1181 // converting X to be a signed value as appropriate. Don't worry about
1182 // bool values, as they will be optimized other ways if they occur in
1183 // this configuration.
1184 if (ConstantInt *CInt = dyn_cast<ConstantInt>(Op1))
1185 if (isSignBit(CInt)) {
1186 // If 'X' is not signed, insert a cast now...
1187 if (!CInt->getType()->isSigned()) {
1188 const Type *DestTy;
1189 switch (CInt->getType()->getPrimitiveID()) {
1190 case Type::UByteTyID: DestTy = Type::SByteTy; break;
1191 case Type::UShortTyID: DestTy = Type::ShortTy; break;
1192 case Type::UIntTyID: DestTy = Type::IntTy; break;
1193 case Type::ULongTyID: DestTy = Type::LongTy; break;
1194 default: assert(0 && "Invalid unsigned integer type!"); abort();
1195 }
1196 CastInst *NewCI = new CastInst(Op0, DestTy,
1197 Op0->getName()+".signed");
1198 InsertNewInstBefore(NewCI, CI);
1199 Op0 = NewCI;
1200 }
1201 return new SetCondInst(Instruction::SetLT, Op0,
1202 Constant::getNullValue(Op0->getType()));
1203 }
1204 break;
1205 default: break;
1206 }
Chris Lattner55d4bda2003-06-23 21:59:52 +00001207 }
1208 }
1209
Chris Lattnerdfae8be2003-07-24 17:35:25 +00001210 // If the source value is an instruction with only this use, we can attempt to
1211 // propagate the cast into the instruction. Also, only handle integral types
1212 // for now.
1213 if (Instruction *SrcI = dyn_cast<Instruction>(Src))
1214 if (SrcI->use_size() == 1 && Src->getType()->isIntegral() &&
1215 CI.getType()->isInteger()) { // Don't mess with casts to bool here
1216 const Type *DestTy = CI.getType();
1217 unsigned SrcBitSize = getTypeSizeInBits(Src->getType());
1218 unsigned DestBitSize = getTypeSizeInBits(DestTy);
1219
1220 Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
1221 Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
1222
1223 switch (SrcI->getOpcode()) {
1224 case Instruction::Add:
1225 case Instruction::Mul:
1226 case Instruction::And:
1227 case Instruction::Or:
1228 case Instruction::Xor:
1229 // If we are discarding information, or just changing the sign, rewrite.
1230 if (DestBitSize <= SrcBitSize && DestBitSize != 1) {
1231 // Don't insert two casts if they cannot be eliminated. We allow two
1232 // casts to be inserted if the sizes are the same. This could only be
1233 // converting signedness, which is a noop.
1234 if (DestBitSize == SrcBitSize || !ValueRequiresCast(Op1, DestTy) ||
1235 !ValueRequiresCast(Op0, DestTy)) {
1236 Value *Op0c = InsertOperandCastBefore(Op0, DestTy, SrcI);
1237 Value *Op1c = InsertOperandCastBefore(Op1, DestTy, SrcI);
1238 return BinaryOperator::create(cast<BinaryOperator>(SrcI)
1239 ->getOpcode(), Op0c, Op1c);
1240 }
1241 }
1242 break;
1243 case Instruction::Shl:
1244 // Allow changing the sign of the source operand. Do not allow changing
1245 // the size of the shift, UNLESS the shift amount is a constant. We
1246 // mush not change variable sized shifts to a smaller size, because it
1247 // is undefined to shift more bits out than exist in the value.
1248 if (DestBitSize == SrcBitSize ||
1249 (DestBitSize < SrcBitSize && isa<Constant>(Op1))) {
1250 Value *Op0c = InsertOperandCastBefore(Op0, DestTy, SrcI);
1251 return new ShiftInst(Instruction::Shl, Op0c, Op1);
1252 }
1253 break;
1254 }
1255 }
1256
Chris Lattner260ab202002-04-18 17:39:14 +00001257 return 0;
Chris Lattnerca081252001-12-14 16:52:21 +00001258}
1259
Chris Lattner970c33a2003-06-19 17:00:31 +00001260// CallInst simplification
1261//
1262Instruction *InstCombiner::visitCallInst(CallInst &CI) {
1263 if (transformConstExprCastCall(&CI)) return 0;
1264 return 0;
1265}
1266
1267// InvokeInst simplification
1268//
1269Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
1270 if (transformConstExprCastCall(&II)) return 0;
1271 return 0;
1272}
1273
1274// getPromotedType - Return the specified type promoted as it would be to pass
1275// though a va_arg area...
1276static const Type *getPromotedType(const Type *Ty) {
1277 switch (Ty->getPrimitiveID()) {
1278 case Type::SByteTyID:
1279 case Type::ShortTyID: return Type::IntTy;
1280 case Type::UByteTyID:
1281 case Type::UShortTyID: return Type::UIntTy;
1282 case Type::FloatTyID: return Type::DoubleTy;
1283 default: return Ty;
1284 }
1285}
1286
1287// transformConstExprCastCall - If the callee is a constexpr cast of a function,
1288// attempt to move the cast to the arguments of the call/invoke.
1289//
1290bool InstCombiner::transformConstExprCastCall(CallSite CS) {
1291 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
1292 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
1293 if (CE->getOpcode() != Instruction::Cast ||
1294 !isa<ConstantPointerRef>(CE->getOperand(0)))
1295 return false;
1296 ConstantPointerRef *CPR = cast<ConstantPointerRef>(CE->getOperand(0));
1297 if (!isa<Function>(CPR->getValue())) return false;
1298 Function *Callee = cast<Function>(CPR->getValue());
1299 Instruction *Caller = CS.getInstruction();
1300
1301 // Okay, this is a cast from a function to a different type. Unless doing so
1302 // would cause a type conversion of one of our arguments, change this call to
1303 // be a direct call with arguments casted to the appropriate types.
1304 //
1305 const FunctionType *FT = Callee->getFunctionType();
1306 const Type *OldRetTy = Caller->getType();
1307
1308 if (Callee->isExternal() &&
1309 !OldRetTy->isLosslesslyConvertibleTo(FT->getReturnType()))
1310 return false; // Cannot transform this return value...
1311
1312 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
1313 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
1314
1315 CallSite::arg_iterator AI = CS.arg_begin();
1316 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
1317 const Type *ParamTy = FT->getParamType(i);
1318 bool isConvertible = (*AI)->getType()->isLosslesslyConvertibleTo(ParamTy);
1319 if (Callee->isExternal() && !isConvertible) return false;
1320 }
1321
1322 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
1323 Callee->isExternal())
1324 return false; // Do not delete arguments unless we have a function body...
1325
1326 // Okay, we decided that this is a safe thing to do: go ahead and start
1327 // inserting cast instructions as necessary...
1328 std::vector<Value*> Args;
1329 Args.reserve(NumActualArgs);
1330
1331 AI = CS.arg_begin();
1332 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
1333 const Type *ParamTy = FT->getParamType(i);
1334 if ((*AI)->getType() == ParamTy) {
1335 Args.push_back(*AI);
1336 } else {
1337 Instruction *Cast = new CastInst(*AI, ParamTy, "tmp");
1338 InsertNewInstBefore(Cast, *Caller);
1339 Args.push_back(Cast);
1340 }
1341 }
1342
1343 // If the function takes more arguments than the call was taking, add them
1344 // now...
1345 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
1346 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
1347
1348 // If we are removing arguments to the function, emit an obnoxious warning...
1349 if (FT->getNumParams() < NumActualArgs)
1350 if (!FT->isVarArg()) {
1351 std::cerr << "WARNING: While resolving call to function '"
1352 << Callee->getName() << "' arguments were dropped!\n";
1353 } else {
1354 // Add all of the arguments in their promoted form to the arg list...
1355 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
1356 const Type *PTy = getPromotedType((*AI)->getType());
1357 if (PTy != (*AI)->getType()) {
1358 // Must promote to pass through va_arg area!
1359 Instruction *Cast = new CastInst(*AI, PTy, "tmp");
1360 InsertNewInstBefore(Cast, *Caller);
1361 Args.push_back(Cast);
1362 } else {
1363 Args.push_back(*AI);
1364 }
1365 }
1366 }
1367
1368 if (FT->getReturnType() == Type::VoidTy)
1369 Caller->setName(""); // Void type should not have a name...
1370
1371 Instruction *NC;
1372 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
1373 NC = new InvokeInst(Callee, II->getNormalDest(), II->getExceptionalDest(),
1374 Args, Caller->getName(), Caller);
1375 } else {
1376 NC = new CallInst(Callee, Args, Caller->getName(), Caller);
1377 }
1378
1379 // Insert a cast of the return type as necessary...
1380 Value *NV = NC;
1381 if (Caller->getType() != NV->getType() && !Caller->use_empty()) {
1382 if (NV->getType() != Type::VoidTy) {
1383 NV = NC = new CastInst(NC, Caller->getType(), "tmp");
1384 InsertNewInstBefore(NC, *Caller);
1385 AddUsesToWorkList(*Caller);
1386 } else {
1387 NV = Constant::getNullValue(Caller->getType());
1388 }
1389 }
1390
1391 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
1392 Caller->replaceAllUsesWith(NV);
1393 Caller->getParent()->getInstList().erase(Caller);
1394 removeFromWorkList(Caller);
1395 return true;
1396}
1397
1398
Chris Lattner48a44f72002-05-02 17:06:02 +00001399
Chris Lattnerbbbdd852002-05-06 18:06:38 +00001400// PHINode simplification
1401//
Chris Lattner113f4f42002-06-25 16:13:24 +00001402Instruction *InstCombiner::visitPHINode(PHINode &PN) {
Chris Lattnerbbbdd852002-05-06 18:06:38 +00001403 // If the PHI node only has one incoming value, eliminate the PHI node...
Chris Lattnere6794492002-08-12 21:17:25 +00001404 if (PN.getNumIncomingValues() == 1)
1405 return ReplaceInstUsesWith(PN, PN.getIncomingValue(0));
Chris Lattner9cd1e662002-08-20 15:35:35 +00001406
1407 // Otherwise if all of the incoming values are the same for the PHI, replace
1408 // the PHI node with the incoming value.
1409 //
Chris Lattnerf6c0efa2002-08-22 20:22:01 +00001410 Value *InVal = 0;
1411 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
1412 if (PN.getIncomingValue(i) != &PN) // Not the PHI node itself...
1413 if (InVal && PN.getIncomingValue(i) != InVal)
1414 return 0; // Not the same, bail out.
1415 else
1416 InVal = PN.getIncomingValue(i);
1417
1418 // The only case that could cause InVal to be null is if we have a PHI node
1419 // that only has entries for itself. In this case, there is no entry into the
1420 // loop, so kill the PHI.
1421 //
1422 if (InVal == 0) InVal = Constant::getNullValue(PN.getType());
Chris Lattnerbbbdd852002-05-06 18:06:38 +00001423
Chris Lattner9cd1e662002-08-20 15:35:35 +00001424 // All of the incoming values are the same, replace the PHI node now.
1425 return ReplaceInstUsesWith(PN, InVal);
Chris Lattnerbbbdd852002-05-06 18:06:38 +00001426}
1427
Chris Lattner48a44f72002-05-02 17:06:02 +00001428
Chris Lattner113f4f42002-06-25 16:13:24 +00001429Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
Chris Lattner471bd762003-05-22 19:07:21 +00001430 // Is it 'getelementptr %P, long 0' or 'getelementptr %P'
Chris Lattner113f4f42002-06-25 16:13:24 +00001431 // If so, eliminate the noop.
Chris Lattnerae7a0d32002-08-02 19:29:35 +00001432 if ((GEP.getNumOperands() == 2 &&
Chris Lattner136dab72002-09-11 01:21:33 +00001433 GEP.getOperand(1) == Constant::getNullValue(Type::LongTy)) ||
Chris Lattnere6794492002-08-12 21:17:25 +00001434 GEP.getNumOperands() == 1)
1435 return ReplaceInstUsesWith(GEP, GEP.getOperand(0));
Chris Lattner48a44f72002-05-02 17:06:02 +00001436
Chris Lattnerae7a0d32002-08-02 19:29:35 +00001437 // Combine Indices - If the source pointer to this getelementptr instruction
1438 // is a getelementptr instruction, combine the indices of the two
1439 // getelementptr instructions into a single instruction.
1440 //
Chris Lattnerc59af1d2002-08-17 22:21:59 +00001441 if (GetElementPtrInst *Src = dyn_cast<GetElementPtrInst>(GEP.getOperand(0))) {
Chris Lattnerae7a0d32002-08-02 19:29:35 +00001442 std::vector<Value *> Indices;
Chris Lattnerca081252001-12-14 16:52:21 +00001443
Chris Lattnerae7a0d32002-08-02 19:29:35 +00001444 // Can we combine the two pointer arithmetics offsets?
Chris Lattner471bd762003-05-22 19:07:21 +00001445 if (Src->getNumOperands() == 2 && isa<Constant>(Src->getOperand(1)) &&
1446 isa<Constant>(GEP.getOperand(1))) {
Chris Lattner235af562003-03-05 22:33:14 +00001447 // Replace: gep (gep %P, long C1), long C2, ...
1448 // With: gep %P, long (C1+C2), ...
Chris Lattner34428442003-05-27 16:40:51 +00001449 Value *Sum = ConstantExpr::get(Instruction::Add,
1450 cast<Constant>(Src->getOperand(1)),
1451 cast<Constant>(GEP.getOperand(1)));
Chris Lattner235af562003-03-05 22:33:14 +00001452 assert(Sum && "Constant folding of longs failed!?");
1453 GEP.setOperand(0, Src->getOperand(0));
1454 GEP.setOperand(1, Sum);
1455 AddUsesToWorkList(*Src); // Reduce use count of Src
1456 return &GEP;
Chris Lattner471bd762003-05-22 19:07:21 +00001457 } else if (Src->getNumOperands() == 2) {
Chris Lattner235af562003-03-05 22:33:14 +00001458 // Replace: gep (gep %P, long B), long A, ...
1459 // With: T = long A+B; gep %P, T, ...
1460 //
1461 Value *Sum = BinaryOperator::create(Instruction::Add, Src->getOperand(1),
1462 GEP.getOperand(1),
1463 Src->getName()+".sum", &GEP);
1464 GEP.setOperand(0, Src->getOperand(0));
1465 GEP.setOperand(1, Sum);
1466 WorkList.push_back(cast<Instruction>(Sum));
1467 return &GEP;
Chris Lattner5d606a02002-11-04 16:43:32 +00001468 } else if (*GEP.idx_begin() == Constant::getNullValue(Type::LongTy) &&
Chris Lattnera8339e32002-09-17 21:05:42 +00001469 Src->getNumOperands() != 1) {
Chris Lattnerae7a0d32002-08-02 19:29:35 +00001470 // Otherwise we can do the fold if the first index of the GEP is a zero
1471 Indices.insert(Indices.end(), Src->idx_begin(), Src->idx_end());
1472 Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
Chris Lattner5d606a02002-11-04 16:43:32 +00001473 } else if (Src->getOperand(Src->getNumOperands()-1) ==
1474 Constant::getNullValue(Type::LongTy)) {
1475 // If the src gep ends with a constant array index, merge this get into
1476 // it, even if we have a non-zero array index.
1477 Indices.insert(Indices.end(), Src->idx_begin(), Src->idx_end()-1);
1478 Indices.insert(Indices.end(), GEP.idx_begin(), GEP.idx_end());
Chris Lattnerae7a0d32002-08-02 19:29:35 +00001479 }
1480
1481 if (!Indices.empty())
1482 return new GetElementPtrInst(Src->getOperand(0), Indices, GEP.getName());
Chris Lattnerc59af1d2002-08-17 22:21:59 +00001483
1484 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(GEP.getOperand(0))) {
1485 // GEP of global variable. If all of the indices for this GEP are
1486 // constants, we can promote this to a constexpr instead of an instruction.
1487
1488 // Scan for nonconstants...
1489 std::vector<Constant*> Indices;
1490 User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
1491 for (; I != E && isa<Constant>(*I); ++I)
1492 Indices.push_back(cast<Constant>(*I));
1493
1494 if (I == E) { // If they are all constants...
Chris Lattner46b3d302003-04-16 22:40:51 +00001495 Constant *CE =
Chris Lattnerc59af1d2002-08-17 22:21:59 +00001496 ConstantExpr::getGetElementPtr(ConstantPointerRef::get(GV), Indices);
1497
1498 // Replace all uses of the GEP with the new constexpr...
1499 return ReplaceInstUsesWith(GEP, CE);
1500 }
Chris Lattnerca081252001-12-14 16:52:21 +00001501 }
1502
Chris Lattnerca081252001-12-14 16:52:21 +00001503 return 0;
1504}
1505
Chris Lattner1085bdf2002-11-04 16:18:53 +00001506Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
1507 // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
1508 if (AI.isArrayAllocation()) // Check C != 1
1509 if (const ConstantUInt *C = dyn_cast<ConstantUInt>(AI.getArraySize())) {
1510 const Type *NewTy = ArrayType::get(AI.getAllocatedType(), C->getValue());
Chris Lattnera2620ac2002-11-09 00:49:43 +00001511 AllocationInst *New = 0;
Chris Lattner1085bdf2002-11-04 16:18:53 +00001512
1513 // Create and insert the replacement instruction...
1514 if (isa<MallocInst>(AI))
1515 New = new MallocInst(NewTy, 0, AI.getName(), &AI);
Chris Lattnera2620ac2002-11-09 00:49:43 +00001516 else {
1517 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
Chris Lattner1085bdf2002-11-04 16:18:53 +00001518 New = new AllocaInst(NewTy, 0, AI.getName(), &AI);
Chris Lattnera2620ac2002-11-09 00:49:43 +00001519 }
Chris Lattner1085bdf2002-11-04 16:18:53 +00001520
1521 // Scan to the end of the allocation instructions, to skip over a block of
1522 // allocas if possible...
1523 //
1524 BasicBlock::iterator It = New;
1525 while (isa<AllocationInst>(*It)) ++It;
1526
1527 // Now that I is pointing to the first non-allocation-inst in the block,
1528 // insert our getelementptr instruction...
1529 //
1530 std::vector<Value*> Idx(2, Constant::getNullValue(Type::LongTy));
1531 Value *V = new GetElementPtrInst(New, Idx, New->getName()+".sub", It);
1532
1533 // Now make everything use the getelementptr instead of the original
1534 // allocation.
1535 ReplaceInstUsesWith(AI, V);
1536 return &AI;
1537 }
1538 return 0;
1539}
1540
Chris Lattner0f1d8a32003-06-26 05:06:25 +00001541/// GetGEPGlobalInitializer - Given a constant, and a getelementptr
1542/// constantexpr, return the constant value being addressed by the constant
1543/// expression, or null if something is funny.
1544///
1545static Constant *GetGEPGlobalInitializer(Constant *C, ConstantExpr *CE) {
1546 if (CE->getOperand(1) != Constant::getNullValue(Type::LongTy))
1547 return 0; // Do not allow stepping over the value!
1548
1549 // Loop over all of the operands, tracking down which value we are
1550 // addressing...
1551 for (unsigned i = 2, e = CE->getNumOperands(); i != e; ++i)
1552 if (ConstantUInt *CU = dyn_cast<ConstantUInt>(CE->getOperand(i))) {
1553 ConstantStruct *CS = cast<ConstantStruct>(C);
1554 if (CU->getValue() >= CS->getValues().size()) return 0;
1555 C = cast<Constant>(CS->getValues()[CU->getValue()]);
1556 } else if (ConstantSInt *CS = dyn_cast<ConstantSInt>(CE->getOperand(i))) {
1557 ConstantArray *CA = cast<ConstantArray>(C);
1558 if ((uint64_t)CS->getValue() >= CA->getValues().size()) return 0;
1559 C = cast<Constant>(CA->getValues()[CS->getValue()]);
1560 } else
1561 return 0;
1562 return C;
1563}
1564
1565Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
1566 Value *Op = LI.getOperand(0);
1567 if (ConstantPointerRef *CPR = dyn_cast<ConstantPointerRef>(Op))
1568 Op = CPR->getValue();
1569
1570 // Instcombine load (constant global) into the value loaded...
1571 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
Chris Lattnerbdb0ce02003-07-22 21:46:59 +00001572 if (GV->isConstant() && !GV->isExternal())
Chris Lattner0f1d8a32003-06-26 05:06:25 +00001573 return ReplaceInstUsesWith(LI, GV->getInitializer());
1574
1575 // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded...
1576 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op))
1577 if (CE->getOpcode() == Instruction::GetElementPtr)
1578 if (ConstantPointerRef *G=dyn_cast<ConstantPointerRef>(CE->getOperand(0)))
1579 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(G->getValue()))
Chris Lattnerbdb0ce02003-07-22 21:46:59 +00001580 if (GV->isConstant() && !GV->isExternal())
Chris Lattner0f1d8a32003-06-26 05:06:25 +00001581 if (Constant *V = GetGEPGlobalInitializer(GV->getInitializer(), CE))
1582 return ReplaceInstUsesWith(LI, V);
1583 return 0;
1584}
1585
1586
Chris Lattner9eef8a72003-06-04 04:46:00 +00001587Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
1588 // Change br (not X), label True, label False to: br X, label False, True
Chris Lattner45789ac2003-06-05 20:12:51 +00001589 if (BI.isConditional() && !isa<Constant>(BI.getCondition()))
Chris Lattnere967b342003-06-04 05:10:11 +00001590 if (Value *V = dyn_castNotVal(BI.getCondition())) {
1591 BasicBlock *TrueDest = BI.getSuccessor(0);
1592 BasicBlock *FalseDest = BI.getSuccessor(1);
1593 // Swap Destinations and condition...
1594 BI.setCondition(V);
1595 BI.setSuccessor(0, FalseDest);
1596 BI.setSuccessor(1, TrueDest);
1597 return &BI;
1598 }
Chris Lattner9eef8a72003-06-04 04:46:00 +00001599 return 0;
1600}
Chris Lattner1085bdf2002-11-04 16:18:53 +00001601
Chris Lattnerca081252001-12-14 16:52:21 +00001602
Chris Lattner99f48c62002-09-02 04:59:56 +00001603void InstCombiner::removeFromWorkList(Instruction *I) {
1604 WorkList.erase(std::remove(WorkList.begin(), WorkList.end(), I),
1605 WorkList.end());
1606}
1607
Chris Lattner113f4f42002-06-25 16:13:24 +00001608bool InstCombiner::runOnFunction(Function &F) {
Chris Lattner260ab202002-04-18 17:39:14 +00001609 bool Changed = false;
Chris Lattnerca081252001-12-14 16:52:21 +00001610
Chris Lattner260ab202002-04-18 17:39:14 +00001611 WorkList.insert(WorkList.end(), inst_begin(F), inst_end(F));
Chris Lattnerca081252001-12-14 16:52:21 +00001612
1613 while (!WorkList.empty()) {
1614 Instruction *I = WorkList.back(); // Get an instruction from the worklist
1615 WorkList.pop_back();
1616
Misha Brukman632df282002-10-29 23:06:16 +00001617 // Check to see if we can DCE or ConstantPropagate the instruction...
Chris Lattner99f48c62002-09-02 04:59:56 +00001618 // Check to see if we can DIE the instruction...
1619 if (isInstructionTriviallyDead(I)) {
1620 // Add operands to the worklist...
1621 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
1622 if (Instruction *Op = dyn_cast<Instruction>(I->getOperand(i)))
1623 WorkList.push_back(Op);
1624
1625 ++NumDeadInst;
1626 BasicBlock::iterator BBI = I;
1627 if (dceInstruction(BBI)) {
1628 removeFromWorkList(I);
1629 continue;
1630 }
1631 }
1632
Misha Brukman632df282002-10-29 23:06:16 +00001633 // Instruction isn't dead, see if we can constant propagate it...
Chris Lattner99f48c62002-09-02 04:59:56 +00001634 if (Constant *C = ConstantFoldInstruction(I)) {
1635 // Add operands to the worklist...
1636 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
1637 if (Instruction *Op = dyn_cast<Instruction>(I->getOperand(i)))
1638 WorkList.push_back(Op);
Chris Lattnerc6509f42002-12-05 22:41:53 +00001639 ReplaceInstUsesWith(*I, C);
1640
Chris Lattner99f48c62002-09-02 04:59:56 +00001641 ++NumConstProp;
1642 BasicBlock::iterator BBI = I;
1643 if (dceInstruction(BBI)) {
1644 removeFromWorkList(I);
1645 continue;
1646 }
1647 }
1648
Chris Lattnerca081252001-12-14 16:52:21 +00001649 // Now that we have an instruction, try combining it to simplify it...
Chris Lattnerae7a0d32002-08-02 19:29:35 +00001650 if (Instruction *Result = visit(*I)) {
Chris Lattner0b18c1d2002-05-10 15:38:35 +00001651 ++NumCombined;
Chris Lattner260ab202002-04-18 17:39:14 +00001652 // Should we replace the old instruction with a new one?
Chris Lattner053c0932002-05-14 15:24:07 +00001653 if (Result != I) {
1654 // Instructions can end up on the worklist more than once. Make sure
1655 // we do not process an instruction that has been deleted.
Chris Lattner99f48c62002-09-02 04:59:56 +00001656 removeFromWorkList(I);
Chris Lattner260ab202002-04-18 17:39:14 +00001657 ReplaceInstWithInst(I, Result);
Chris Lattner113f4f42002-06-25 16:13:24 +00001658 } else {
Chris Lattnerae7a0d32002-08-02 19:29:35 +00001659 BasicBlock::iterator II = I;
1660
1661 // If the instruction was modified, it's possible that it is now dead.
1662 // if so, remove it.
1663 if (dceInstruction(II)) {
1664 // Instructions may end up in the worklist more than once. Erase them
1665 // all.
Chris Lattner99f48c62002-09-02 04:59:56 +00001666 removeFromWorkList(I);
Chris Lattnerae7a0d32002-08-02 19:29:35 +00001667 Result = 0;
1668 }
Chris Lattner053c0932002-05-14 15:24:07 +00001669 }
Chris Lattner260ab202002-04-18 17:39:14 +00001670
Chris Lattnerae7a0d32002-08-02 19:29:35 +00001671 if (Result) {
1672 WorkList.push_back(Result);
1673 AddUsesToWorkList(*Result);
1674 }
Chris Lattner260ab202002-04-18 17:39:14 +00001675 Changed = true;
Chris Lattnerca081252001-12-14 16:52:21 +00001676 }
1677 }
1678
Chris Lattner260ab202002-04-18 17:39:14 +00001679 return Changed;
Chris Lattner04805fa2002-02-26 21:46:54 +00001680}
1681
1682Pass *createInstructionCombiningPass() {
Chris Lattner260ab202002-04-18 17:39:14 +00001683 return new InstCombiner();
Chris Lattner04805fa2002-02-26 21:46:54 +00001684}