blob: d2d8c93b5f74178deb35267bd79c8c433a6ba4d0 [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
Chris Lattnerede3fe02003-08-13 04:18:28 +000022// 5. add X, X is represented as (X*2) => (X << 1)
23// 6. Multiplies with a power-of-two constant argument are transformed into
24// shifts.
Chris Lattnerbfb1d032003-07-23 21:41:57 +000025// N. This list is incomplete
26//
Chris Lattnerca081252001-12-14 16:52:21 +000027//===----------------------------------------------------------------------===//
28
Chris Lattnerb4cfa7f2002-05-07 20:03:00 +000029#include "llvm/Transforms/Scalar.h"
Chris Lattner9b55e5a2002-05-07 18:12:18 +000030#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Chris Lattnerae7a0d32002-08-02 19:29:35 +000031#include "llvm/Transforms/Utils/Local.h"
Chris Lattner471bd762003-05-22 19:07:21 +000032#include "llvm/Instructions.h"
Chris Lattner04805fa2002-02-26 21:46:54 +000033#include "llvm/Pass.h"
Chris Lattner34428442003-05-27 16:40:51 +000034#include "llvm/Constants.h"
35#include "llvm/ConstantHandling.h"
Chris Lattner1085bdf2002-11-04 16:18:53 +000036#include "llvm/DerivedTypes.h"
Chris Lattner0f1d8a32003-06-26 05:06:25 +000037#include "llvm/GlobalVariable.h"
Chris Lattner60a65912002-02-12 21:07:25 +000038#include "llvm/Support/InstIterator.h"
Chris Lattner260ab202002-04-18 17:39:14 +000039#include "llvm/Support/InstVisitor.h"
Chris Lattner970c33a2003-06-19 17:00:31 +000040#include "llvm/Support/CallSite.h"
Chris Lattnerbf3a0992002-10-01 22:38:41 +000041#include "Support/Statistic.h"
Chris Lattner053c0932002-05-14 15:24:07 +000042#include <algorithm>
Chris Lattnerca081252001-12-14 16:52:21 +000043
Chris Lattner260ab202002-04-18 17:39:14 +000044namespace {
Chris Lattnerbf3a0992002-10-01 22:38:41 +000045 Statistic<> NumCombined ("instcombine", "Number of insts combined");
46 Statistic<> NumConstProp("instcombine", "Number of constant folds");
47 Statistic<> NumDeadInst ("instcombine", "Number of dead inst eliminated");
48
Chris Lattnerc8e66542002-04-27 06:56:12 +000049 class InstCombiner : public FunctionPass,
Chris Lattner260ab202002-04-18 17:39:14 +000050 public InstVisitor<InstCombiner, Instruction*> {
51 // Worklist of all of the instructions that need to be simplified.
52 std::vector<Instruction*> WorkList;
53
Chris Lattner113f4f42002-06-25 16:13:24 +000054 void AddUsesToWorkList(Instruction &I) {
Chris Lattner260ab202002-04-18 17:39:14 +000055 // The instruction was simplified, add all users of the instruction to
56 // the work lists because they might get more simplified now...
57 //
Chris Lattner113f4f42002-06-25 16:13:24 +000058 for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
Chris Lattner260ab202002-04-18 17:39:14 +000059 UI != UE; ++UI)
60 WorkList.push_back(cast<Instruction>(*UI));
61 }
62
Chris Lattner99f48c62002-09-02 04:59:56 +000063 // removeFromWorkList - remove all instances of I from the worklist.
64 void removeFromWorkList(Instruction *I);
Chris Lattner260ab202002-04-18 17:39:14 +000065 public:
Chris Lattner113f4f42002-06-25 16:13:24 +000066 virtual bool runOnFunction(Function &F);
Chris Lattner260ab202002-04-18 17:39:14 +000067
Chris Lattnerf12cc842002-04-28 21:27:06 +000068 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Chris Lattner820d9712002-10-21 20:00:28 +000069 AU.setPreservesCFG();
Chris Lattnerf12cc842002-04-28 21:27:06 +000070 }
71
Chris Lattner260ab202002-04-18 17:39:14 +000072 // Visitation implementation - Implement instruction combining for different
73 // instruction types. The semantics are as follows:
74 // Return Value:
75 // null - No change was made
Chris Lattnere6794492002-08-12 21:17:25 +000076 // I - Change was made, I is still valid, I may be dead though
Chris Lattner260ab202002-04-18 17:39:14 +000077 // otherwise - Change was made, replace I with returned instruction
78 //
Chris Lattner113f4f42002-06-25 16:13:24 +000079 Instruction *visitAdd(BinaryOperator &I);
80 Instruction *visitSub(BinaryOperator &I);
81 Instruction *visitMul(BinaryOperator &I);
82 Instruction *visitDiv(BinaryOperator &I);
83 Instruction *visitRem(BinaryOperator &I);
84 Instruction *visitAnd(BinaryOperator &I);
85 Instruction *visitOr (BinaryOperator &I);
86 Instruction *visitXor(BinaryOperator &I);
87 Instruction *visitSetCondInst(BinaryOperator &I);
Chris Lattnere8d6c602003-03-10 19:16:08 +000088 Instruction *visitShiftInst(ShiftInst &I);
Chris Lattner113f4f42002-06-25 16:13:24 +000089 Instruction *visitCastInst(CastInst &CI);
Chris Lattner970c33a2003-06-19 17:00:31 +000090 Instruction *visitCallInst(CallInst &CI);
91 Instruction *visitInvokeInst(InvokeInst &II);
Chris Lattner113f4f42002-06-25 16:13:24 +000092 Instruction *visitPHINode(PHINode &PN);
93 Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
Chris Lattner1085bdf2002-11-04 16:18:53 +000094 Instruction *visitAllocationInst(AllocationInst &AI);
Chris Lattner0f1d8a32003-06-26 05:06:25 +000095 Instruction *visitLoadInst(LoadInst &LI);
Chris Lattner9eef8a72003-06-04 04:46:00 +000096 Instruction *visitBranchInst(BranchInst &BI);
Chris Lattner260ab202002-04-18 17:39:14 +000097
98 // visitInstruction - Specify what to return for unhandled instructions...
Chris Lattner113f4f42002-06-25 16:13:24 +000099 Instruction *visitInstruction(Instruction &I) { return 0; }
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000100
Chris Lattner970c33a2003-06-19 17:00:31 +0000101 private:
102 bool transformConstExprCastCall(CallSite CS);
103
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000104 // InsertNewInstBefore - insert an instruction New before instruction Old
105 // in the program. Add the new instruction to the worklist.
106 //
107 void InsertNewInstBefore(Instruction *New, Instruction &Old) {
Chris Lattner65217ff2002-08-23 18:32:43 +0000108 assert(New && New->getParent() == 0 &&
109 "New instruction already inserted into a basic block!");
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000110 BasicBlock *BB = Old.getParent();
111 BB->getInstList().insert(&Old, New); // Insert inst
112 WorkList.push_back(New); // Add to worklist
113 }
114
115 // ReplaceInstUsesWith - This method is to be used when an instruction is
116 // found to be dead, replacable with another preexisting expression. Here
117 // we add all uses of I to the worklist, replace all uses of I with the new
118 // value, then return I, so that the inst combiner will know that I was
119 // modified.
120 //
121 Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
122 AddUsesToWorkList(I); // Add all modified instrs to worklist
123 I.replaceAllUsesWith(V);
124 return &I;
125 }
Chris Lattner7fb29e12003-03-11 00:12:48 +0000126
Chris Lattnerdfae8be2003-07-24 17:35:25 +0000127 /// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
128 /// InsertBefore instruction. This is specialized a bit to avoid inserting
129 /// casts that are known to not do anything...
130 ///
131 Value *InsertOperandCastBefore(Value *V, const Type *DestTy,
132 Instruction *InsertBefore);
133
Chris Lattner7fb29e12003-03-11 00:12:48 +0000134 // SimplifyCommutative - This performs a few simplifications for commutative
135 // operators...
136 bool SimplifyCommutative(BinaryOperator &I);
Chris Lattner260ab202002-04-18 17:39:14 +0000137 };
Chris Lattnerb28b6802002-07-23 18:06:35 +0000138
Chris Lattnerc8b70922002-07-26 21:12:46 +0000139 RegisterOpt<InstCombiner> X("instcombine", "Combine redundant instructions");
Chris Lattner260ab202002-04-18 17:39:14 +0000140}
141
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000142// getComplexity: Assign a complexity or rank value to LLVM Values...
143// 0 -> Constant, 1 -> Other, 2 -> Argument, 2 -> Unary, 3 -> OtherInst
144static unsigned getComplexity(Value *V) {
145 if (isa<Instruction>(V)) {
146 if (BinaryOperator::isNeg(V) || BinaryOperator::isNot(V))
147 return 2;
148 return 3;
149 }
150 if (isa<Argument>(V)) return 2;
151 return isa<Constant>(V) ? 0 : 1;
152}
Chris Lattner260ab202002-04-18 17:39:14 +0000153
Chris Lattner7fb29e12003-03-11 00:12:48 +0000154// isOnlyUse - Return true if this instruction will be deleted if we stop using
155// it.
156static bool isOnlyUse(Value *V) {
157 return V->use_size() == 1 || isa<Constant>(V);
158}
159
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000160// SimplifyCommutative - This performs a few simplifications for commutative
161// operators:
Chris Lattner260ab202002-04-18 17:39:14 +0000162//
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000163// 1. Order operands such that they are listed from right (least complex) to
164// left (most complex). This puts constants before unary operators before
165// binary operators.
166//
Chris Lattner7fb29e12003-03-11 00:12:48 +0000167// 2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
168// 3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000169//
Chris Lattner7fb29e12003-03-11 00:12:48 +0000170bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000171 bool Changed = false;
172 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
173 Changed = !I.swapOperands();
174
175 if (!I.isAssociative()) return Changed;
176 Instruction::BinaryOps Opcode = I.getOpcode();
Chris Lattner7fb29e12003-03-11 00:12:48 +0000177 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
178 if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
179 if (isa<Constant>(I.getOperand(1))) {
Chris Lattner34428442003-05-27 16:40:51 +0000180 Constant *Folded = ConstantExpr::get(I.getOpcode(),
181 cast<Constant>(I.getOperand(1)),
182 cast<Constant>(Op->getOperand(1)));
Chris Lattner7fb29e12003-03-11 00:12:48 +0000183 I.setOperand(0, Op->getOperand(0));
184 I.setOperand(1, Folded);
185 return true;
186 } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
187 if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
188 isOnlyUse(Op) && isOnlyUse(Op1)) {
189 Constant *C1 = cast<Constant>(Op->getOperand(1));
190 Constant *C2 = cast<Constant>(Op1->getOperand(1));
191
192 // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattner34428442003-05-27 16:40:51 +0000193 Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
Chris Lattner7fb29e12003-03-11 00:12:48 +0000194 Instruction *New = BinaryOperator::create(Opcode, Op->getOperand(0),
195 Op1->getOperand(0),
196 Op1->getName(), &I);
197 WorkList.push_back(New);
198 I.setOperand(0, New);
199 I.setOperand(1, Folded);
200 return true;
201 }
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000202 }
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000203 return Changed;
Chris Lattner260ab202002-04-18 17:39:14 +0000204}
Chris Lattnerca081252001-12-14 16:52:21 +0000205
Chris Lattnerbb74e222003-03-10 23:06:50 +0000206// dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
207// if the LHS is a constant zero (which is the 'negate' form).
Chris Lattner9fa53de2002-05-06 16:49:18 +0000208//
Chris Lattnerbb74e222003-03-10 23:06:50 +0000209static inline Value *dyn_castNegVal(Value *V) {
210 if (BinaryOperator::isNeg(V))
211 return BinaryOperator::getNegArgument(cast<BinaryOperator>(V));
212
Chris Lattner9244df62003-04-30 22:19:10 +0000213 // Constants can be considered to be negated values if they can be folded...
214 if (Constant *C = dyn_cast<Constant>(V))
Chris Lattner34428442003-05-27 16:40:51 +0000215 return ConstantExpr::get(Instruction::Sub,
216 Constant::getNullValue(V->getType()), C);
Chris Lattnerbb74e222003-03-10 23:06:50 +0000217 return 0;
Chris Lattner9fa53de2002-05-06 16:49:18 +0000218}
219
Chris Lattnerbb74e222003-03-10 23:06:50 +0000220static inline Value *dyn_castNotVal(Value *V) {
221 if (BinaryOperator::isNot(V))
222 return BinaryOperator::getNotArgument(cast<BinaryOperator>(V));
223
224 // Constants can be considered to be not'ed values...
Chris Lattnerdd65d862003-04-30 22:34:06 +0000225 if (ConstantIntegral *C = dyn_cast<ConstantIntegral>(V))
Chris Lattner34428442003-05-27 16:40:51 +0000226 return ConstantExpr::get(Instruction::Xor,
227 ConstantIntegral::getAllOnesValue(C->getType()),C);
Chris Lattnerbb74e222003-03-10 23:06:50 +0000228 return 0;
229}
230
Chris Lattner7fb29e12003-03-11 00:12:48 +0000231// dyn_castFoldableMul - If this value is a multiply that can be folded into
232// other computations (because it has a constant operand), return the
233// non-constant operand of the multiply.
234//
235static inline Value *dyn_castFoldableMul(Value *V) {
236 if (V->use_size() == 1 && V->getType()->isInteger())
237 if (Instruction *I = dyn_cast<Instruction>(V))
238 if (I->getOpcode() == Instruction::Mul)
239 if (isa<Constant>(I->getOperand(1)))
240 return I->getOperand(0);
241 return 0;
Chris Lattner3082c5a2003-02-18 19:28:33 +0000242}
Chris Lattner31ae8632002-08-14 17:51:49 +0000243
Chris Lattner7fb29e12003-03-11 00:12:48 +0000244// dyn_castMaskingAnd - If this value is an And instruction masking a value with
245// a constant, return the constant being anded with.
246//
Chris Lattner01d56392003-08-12 19:17:27 +0000247template<class ValueType>
248static inline Constant *dyn_castMaskingAnd(ValueType *V) {
Chris Lattner7fb29e12003-03-11 00:12:48 +0000249 if (Instruction *I = dyn_cast<Instruction>(V))
250 if (I->getOpcode() == Instruction::And)
251 return dyn_cast<Constant>(I->getOperand(1));
252
253 // If this is a constant, it acts just like we were masking with it.
254 return dyn_cast<Constant>(V);
255}
Chris Lattner3082c5a2003-02-18 19:28:33 +0000256
257// Log2 - Calculate the log base 2 for the specified value if it is exactly a
258// power of 2.
259static unsigned Log2(uint64_t Val) {
260 assert(Val > 1 && "Values 0 and 1 should be handled elsewhere!");
261 unsigned Count = 0;
262 while (Val != 1) {
263 if (Val & 1) return 0; // Multiple bits set?
264 Val >>= 1;
265 ++Count;
266 }
267 return Count;
Chris Lattner31ae8632002-08-14 17:51:49 +0000268}
269
Chris Lattner113f4f42002-06-25 16:13:24 +0000270Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000271 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +0000272 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
Chris Lattner9fa53de2002-05-06 16:49:18 +0000273
274 // Eliminate 'add int %X, 0'
Chris Lattnere6794492002-08-12 21:17:25 +0000275 if (RHS == Constant::getNullValue(I.getType()))
276 return ReplaceInstUsesWith(I, LHS);
Chris Lattner9fa53de2002-05-06 16:49:18 +0000277
Chris Lattnerede3fe02003-08-13 04:18:28 +0000278 // Convert 'add X, X' to 'shl X, 1'
279 if (LHS == RHS && I.getType()->isInteger())
280 return new ShiftInst(Instruction::Shl, LHS,
281 ConstantInt::get(Type::UByteTy, 1));
282
Chris Lattner147e9752002-05-08 22:46:53 +0000283 // -A + B --> B - A
Chris Lattnerbb74e222003-03-10 23:06:50 +0000284 if (Value *V = dyn_castNegVal(LHS))
Chris Lattner147e9752002-05-08 22:46:53 +0000285 return BinaryOperator::create(Instruction::Sub, RHS, V);
Chris Lattner9fa53de2002-05-06 16:49:18 +0000286
287 // A + -B --> A - B
Chris Lattnerbb74e222003-03-10 23:06:50 +0000288 if (!isa<Constant>(RHS))
289 if (Value *V = dyn_castNegVal(RHS))
290 return BinaryOperator::create(Instruction::Sub, LHS, V);
Chris Lattner260ab202002-04-18 17:39:14 +0000291
Chris Lattner57c8d992003-02-18 19:57:07 +0000292 // X*C + X --> X * (C+1)
293 if (dyn_castFoldableMul(LHS) == RHS) {
Chris Lattner34428442003-05-27 16:40:51 +0000294 Constant *CP1 =
295 ConstantExpr::get(Instruction::Add,
296 cast<Constant>(cast<Instruction>(LHS)->getOperand(1)),
297 ConstantInt::get(I.getType(), 1));
Chris Lattner57c8d992003-02-18 19:57:07 +0000298 return BinaryOperator::create(Instruction::Mul, RHS, CP1);
299 }
300
301 // X + X*C --> X * (C+1)
302 if (dyn_castFoldableMul(RHS) == LHS) {
Chris Lattner34428442003-05-27 16:40:51 +0000303 Constant *CP1 =
304 ConstantExpr::get(Instruction::Add,
305 cast<Constant>(cast<Instruction>(RHS)->getOperand(1)),
306 ConstantInt::get(I.getType(), 1));
Chris Lattner57c8d992003-02-18 19:57:07 +0000307 return BinaryOperator::create(Instruction::Mul, LHS, CP1);
308 }
309
Chris Lattner7fb29e12003-03-11 00:12:48 +0000310 // (A & C1)+(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
311 if (Constant *C1 = dyn_castMaskingAnd(LHS))
312 if (Constant *C2 = dyn_castMaskingAnd(RHS))
Chris Lattner34428442003-05-27 16:40:51 +0000313 if (ConstantExpr::get(Instruction::And, C1, C2)->isNullValue())
Chris Lattner7fb29e12003-03-11 00:12:48 +0000314 return BinaryOperator::create(Instruction::Or, LHS, RHS);
315
Chris Lattner113f4f42002-06-25 16:13:24 +0000316 return Changed ? &I : 0;
Chris Lattner260ab202002-04-18 17:39:14 +0000317}
318
Chris Lattnerbdb0ce02003-07-22 21:46:59 +0000319// isSignBit - Return true if the value represented by the constant only has the
320// highest order bit set.
321static bool isSignBit(ConstantInt *CI) {
322 unsigned NumBits = CI->getType()->getPrimitiveSize()*8;
323 return (CI->getRawValue() & ~(-1LL << NumBits)) == (1ULL << (NumBits-1));
324}
325
Chris Lattnerdfae8be2003-07-24 17:35:25 +0000326static unsigned getTypeSizeInBits(const Type *Ty) {
327 return Ty == Type::BoolTy ? 1 : Ty->getPrimitiveSize()*8;
328}
329
Chris Lattner113f4f42002-06-25 16:13:24 +0000330Instruction *InstCombiner::visitSub(BinaryOperator &I) {
Chris Lattner113f4f42002-06-25 16:13:24 +0000331 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000332
Chris Lattnere6794492002-08-12 21:17:25 +0000333 if (Op0 == Op1) // sub X, X -> 0
334 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner260ab202002-04-18 17:39:14 +0000335
Chris Lattnere6794492002-08-12 21:17:25 +0000336 // If this is a 'B = x-(-A)', change to B = x+A...
Chris Lattnerbb74e222003-03-10 23:06:50 +0000337 if (Value *V = dyn_castNegVal(Op1))
Chris Lattner147e9752002-05-08 22:46:53 +0000338 return BinaryOperator::create(Instruction::Add, Op0, V);
Chris Lattner9fa53de2002-05-06 16:49:18 +0000339
Chris Lattner3082c5a2003-02-18 19:28:33 +0000340 // Replace (-1 - A) with (~A)...
341 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0))
342 if (C->isAllOnesValue())
343 return BinaryOperator::createNot(Op1);
Chris Lattnerad3c4952002-05-09 01:29:19 +0000344
Chris Lattner3082c5a2003-02-18 19:28:33 +0000345 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1))
346 if (Op1I->use_size() == 1) {
347 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
348 // is not used by anyone else...
349 //
350 if (Op1I->getOpcode() == Instruction::Sub) {
351 // Swap the two operands of the subexpr...
352 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
353 Op1I->setOperand(0, IIOp1);
354 Op1I->setOperand(1, IIOp0);
355
356 // Create the new top level add instruction...
357 return BinaryOperator::create(Instruction::Add, Op0, Op1);
358 }
359
360 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
361 //
362 if (Op1I->getOpcode() == Instruction::And &&
363 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
364 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
365
366 Instruction *NewNot = BinaryOperator::createNot(OtherOp, "B.not", &I);
367 return BinaryOperator::create(Instruction::And, Op0, NewNot);
368 }
Chris Lattner57c8d992003-02-18 19:57:07 +0000369
370 // X - X*C --> X * (1-C)
371 if (dyn_castFoldableMul(Op1I) == Op0) {
Chris Lattner34428442003-05-27 16:40:51 +0000372 Constant *CP1 =
373 ConstantExpr::get(Instruction::Sub,
374 ConstantInt::get(I.getType(), 1),
375 cast<Constant>(cast<Instruction>(Op1)->getOperand(1)));
Chris Lattner57c8d992003-02-18 19:57:07 +0000376 assert(CP1 && "Couldn't constant fold 1-C?");
377 return BinaryOperator::create(Instruction::Mul, Op0, CP1);
378 }
Chris Lattnerad3c4952002-05-09 01:29:19 +0000379 }
Chris Lattner3082c5a2003-02-18 19:28:33 +0000380
Chris Lattner57c8d992003-02-18 19:57:07 +0000381 // X*C - X --> X * (C-1)
382 if (dyn_castFoldableMul(Op0) == Op1) {
Chris Lattner34428442003-05-27 16:40:51 +0000383 Constant *CP1 =
384 ConstantExpr::get(Instruction::Sub,
385 cast<Constant>(cast<Instruction>(Op0)->getOperand(1)),
386 ConstantInt::get(I.getType(), 1));
Chris Lattner57c8d992003-02-18 19:57:07 +0000387 assert(CP1 && "Couldn't constant fold C - 1?");
388 return BinaryOperator::create(Instruction::Mul, Op1, CP1);
389 }
390
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000391 return 0;
Chris Lattner260ab202002-04-18 17:39:14 +0000392}
393
Chris Lattner113f4f42002-06-25 16:13:24 +0000394Instruction *InstCombiner::visitMul(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000395 bool Changed = SimplifyCommutative(I);
Chris Lattner3082c5a2003-02-18 19:28:33 +0000396 Value *Op0 = I.getOperand(0);
Chris Lattner260ab202002-04-18 17:39:14 +0000397
Chris Lattnere6794492002-08-12 21:17:25 +0000398 // Simplify mul instructions with a constant RHS...
Chris Lattner3082c5a2003-02-18 19:28:33 +0000399 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
400 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnerede3fe02003-08-13 04:18:28 +0000401
402 // ((X << C1)*C2) == (X * (C2 << C1))
403 if (ShiftInst *SI = dyn_cast<ShiftInst>(Op0))
404 if (SI->getOpcode() == Instruction::Shl)
405 if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
406 return BinaryOperator::create(Instruction::Mul, SI->getOperand(0),
407 *CI << *ShOp);
408
Chris Lattner3082c5a2003-02-18 19:28:33 +0000409 const Type *Ty = CI->getType();
Chris Lattner6077c312003-07-23 15:22:26 +0000410 int64_t Val = (int64_t)cast<ConstantInt>(CI)->getRawValue();
Chris Lattner3082c5a2003-02-18 19:28:33 +0000411 switch (Val) {
Chris Lattner35236d82003-06-25 17:09:20 +0000412 case -1: // X * -1 -> -X
413 return BinaryOperator::createNeg(Op0, I.getName());
Chris Lattner3082c5a2003-02-18 19:28:33 +0000414 case 0:
415 return ReplaceInstUsesWith(I, Op1); // Eliminate 'mul double %X, 0'
416 case 1:
417 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul int %X, 1'
Chris Lattner3082c5a2003-02-18 19:28:33 +0000418 }
Chris Lattner31ba1292002-04-29 22:24:47 +0000419
Chris Lattner3082c5a2003-02-18 19:28:33 +0000420 if (uint64_t C = Log2(Val)) // Replace X*(2^C) with X << C
421 return new ShiftInst(Instruction::Shl, Op0,
422 ConstantUInt::get(Type::UByteTy, C));
423 } else {
424 ConstantFP *Op1F = cast<ConstantFP>(Op1);
425 if (Op1F->isNullValue())
426 return ReplaceInstUsesWith(I, Op1);
Chris Lattner31ba1292002-04-29 22:24:47 +0000427
Chris Lattner3082c5a2003-02-18 19:28:33 +0000428 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
429 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
430 if (Op1F->getValue() == 1.0)
431 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0'
432 }
Chris Lattner260ab202002-04-18 17:39:14 +0000433 }
434
Chris Lattner934a64cf2003-03-10 23:23:04 +0000435 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
436 if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
437 return BinaryOperator::create(Instruction::Mul, Op0v, Op1v);
438
Chris Lattner113f4f42002-06-25 16:13:24 +0000439 return Changed ? &I : 0;
Chris Lattner260ab202002-04-18 17:39:14 +0000440}
441
Chris Lattner113f4f42002-06-25 16:13:24 +0000442Instruction *InstCombiner::visitDiv(BinaryOperator &I) {
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000443 // div X, 1 == X
Chris Lattner3082c5a2003-02-18 19:28:33 +0000444 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I.getOperand(1))) {
Chris Lattnere6794492002-08-12 21:17:25 +0000445 if (RHS->equalsInt(1))
446 return ReplaceInstUsesWith(I, I.getOperand(0));
Chris Lattner3082c5a2003-02-18 19:28:33 +0000447
448 // Check to see if this is an unsigned division with an exact power of 2,
449 // if so, convert to a right shift.
450 if (ConstantUInt *C = dyn_cast<ConstantUInt>(RHS))
451 if (uint64_t Val = C->getValue()) // Don't break X / 0
452 if (uint64_t C = Log2(Val))
453 return new ShiftInst(Instruction::Shr, I.getOperand(0),
454 ConstantUInt::get(Type::UByteTy, C));
455 }
456
457 // 0 / X == 0, we don't need to preserve faults!
458 if (ConstantInt *LHS = dyn_cast<ConstantInt>(I.getOperand(0)))
459 if (LHS->equalsInt(0))
460 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
461
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000462 return 0;
463}
464
465
Chris Lattner113f4f42002-06-25 16:13:24 +0000466Instruction *InstCombiner::visitRem(BinaryOperator &I) {
Chris Lattner3082c5a2003-02-18 19:28:33 +0000467 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I.getOperand(1))) {
468 if (RHS->equalsInt(1)) // X % 1 == 0
469 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
470
471 // Check to see if this is an unsigned remainder with an exact power of 2,
472 // if so, convert to a bitwise and.
473 if (ConstantUInt *C = dyn_cast<ConstantUInt>(RHS))
474 if (uint64_t Val = C->getValue()) // Don't break X % 0 (divide by zero)
475 if (Log2(Val))
476 return BinaryOperator::create(Instruction::And, I.getOperand(0),
477 ConstantUInt::get(I.getType(), Val-1));
478 }
479
480 // 0 % X == 0, we don't need to preserve faults!
481 if (ConstantInt *LHS = dyn_cast<ConstantInt>(I.getOperand(0)))
482 if (LHS->equalsInt(0))
Chris Lattnere6794492002-08-12 21:17:25 +0000483 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
484
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000485 return 0;
486}
487
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000488// isMaxValueMinusOne - return true if this is Max-1
Chris Lattnere6794492002-08-12 21:17:25 +0000489static bool isMaxValueMinusOne(const ConstantInt *C) {
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000490 if (const ConstantUInt *CU = dyn_cast<ConstantUInt>(C)) {
491 // Calculate -1 casted to the right type...
492 unsigned TypeBits = C->getType()->getPrimitiveSize()*8;
493 uint64_t Val = ~0ULL; // All ones
494 Val >>= 64-TypeBits; // Shift out unwanted 1 bits...
495 return CU->getValue() == Val-1;
496 }
497
498 const ConstantSInt *CS = cast<ConstantSInt>(C);
499
500 // Calculate 0111111111..11111
501 unsigned TypeBits = C->getType()->getPrimitiveSize()*8;
502 int64_t Val = INT64_MAX; // All ones
503 Val >>= 64-TypeBits; // Shift out unwanted 1 bits...
504 return CS->getValue() == Val-1;
505}
506
507// isMinValuePlusOne - return true if this is Min+1
Chris Lattnere6794492002-08-12 21:17:25 +0000508static bool isMinValuePlusOne(const ConstantInt *C) {
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000509 if (const ConstantUInt *CU = dyn_cast<ConstantUInt>(C))
510 return CU->getValue() == 1;
511
512 const ConstantSInt *CS = cast<ConstantSInt>(C);
513
514 // Calculate 1111111111000000000000
515 unsigned TypeBits = C->getType()->getPrimitiveSize()*8;
516 int64_t Val = -1; // All ones
517 Val <<= TypeBits-1; // Shift over to the right spot
518 return CS->getValue() == Val+1;
519}
520
521
Chris Lattner113f4f42002-06-25 16:13:24 +0000522Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000523 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +0000524 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000525
526 // and X, X = X and X, 0 == 0
Chris Lattnere6794492002-08-12 21:17:25 +0000527 if (Op0 == Op1 || Op1 == Constant::getNullValue(I.getType()))
528 return ReplaceInstUsesWith(I, Op1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000529
530 // and X, -1 == X
Chris Lattner49b47ae2003-07-23 17:57:01 +0000531 if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
Chris Lattnere6794492002-08-12 21:17:25 +0000532 if (RHS->isAllOnesValue())
533 return ReplaceInstUsesWith(I, Op0);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000534
Chris Lattner33217db2003-07-23 19:36:21 +0000535 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
536 Value *X = Op0I->getOperand(0);
Chris Lattner16464b32003-07-23 19:25:52 +0000537 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
538 if (Op0I->getOpcode() == Instruction::Xor) {
Chris Lattner33217db2003-07-23 19:36:21 +0000539 if ((*RHS & *Op0CI)->isNullValue()) {
540 // (X ^ C1) & C2 --> (X & C2) iff (C1&C2) == 0
541 return BinaryOperator::create(Instruction::And, X, RHS);
542 } else if (isOnlyUse(Op0)) {
Chris Lattner16464b32003-07-23 19:25:52 +0000543 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
544 std::string Op0Name = Op0I->getName(); Op0I->setName("");
545 Instruction *And = BinaryOperator::create(Instruction::And,
Chris Lattner33217db2003-07-23 19:36:21 +0000546 X, RHS, Op0Name);
Chris Lattner16464b32003-07-23 19:25:52 +0000547 InsertNewInstBefore(And, I);
548 return BinaryOperator::create(Instruction::Xor, And, *RHS & *Op0CI);
549 }
550 } else if (Op0I->getOpcode() == Instruction::Or) {
551 // (X | C1) & C2 --> X & C2 iff C1 & C1 == 0
552 if ((*RHS & *Op0CI)->isNullValue())
Chris Lattner33217db2003-07-23 19:36:21 +0000553 return BinaryOperator::create(Instruction::And, X, RHS);
Chris Lattner16464b32003-07-23 19:25:52 +0000554
555 Constant *Together = *RHS & *Op0CI;
556 if (Together == RHS) // (X | C) & C --> C
557 return ReplaceInstUsesWith(I, RHS);
558
559 if (isOnlyUse(Op0)) {
560 if (Together != Op0CI) {
561 // (X | C1) & C2 --> (X | (C1&C2)) & C2
562 std::string Op0Name = Op0I->getName(); Op0I->setName("");
Chris Lattner33217db2003-07-23 19:36:21 +0000563 Instruction *Or = BinaryOperator::create(Instruction::Or, X,
564 Together, Op0Name);
Chris Lattner16464b32003-07-23 19:25:52 +0000565 InsertNewInstBefore(Or, I);
566 return BinaryOperator::create(Instruction::And, Or, RHS);
567 }
568 }
Chris Lattner49b47ae2003-07-23 17:57:01 +0000569 }
Chris Lattner33217db2003-07-23 19:36:21 +0000570 }
Chris Lattner49b47ae2003-07-23 17:57:01 +0000571 }
572
Chris Lattnerbb74e222003-03-10 23:06:50 +0000573 Value *Op0NotVal = dyn_castNotVal(Op0);
574 Value *Op1NotVal = dyn_castNotVal(Op1);
Chris Lattner3082c5a2003-02-18 19:28:33 +0000575
576 // (~A & ~B) == (~(A | B)) - Demorgan's Law
Chris Lattnerbb74e222003-03-10 23:06:50 +0000577 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Chris Lattner3082c5a2003-02-18 19:28:33 +0000578 Instruction *Or = BinaryOperator::create(Instruction::Or, Op0NotVal,
Chris Lattner49b47ae2003-07-23 17:57:01 +0000579 Op1NotVal,I.getName()+".demorgan");
580 InsertNewInstBefore(Or, I);
Chris Lattner3082c5a2003-02-18 19:28:33 +0000581 return BinaryOperator::createNot(Or);
582 }
583
584 if (Op0NotVal == Op1 || Op1NotVal == Op0) // A & ~A == ~A & A == 0
585 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner65217ff2002-08-23 18:32:43 +0000586
Chris Lattner113f4f42002-06-25 16:13:24 +0000587 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000588}
589
590
591
Chris Lattner113f4f42002-06-25 16:13:24 +0000592Instruction *InstCombiner::visitOr(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000593 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +0000594 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000595
596 // or X, X = X or X, 0 == X
Chris Lattnere6794492002-08-12 21:17:25 +0000597 if (Op0 == Op1 || Op1 == Constant::getNullValue(I.getType()))
598 return ReplaceInstUsesWith(I, Op0);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000599
600 // or X, -1 == -1
Chris Lattner8f0d1562003-07-23 18:29:44 +0000601 if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
Chris Lattnere6794492002-08-12 21:17:25 +0000602 if (RHS->isAllOnesValue())
603 return ReplaceInstUsesWith(I, Op1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000604
Chris Lattner8f0d1562003-07-23 18:29:44 +0000605 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
606 // (X & C1) | C2 --> (X | C2) & (C1|C2)
607 if (Op0I->getOpcode() == Instruction::And && isOnlyUse(Op0))
608 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
609 std::string Op0Name = Op0I->getName(); Op0I->setName("");
610 Instruction *Or = BinaryOperator::create(Instruction::Or,
611 Op0I->getOperand(0), RHS,
612 Op0Name);
613 InsertNewInstBefore(Or, I);
614 return BinaryOperator::create(Instruction::And, Or, *RHS | *Op0CI);
615 }
616
617 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
618 if (Op0I->getOpcode() == Instruction::Xor && isOnlyUse(Op0))
619 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
620 std::string Op0Name = Op0I->getName(); Op0I->setName("");
621 Instruction *Or = BinaryOperator::create(Instruction::Or,
622 Op0I->getOperand(0), RHS,
623 Op0Name);
624 InsertNewInstBefore(Or, I);
625 return BinaryOperator::create(Instruction::Xor, Or, *Op0CI & *~*RHS);
626 }
627 }
628 }
629
Chris Lattner812aab72003-08-12 19:11:07 +0000630 // (A & C1)|(A & C2) == A & (C1|C2)
Chris Lattner01d56392003-08-12 19:17:27 +0000631 if (Instruction *LHS = dyn_cast<BinaryOperator>(Op0))
632 if (Instruction *RHS = dyn_cast<BinaryOperator>(Op1))
633 if (LHS->getOperand(0) == RHS->getOperand(0))
634 if (Constant *C0 = dyn_castMaskingAnd(LHS))
635 if (Constant *C1 = dyn_castMaskingAnd(RHS))
636 return BinaryOperator::create(Instruction::And, LHS->getOperand(0),
Chris Lattner812aab72003-08-12 19:11:07 +0000637 *C0 | *C1);
638
Chris Lattner3e327a42003-03-10 23:13:59 +0000639 Value *Op0NotVal = dyn_castNotVal(Op0);
640 Value *Op1NotVal = dyn_castNotVal(Op1);
Chris Lattner3082c5a2003-02-18 19:28:33 +0000641
Chris Lattner3e327a42003-03-10 23:13:59 +0000642 if (Op1 == Op0NotVal) // ~A | A == -1
643 return ReplaceInstUsesWith(I,
644 ConstantIntegral::getAllOnesValue(I.getType()));
645
646 if (Op0 == Op1NotVal) // A | ~A == -1
647 return ReplaceInstUsesWith(I,
648 ConstantIntegral::getAllOnesValue(I.getType()));
649
650 // (~A | ~B) == (~(A & B)) - Demorgan's Law
651 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
652 Instruction *And = BinaryOperator::create(Instruction::And, Op0NotVal,
653 Op1NotVal,I.getName()+".demorgan",
654 &I);
655 WorkList.push_back(And);
656 return BinaryOperator::createNot(And);
657 }
Chris Lattner3082c5a2003-02-18 19:28:33 +0000658
Chris Lattner113f4f42002-06-25 16:13:24 +0000659 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000660}
661
662
663
Chris Lattner113f4f42002-06-25 16:13:24 +0000664Instruction *InstCombiner::visitXor(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000665 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +0000666 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000667
668 // xor X, X = 0
Chris Lattnere6794492002-08-12 21:17:25 +0000669 if (Op0 == Op1)
670 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000671
Chris Lattner97638592003-07-23 21:37:07 +0000672 if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000673 // xor X, 0 == X
Chris Lattner97638592003-07-23 21:37:07 +0000674 if (RHS->isNullValue())
Chris Lattnere6794492002-08-12 21:17:25 +0000675 return ReplaceInstUsesWith(I, Op0);
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000676
Chris Lattner97638592003-07-23 21:37:07 +0000677 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Chris Lattnerb8d6e402002-08-20 18:24:26 +0000678 // xor (setcc A, B), true = not (setcc A, B) = setncc A, B
Chris Lattner97638592003-07-23 21:37:07 +0000679 if (SetCondInst *SCI = dyn_cast<SetCondInst>(Op0I))
680 if (RHS == ConstantBool::True && SCI->use_size() == 1)
Chris Lattnerb8d6e402002-08-20 18:24:26 +0000681 return new SetCondInst(SCI->getInverseCondition(),
682 SCI->getOperand(0), SCI->getOperand(1));
Chris Lattner97638592003-07-23 21:37:07 +0000683
684 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
685 if (Op0I->getOpcode() == Instruction::And) {
686 // (X & C1) ^ C2 --> (X & C1) | C2 iff (C1&C2) == 0
687 if ((*RHS & *Op0CI)->isNullValue())
688 return BinaryOperator::create(Instruction::Or, Op0, RHS);
689 } else if (Op0I->getOpcode() == Instruction::Or) {
690 // (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
691 if ((*RHS & *Op0CI) == RHS)
692 return BinaryOperator::create(Instruction::And, Op0, ~*RHS);
693 }
Chris Lattnerb8d6e402002-08-20 18:24:26 +0000694 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000695 }
696
Chris Lattnerbb74e222003-03-10 23:06:50 +0000697 if (Value *X = dyn_castNotVal(Op0)) // ~A ^ A == -1
Chris Lattner3082c5a2003-02-18 19:28:33 +0000698 if (X == Op1)
699 return ReplaceInstUsesWith(I,
700 ConstantIntegral::getAllOnesValue(I.getType()));
701
Chris Lattnerbb74e222003-03-10 23:06:50 +0000702 if (Value *X = dyn_castNotVal(Op1)) // A ^ ~A == -1
Chris Lattner3082c5a2003-02-18 19:28:33 +0000703 if (X == Op0)
704 return ReplaceInstUsesWith(I,
705 ConstantIntegral::getAllOnesValue(I.getType()));
706
Chris Lattner1bbb7b62003-03-10 18:24:17 +0000707 if (Instruction *Op1I = dyn_cast<Instruction>(Op1))
708 if (Op1I->getOpcode() == Instruction::Or)
709 if (Op1I->getOperand(0) == Op0) { // B^(B|A) == (A|B)^B
710 cast<BinaryOperator>(Op1I)->swapOperands();
711 I.swapOperands();
712 std::swap(Op0, Op1);
713 } else if (Op1I->getOperand(1) == Op0) { // B^(A|B) == (A|B)^B
714 I.swapOperands();
715 std::swap(Op0, Op1);
716 }
717
718 if (Instruction *Op0I = dyn_cast<Instruction>(Op0))
719 if (Op0I->getOpcode() == Instruction::Or && Op0I->use_size() == 1) {
720 if (Op0I->getOperand(0) == Op1) // (B|A)^B == (A|B)^B
721 cast<BinaryOperator>(Op0I)->swapOperands();
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000722 if (Op0I->getOperand(1) == Op1) { // (A|B)^B == A & ~B
Chris Lattner1bbb7b62003-03-10 18:24:17 +0000723 Value *NotB = BinaryOperator::createNot(Op1, Op1->getName()+".not", &I);
724 WorkList.push_back(cast<Instruction>(NotB));
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000725 return BinaryOperator::create(Instruction::And, Op0I->getOperand(0),
726 NotB);
Chris Lattner1bbb7b62003-03-10 18:24:17 +0000727 }
728 }
729
Chris Lattner7fb29e12003-03-11 00:12:48 +0000730 // (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1^C2 == 0
731 if (Constant *C1 = dyn_castMaskingAnd(Op0))
732 if (Constant *C2 = dyn_castMaskingAnd(Op1))
Chris Lattner34428442003-05-27 16:40:51 +0000733 if (ConstantExpr::get(Instruction::And, C1, C2)->isNullValue())
Chris Lattner7fb29e12003-03-11 00:12:48 +0000734 return BinaryOperator::create(Instruction::Or, Op0, Op1);
735
Chris Lattner113f4f42002-06-25 16:13:24 +0000736 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000737}
738
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000739// AddOne, SubOne - Add or subtract a constant one from an integer constant...
740static Constant *AddOne(ConstantInt *C) {
Chris Lattner34428442003-05-27 16:40:51 +0000741 Constant *Result = ConstantExpr::get(Instruction::Add, C,
742 ConstantInt::get(C->getType(), 1));
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000743 assert(Result && "Constant folding integer addition failed!");
744 return Result;
745}
746static Constant *SubOne(ConstantInt *C) {
Chris Lattner34428442003-05-27 16:40:51 +0000747 Constant *Result = ConstantExpr::get(Instruction::Sub, C,
748 ConstantInt::get(C->getType(), 1));
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000749 assert(Result && "Constant folding integer addition failed!");
750 return Result;
751}
752
Chris Lattner1fc23f32002-05-09 20:11:54 +0000753// isTrueWhenEqual - Return true if the specified setcondinst instruction is
754// true when both operands are equal...
755//
Chris Lattner113f4f42002-06-25 16:13:24 +0000756static bool isTrueWhenEqual(Instruction &I) {
757 return I.getOpcode() == Instruction::SetEQ ||
758 I.getOpcode() == Instruction::SetGE ||
759 I.getOpcode() == Instruction::SetLE;
Chris Lattner1fc23f32002-05-09 20:11:54 +0000760}
761
Chris Lattner113f4f42002-06-25 16:13:24 +0000762Instruction *InstCombiner::visitSetCondInst(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000763 bool Changed = SimplifyCommutative(I);
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000764 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
765 const Type *Ty = Op0->getType();
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000766
767 // setcc X, X
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000768 if (Op0 == Op1)
769 return ReplaceInstUsesWith(I, ConstantBool::get(isTrueWhenEqual(I)));
Chris Lattner1fc23f32002-05-09 20:11:54 +0000770
771 // setcc <global*>, 0 - Global value addresses are never null!
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000772 if (isa<GlobalValue>(Op0) && isa<ConstantPointerNull>(Op1))
773 return ReplaceInstUsesWith(I, ConstantBool::get(!isTrueWhenEqual(I)));
774
775 // setcc's with boolean values can always be turned into bitwise operations
776 if (Ty == Type::BoolTy) {
777 // If this is <, >, or !=, we can change this into a simple xor instruction
778 if (!isTrueWhenEqual(I))
779 return BinaryOperator::create(Instruction::Xor, Op0, Op1, I.getName());
780
781 // Otherwise we need to make a temporary intermediate instruction and insert
782 // it into the instruction stream. This is what we are after:
783 //
784 // seteq bool %A, %B -> ~(A^B)
785 // setle bool %A, %B -> ~A | B
786 // setge bool %A, %B -> A | ~B
787 //
788 if (I.getOpcode() == Instruction::SetEQ) { // seteq case
789 Instruction *Xor = BinaryOperator::create(Instruction::Xor, Op0, Op1,
790 I.getName()+"tmp");
791 InsertNewInstBefore(Xor, I);
Chris Lattner31ae8632002-08-14 17:51:49 +0000792 return BinaryOperator::createNot(Xor, I.getName());
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000793 }
794
795 // Handle the setXe cases...
796 assert(I.getOpcode() == Instruction::SetGE ||
797 I.getOpcode() == Instruction::SetLE);
798
799 if (I.getOpcode() == Instruction::SetGE)
800 std::swap(Op0, Op1); // Change setge -> setle
801
802 // Now we just have the SetLE case.
Chris Lattner31ae8632002-08-14 17:51:49 +0000803 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000804 InsertNewInstBefore(Not, I);
805 return BinaryOperator::create(Instruction::Or, Not, Op1, I.getName());
806 }
807
808 // Check to see if we are doing one of many comparisons against constant
809 // integers at the end of their ranges...
810 //
811 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnerd492a0b2003-07-23 17:02:11 +0000812 // Simplify seteq and setne instructions...
813 if (I.getOpcode() == Instruction::SetEQ ||
814 I.getOpcode() == Instruction::SetNE) {
815 bool isSetNE = I.getOpcode() == Instruction::SetNE;
816
Chris Lattnercfbce7c2003-07-23 17:26:36 +0000817 // If the first operand is (and|or|xor) with a constant, and the second
Chris Lattnerd492a0b2003-07-23 17:02:11 +0000818 // operand is a constant, simplify a bit.
Chris Lattnerc992add2003-08-13 05:33:12 +0000819 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0)) {
820 switch (BO->getOpcode()) {
821 case Instruction::Add:
822 if (CI->isNullValue()) {
823 // Replace ((add A, B) != 0) with (A != -B) if A or B is
824 // efficiently invertible, or if the add has just this one use.
825 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
826 if (Value *NegVal = dyn_castNegVal(BOp1))
827 return new SetCondInst(I.getOpcode(), BOp0, NegVal);
828 else if (Value *NegVal = dyn_castNegVal(BOp0))
829 return new SetCondInst(I.getOpcode(), NegVal, BOp1);
830 else if (BO->use_size() == 1) {
831 Instruction *Neg = BinaryOperator::createNeg(BOp1, BO->getName());
832 BO->setName("");
833 InsertNewInstBefore(Neg, I);
834 return new SetCondInst(I.getOpcode(), BOp0, Neg);
835 }
836 }
837 break;
838 case Instruction::Xor:
839 // For the xor case, we can xor two constants together, eliminating
840 // the explicit xor.
841 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
842 return BinaryOperator::create(I.getOpcode(), BO->getOperand(0),
843 *CI ^ *BOC);
844
845 // FALLTHROUGH
846 case Instruction::Sub:
847 // Replace (([sub|xor] A, B) != 0) with (A != B)
848 if (CI->isNullValue())
849 return new SetCondInst(I.getOpcode(), BO->getOperand(0),
850 BO->getOperand(1));
851 break;
852
853 case Instruction::Or:
854 // If bits are being or'd in that are not present in the constant we
855 // are comparing against, then the comparison could never succeed!
856 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
Chris Lattnerd492a0b2003-07-23 17:02:11 +0000857 if (!(*BOC & *~*CI)->isNullValue())
858 return ReplaceInstUsesWith(I, ConstantBool::get(isSetNE));
Chris Lattnerc992add2003-08-13 05:33:12 +0000859 break;
860
861 case Instruction::And:
862 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
Chris Lattnerd492a0b2003-07-23 17:02:11 +0000863 // If bits are being compared against that are and'd out, then the
864 // comparison can never succeed!
865 if (!(*CI & *~*BOC)->isNullValue())
866 return ReplaceInstUsesWith(I, ConstantBool::get(isSetNE));
Chris Lattnerc992add2003-08-13 05:33:12 +0000867
868 // Replace (and X, (1 << size(X)-1) != 0) with x < 0, converting X
869 // to be a signed value as appropriate.
870 if (isSignBit(BOC)) {
871 Value *X = BO->getOperand(0);
872 // If 'X' is not signed, insert a cast now...
873 if (!BOC->getType()->isSigned()) {
874 const Type *DestTy;
875 switch (BOC->getType()->getPrimitiveID()) {
876 case Type::UByteTyID: DestTy = Type::SByteTy; break;
877 case Type::UShortTyID: DestTy = Type::ShortTy; break;
878 case Type::UIntTyID: DestTy = Type::IntTy; break;
879 case Type::ULongTyID: DestTy = Type::LongTy; break;
880 default: assert(0 && "Invalid unsigned integer type!"); abort();
881 }
882 CastInst *NewCI = new CastInst(X,DestTy,X->getName()+".signed");
883 InsertNewInstBefore(NewCI, I);
884 X = NewCI;
885 }
886 return new SetCondInst(isSetNE ? Instruction::SetLT :
887 Instruction::SetGE, X,
888 Constant::getNullValue(X->getType()));
889 }
Chris Lattnerd492a0b2003-07-23 17:02:11 +0000890 }
Chris Lattnerc992add2003-08-13 05:33:12 +0000891 default: break;
892 }
893 }
Chris Lattnere967b342003-06-04 05:10:11 +0000894 }
Chris Lattner791ac1a2003-06-01 03:35:25 +0000895
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000896 // Check to see if we are comparing against the minimum or maximum value...
Chris Lattnere6794492002-08-12 21:17:25 +0000897 if (CI->isMinValue()) {
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000898 if (I.getOpcode() == Instruction::SetLT) // A < MIN -> FALSE
899 return ReplaceInstUsesWith(I, ConstantBool::False);
900 if (I.getOpcode() == Instruction::SetGE) // A >= MIN -> TRUE
901 return ReplaceInstUsesWith(I, ConstantBool::True);
902 if (I.getOpcode() == Instruction::SetLE) // A <= MIN -> A == MIN
903 return BinaryOperator::create(Instruction::SetEQ, Op0,Op1, I.getName());
904 if (I.getOpcode() == Instruction::SetGT) // A > MIN -> A != MIN
905 return BinaryOperator::create(Instruction::SetNE, Op0,Op1, I.getName());
906
Chris Lattnere6794492002-08-12 21:17:25 +0000907 } else if (CI->isMaxValue()) {
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000908 if (I.getOpcode() == Instruction::SetGT) // A > MAX -> FALSE
909 return ReplaceInstUsesWith(I, ConstantBool::False);
910 if (I.getOpcode() == Instruction::SetLE) // A <= MAX -> TRUE
911 return ReplaceInstUsesWith(I, ConstantBool::True);
912 if (I.getOpcode() == Instruction::SetGE) // A >= MAX -> A == MAX
913 return BinaryOperator::create(Instruction::SetEQ, Op0,Op1, I.getName());
914 if (I.getOpcode() == Instruction::SetLT) // A < MAX -> A != MAX
915 return BinaryOperator::create(Instruction::SetNE, Op0,Op1, I.getName());
916
917 // Comparing against a value really close to min or max?
918 } else if (isMinValuePlusOne(CI)) {
919 if (I.getOpcode() == Instruction::SetLT) // A < MIN+1 -> A == MIN
920 return BinaryOperator::create(Instruction::SetEQ, Op0,
921 SubOne(CI), I.getName());
922 if (I.getOpcode() == Instruction::SetGE) // A >= MIN-1 -> A != MIN
923 return BinaryOperator::create(Instruction::SetNE, Op0,
924 SubOne(CI), I.getName());
925
926 } else if (isMaxValueMinusOne(CI)) {
927 if (I.getOpcode() == Instruction::SetGT) // A > MAX-1 -> A == MAX
928 return BinaryOperator::create(Instruction::SetEQ, Op0,
929 AddOne(CI), I.getName());
930 if (I.getOpcode() == Instruction::SetLE) // A <= MAX-1 -> A != MAX
931 return BinaryOperator::create(Instruction::SetNE, Op0,
932 AddOne(CI), I.getName());
933 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000934 }
935
Chris Lattner113f4f42002-06-25 16:13:24 +0000936 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000937}
938
939
940
Chris Lattnere8d6c602003-03-10 19:16:08 +0000941Instruction *InstCombiner::visitShiftInst(ShiftInst &I) {
Chris Lattner113f4f42002-06-25 16:13:24 +0000942 assert(I.getOperand(1)->getType() == Type::UByteTy);
943 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +0000944 bool isLeftShift = I.getOpcode() == Instruction::Shl;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000945
946 // shl X, 0 == X and shr X, 0 == X
947 // shl 0, X == 0 and shr 0, X == 0
948 if (Op1 == Constant::getNullValue(Type::UByteTy) ||
Chris Lattnere6794492002-08-12 21:17:25 +0000949 Op0 == Constant::getNullValue(Op0->getType()))
950 return ReplaceInstUsesWith(I, Op0);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000951
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +0000952 // shr int -1, X = -1 (for any arithmetic shift rights of ~0)
953 if (!isLeftShift)
954 if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(Op0))
955 if (CSI->isAllOnesValue())
956 return ReplaceInstUsesWith(I, CSI);
957
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000958 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(Op1)) {
Chris Lattner3204d4e2003-07-24 17:52:58 +0000959 // shl uint X, 32 = 0 and shr ubyte Y, 9 = 0, ... just don't eliminate shr
960 // of a signed value.
961 //
Chris Lattnere8d6c602003-03-10 19:16:08 +0000962 unsigned TypeBits = Op0->getType()->getPrimitiveSize()*8;
963 if (CUI->getValue() >= TypeBits &&
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +0000964 (!Op0->getType()->isSigned() || isLeftShift))
Chris Lattnere8d6c602003-03-10 19:16:08 +0000965 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
Chris Lattner55f3d942002-09-10 23:04:09 +0000966
Chris Lattnerede3fe02003-08-13 04:18:28 +0000967 // ((X*C1) << C2) == (X * (C1 << C2))
968 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
969 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
970 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
971 return BinaryOperator::create(Instruction::Mul, BO->getOperand(0),
972 *BOOp << *CUI);
973
974
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +0000975 // If the operand is an bitwise operator with a constant RHS, and the
976 // shift is the only use, we can pull it out of the shift.
977 if (Op0->use_size() == 1)
978 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0))
979 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
980 bool isValid = true; // Valid only for And, Or, Xor
981 bool highBitSet = false; // Transform if high bit of constant set?
982
983 switch (Op0BO->getOpcode()) {
984 default: isValid = false; break; // Do not perform transform!
985 case Instruction::Or:
986 case Instruction::Xor:
987 highBitSet = false;
988 break;
989 case Instruction::And:
990 highBitSet = true;
991 break;
992 }
993
994 // If this is a signed shift right, and the high bit is modified
995 // by the logical operation, do not perform the transformation.
996 // The highBitSet boolean indicates the value of the high bit of
997 // the constant which would cause it to be modified for this
998 // operation.
999 //
1000 if (isValid && !isLeftShift && !I.getType()->isUnsigned()) {
1001 uint64_t Val = Op0C->getRawValue();
1002 isValid = ((Val & (1 << (TypeBits-1))) != 0) == highBitSet;
1003 }
1004
1005 if (isValid) {
1006 Constant *NewRHS =
1007 ConstantFoldShiftInstruction(I.getOpcode(), Op0C, CUI);
1008
1009 Instruction *NewShift =
1010 new ShiftInst(I.getOpcode(), Op0BO->getOperand(0), CUI,
1011 Op0BO->getName());
1012 Op0BO->setName("");
1013 InsertNewInstBefore(NewShift, I);
1014
1015 return BinaryOperator::create(Op0BO->getOpcode(), NewShift,
1016 NewRHS);
1017 }
1018 }
1019
Chris Lattner3204d4e2003-07-24 17:52:58 +00001020 // If this is a shift of a shift, see if we can fold the two together...
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00001021 if (ShiftInst *Op0SI = dyn_cast<ShiftInst>(Op0))
Chris Lattnerab780df2003-07-24 18:38:56 +00001022 if (ConstantUInt *ShiftAmt1C =
1023 dyn_cast<ConstantUInt>(Op0SI->getOperand(1))) {
Chris Lattner3204d4e2003-07-24 17:52:58 +00001024 unsigned ShiftAmt1 = ShiftAmt1C->getValue();
1025 unsigned ShiftAmt2 = CUI->getValue();
1026
1027 // Check for (A << c1) << c2 and (A >> c1) >> c2
1028 if (I.getOpcode() == Op0SI->getOpcode()) {
1029 unsigned Amt = ShiftAmt1+ShiftAmt2; // Fold into one big shift...
1030 return new ShiftInst(I.getOpcode(), Op0SI->getOperand(0),
1031 ConstantUInt::get(Type::UByteTy, Amt));
1032 }
1033
Chris Lattnerab780df2003-07-24 18:38:56 +00001034 // Check for (A << c1) >> c2 or visaversa. If we are dealing with
1035 // signed types, we can only support the (A >> c1) << c2 configuration,
1036 // because it can not turn an arbitrary bit of A into a sign bit.
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00001037 if (I.getType()->isUnsigned() || isLeftShift) {
Chris Lattner3204d4e2003-07-24 17:52:58 +00001038 // Calculate bitmask for what gets shifted off the edge...
1039 Constant *C = ConstantIntegral::getAllOnesValue(I.getType());
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00001040 if (isLeftShift)
Chris Lattner3204d4e2003-07-24 17:52:58 +00001041 C = ConstantExpr::getShift(Instruction::Shl, C, ShiftAmt1C);
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00001042 else
1043 C = ConstantExpr::getShift(Instruction::Shr, C, ShiftAmt1C);
Chris Lattner3204d4e2003-07-24 17:52:58 +00001044
1045 Instruction *Mask =
1046 BinaryOperator::create(Instruction::And, Op0SI->getOperand(0),
1047 C, Op0SI->getOperand(0)->getName()+".mask");
1048 InsertNewInstBefore(Mask, I);
1049
1050 // Figure out what flavor of shift we should use...
1051 if (ShiftAmt1 == ShiftAmt2)
1052 return ReplaceInstUsesWith(I, Mask); // (A << c) >> c === A & c2
1053 else if (ShiftAmt1 < ShiftAmt2) {
1054 return new ShiftInst(I.getOpcode(), Mask,
1055 ConstantUInt::get(Type::UByteTy, ShiftAmt2-ShiftAmt1));
1056 } else {
1057 return new ShiftInst(Op0SI->getOpcode(), Mask,
1058 ConstantUInt::get(Type::UByteTy, ShiftAmt1-ShiftAmt2));
1059 }
1060 }
1061 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001062 }
Chris Lattner2e0fb392002-10-08 16:16:40 +00001063
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001064 return 0;
1065}
1066
1067
Chris Lattner48a44f72002-05-02 17:06:02 +00001068// isEliminableCastOfCast - Return true if it is valid to eliminate the CI
1069// instruction.
1070//
Chris Lattnerdfae8be2003-07-24 17:35:25 +00001071static inline bool isEliminableCastOfCast(const Type *SrcTy, const Type *MidTy,
1072 const Type *DstTy) {
Chris Lattner48a44f72002-05-02 17:06:02 +00001073
Chris Lattner650b6da2002-08-02 20:00:25 +00001074 // It is legal to eliminate the instruction if casting A->B->A if the sizes
1075 // are identical and the bits don't get reinterpreted (for example
Chris Lattner0bb75912002-08-14 23:21:10 +00001076 // int->float->int would not be allowed)
Misha Brukmane5838c42003-05-20 18:45:36 +00001077 if (SrcTy == DstTy && SrcTy->isLosslesslyConvertibleTo(MidTy))
Chris Lattner650b6da2002-08-02 20:00:25 +00001078 return true;
Chris Lattner48a44f72002-05-02 17:06:02 +00001079
1080 // Allow free casting and conversion of sizes as long as the sign doesn't
1081 // change...
Chris Lattnerb0b412e2002-09-03 01:08:28 +00001082 if (SrcTy->isIntegral() && MidTy->isIntegral() && DstTy->isIntegral()) {
Chris Lattner650b6da2002-08-02 20:00:25 +00001083 unsigned SrcSize = SrcTy->getPrimitiveSize();
1084 unsigned MidSize = MidTy->getPrimitiveSize();
1085 unsigned DstSize = DstTy->getPrimitiveSize();
Chris Lattner650b6da2002-08-02 20:00:25 +00001086
Chris Lattner3732aca2002-08-15 16:15:25 +00001087 // Cases where we are monotonically decreasing the size of the type are
1088 // always ok, regardless of what sign changes are going on.
1089 //
Chris Lattner0bb75912002-08-14 23:21:10 +00001090 if (SrcSize >= MidSize && MidSize >= DstSize)
Chris Lattner650b6da2002-08-02 20:00:25 +00001091 return true;
Chris Lattner3732aca2002-08-15 16:15:25 +00001092
Chris Lattner555518c2002-09-23 23:39:43 +00001093 // Cases where the source and destination type are the same, but the middle
1094 // type is bigger are noops.
1095 //
1096 if (SrcSize == DstSize && MidSize > SrcSize)
1097 return true;
1098
Chris Lattner3732aca2002-08-15 16:15:25 +00001099 // If we are monotonically growing, things are more complex.
1100 //
1101 if (SrcSize <= MidSize && MidSize <= DstSize) {
1102 // We have eight combinations of signedness to worry about. Here's the
1103 // table:
1104 static const int SignTable[8] = {
1105 // CODE, SrcSigned, MidSigned, DstSigned, Comment
1106 1, // U U U Always ok
1107 1, // U U S Always ok
1108 3, // U S U Ok iff SrcSize != MidSize
1109 3, // U S S Ok iff SrcSize != MidSize
1110 0, // S U U Never ok
1111 2, // S U S Ok iff MidSize == DstSize
1112 1, // S S U Always ok
1113 1, // S S S Always ok
1114 };
1115
1116 // Choose an action based on the current entry of the signtable that this
1117 // cast of cast refers to...
1118 unsigned Row = SrcTy->isSigned()*4+MidTy->isSigned()*2+DstTy->isSigned();
1119 switch (SignTable[Row]) {
1120 case 0: return false; // Never ok
1121 case 1: return true; // Always ok
1122 case 2: return MidSize == DstSize; // Ok iff MidSize == DstSize
1123 case 3: // Ok iff SrcSize != MidSize
1124 return SrcSize != MidSize || SrcTy == Type::BoolTy;
1125 default: assert(0 && "Bad entry in sign table!");
1126 }
Chris Lattner3732aca2002-08-15 16:15:25 +00001127 }
Chris Lattner650b6da2002-08-02 20:00:25 +00001128 }
Chris Lattner48a44f72002-05-02 17:06:02 +00001129
1130 // Otherwise, we cannot succeed. Specifically we do not want to allow things
1131 // like: short -> ushort -> uint, because this can create wrong results if
1132 // the input short is negative!
1133 //
1134 return false;
1135}
1136
Chris Lattnerdfae8be2003-07-24 17:35:25 +00001137static bool ValueRequiresCast(const Value *V, const Type *Ty) {
1138 if (V->getType() == Ty || isa<Constant>(V)) return false;
1139 if (const CastInst *CI = dyn_cast<CastInst>(V))
1140 if (isEliminableCastOfCast(CI->getOperand(0)->getType(), CI->getType(), Ty))
1141 return false;
1142 return true;
1143}
1144
1145/// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
1146/// InsertBefore instruction. This is specialized a bit to avoid inserting
1147/// casts that are known to not do anything...
1148///
1149Value *InstCombiner::InsertOperandCastBefore(Value *V, const Type *DestTy,
1150 Instruction *InsertBefore) {
1151 if (V->getType() == DestTy) return V;
1152 if (Constant *C = dyn_cast<Constant>(V))
1153 return ConstantExpr::getCast(C, DestTy);
1154
1155 CastInst *CI = new CastInst(V, DestTy, V->getName());
1156 InsertNewInstBefore(CI, *InsertBefore);
1157 return CI;
1158}
Chris Lattner48a44f72002-05-02 17:06:02 +00001159
1160// CastInst simplification
Chris Lattner260ab202002-04-18 17:39:14 +00001161//
Chris Lattner113f4f42002-06-25 16:13:24 +00001162Instruction *InstCombiner::visitCastInst(CastInst &CI) {
Chris Lattner55d4bda2003-06-23 21:59:52 +00001163 Value *Src = CI.getOperand(0);
1164
Chris Lattner48a44f72002-05-02 17:06:02 +00001165 // If the user is casting a value to the same type, eliminate this cast
1166 // instruction...
Chris Lattner55d4bda2003-06-23 21:59:52 +00001167 if (CI.getType() == Src->getType())
1168 return ReplaceInstUsesWith(CI, Src);
Chris Lattner48a44f72002-05-02 17:06:02 +00001169
Chris Lattner48a44f72002-05-02 17:06:02 +00001170 // If casting the result of another cast instruction, try to eliminate this
1171 // one!
1172 //
Chris Lattner55d4bda2003-06-23 21:59:52 +00001173 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) {
Chris Lattnerdfae8be2003-07-24 17:35:25 +00001174 if (isEliminableCastOfCast(CSrc->getOperand(0)->getType(),
1175 CSrc->getType(), CI.getType())) {
Chris Lattner48a44f72002-05-02 17:06:02 +00001176 // This instruction now refers directly to the cast's src operand. This
1177 // has a good chance of making CSrc dead.
Chris Lattner113f4f42002-06-25 16:13:24 +00001178 CI.setOperand(0, CSrc->getOperand(0));
1179 return &CI;
Chris Lattner48a44f72002-05-02 17:06:02 +00001180 }
1181
Chris Lattner650b6da2002-08-02 20:00:25 +00001182 // If this is an A->B->A cast, and we are dealing with integral types, try
1183 // to convert this into a logical 'and' instruction.
1184 //
1185 if (CSrc->getOperand(0)->getType() == CI.getType() &&
Chris Lattnerb0b412e2002-09-03 01:08:28 +00001186 CI.getType()->isInteger() && CSrc->getType()->isInteger() &&
Chris Lattner650b6da2002-08-02 20:00:25 +00001187 CI.getType()->isUnsigned() && CSrc->getType()->isUnsigned() &&
1188 CSrc->getType()->getPrimitiveSize() < CI.getType()->getPrimitiveSize()){
1189 assert(CSrc->getType() != Type::ULongTy &&
1190 "Cannot have type bigger than ulong!");
Chris Lattner196897c2003-05-26 23:41:32 +00001191 uint64_t AndValue = (1ULL << CSrc->getType()->getPrimitiveSize()*8)-1;
Chris Lattner650b6da2002-08-02 20:00:25 +00001192 Constant *AndOp = ConstantUInt::get(CI.getType(), AndValue);
1193 return BinaryOperator::create(Instruction::And, CSrc->getOperand(0),
1194 AndOp);
1195 }
1196 }
1197
Chris Lattnerd0d51602003-06-21 23:12:02 +00001198 // If casting the result of a getelementptr instruction with no offset, turn
1199 // this into a cast of the original pointer!
1200 //
Chris Lattner55d4bda2003-06-23 21:59:52 +00001201 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
Chris Lattnerd0d51602003-06-21 23:12:02 +00001202 bool AllZeroOperands = true;
1203 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i)
1204 if (!isa<Constant>(GEP->getOperand(i)) ||
1205 !cast<Constant>(GEP->getOperand(i))->isNullValue()) {
1206 AllZeroOperands = false;
1207 break;
1208 }
1209 if (AllZeroOperands) {
1210 CI.setOperand(0, GEP->getOperand(0));
1211 return &CI;
1212 }
1213 }
1214
Chris Lattnerdfae8be2003-07-24 17:35:25 +00001215 // If the source value is an instruction with only this use, we can attempt to
1216 // propagate the cast into the instruction. Also, only handle integral types
1217 // for now.
1218 if (Instruction *SrcI = dyn_cast<Instruction>(Src))
1219 if (SrcI->use_size() == 1 && Src->getType()->isIntegral() &&
1220 CI.getType()->isInteger()) { // Don't mess with casts to bool here
1221 const Type *DestTy = CI.getType();
1222 unsigned SrcBitSize = getTypeSizeInBits(Src->getType());
1223 unsigned DestBitSize = getTypeSizeInBits(DestTy);
1224
1225 Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
1226 Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
1227
1228 switch (SrcI->getOpcode()) {
1229 case Instruction::Add:
1230 case Instruction::Mul:
1231 case Instruction::And:
1232 case Instruction::Or:
1233 case Instruction::Xor:
1234 // If we are discarding information, or just changing the sign, rewrite.
1235 if (DestBitSize <= SrcBitSize && DestBitSize != 1) {
1236 // Don't insert two casts if they cannot be eliminated. We allow two
1237 // casts to be inserted if the sizes are the same. This could only be
1238 // converting signedness, which is a noop.
1239 if (DestBitSize == SrcBitSize || !ValueRequiresCast(Op1, DestTy) ||
1240 !ValueRequiresCast(Op0, DestTy)) {
1241 Value *Op0c = InsertOperandCastBefore(Op0, DestTy, SrcI);
1242 Value *Op1c = InsertOperandCastBefore(Op1, DestTy, SrcI);
1243 return BinaryOperator::create(cast<BinaryOperator>(SrcI)
1244 ->getOpcode(), Op0c, Op1c);
1245 }
1246 }
1247 break;
1248 case Instruction::Shl:
1249 // Allow changing the sign of the source operand. Do not allow changing
1250 // the size of the shift, UNLESS the shift amount is a constant. We
1251 // mush not change variable sized shifts to a smaller size, because it
1252 // is undefined to shift more bits out than exist in the value.
1253 if (DestBitSize == SrcBitSize ||
1254 (DestBitSize < SrcBitSize && isa<Constant>(Op1))) {
1255 Value *Op0c = InsertOperandCastBefore(Op0, DestTy, SrcI);
1256 return new ShiftInst(Instruction::Shl, Op0c, Op1);
1257 }
1258 break;
1259 }
1260 }
1261
Chris Lattner260ab202002-04-18 17:39:14 +00001262 return 0;
Chris Lattnerca081252001-12-14 16:52:21 +00001263}
1264
Chris Lattner970c33a2003-06-19 17:00:31 +00001265// CallInst simplification
1266//
1267Instruction *InstCombiner::visitCallInst(CallInst &CI) {
1268 if (transformConstExprCastCall(&CI)) return 0;
1269 return 0;
1270}
1271
1272// InvokeInst simplification
1273//
1274Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
1275 if (transformConstExprCastCall(&II)) return 0;
1276 return 0;
1277}
1278
1279// getPromotedType - Return the specified type promoted as it would be to pass
1280// though a va_arg area...
1281static const Type *getPromotedType(const Type *Ty) {
1282 switch (Ty->getPrimitiveID()) {
1283 case Type::SByteTyID:
1284 case Type::ShortTyID: return Type::IntTy;
1285 case Type::UByteTyID:
1286 case Type::UShortTyID: return Type::UIntTy;
1287 case Type::FloatTyID: return Type::DoubleTy;
1288 default: return Ty;
1289 }
1290}
1291
1292// transformConstExprCastCall - If the callee is a constexpr cast of a function,
1293// attempt to move the cast to the arguments of the call/invoke.
1294//
1295bool InstCombiner::transformConstExprCastCall(CallSite CS) {
1296 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
1297 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
1298 if (CE->getOpcode() != Instruction::Cast ||
1299 !isa<ConstantPointerRef>(CE->getOperand(0)))
1300 return false;
1301 ConstantPointerRef *CPR = cast<ConstantPointerRef>(CE->getOperand(0));
1302 if (!isa<Function>(CPR->getValue())) return false;
1303 Function *Callee = cast<Function>(CPR->getValue());
1304 Instruction *Caller = CS.getInstruction();
1305
1306 // Okay, this is a cast from a function to a different type. Unless doing so
1307 // would cause a type conversion of one of our arguments, change this call to
1308 // be a direct call with arguments casted to the appropriate types.
1309 //
1310 const FunctionType *FT = Callee->getFunctionType();
1311 const Type *OldRetTy = Caller->getType();
1312
1313 if (Callee->isExternal() &&
1314 !OldRetTy->isLosslesslyConvertibleTo(FT->getReturnType()))
1315 return false; // Cannot transform this return value...
1316
1317 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
1318 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
1319
1320 CallSite::arg_iterator AI = CS.arg_begin();
1321 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
1322 const Type *ParamTy = FT->getParamType(i);
1323 bool isConvertible = (*AI)->getType()->isLosslesslyConvertibleTo(ParamTy);
1324 if (Callee->isExternal() && !isConvertible) return false;
1325 }
1326
1327 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
1328 Callee->isExternal())
1329 return false; // Do not delete arguments unless we have a function body...
1330
1331 // Okay, we decided that this is a safe thing to do: go ahead and start
1332 // inserting cast instructions as necessary...
1333 std::vector<Value*> Args;
1334 Args.reserve(NumActualArgs);
1335
1336 AI = CS.arg_begin();
1337 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
1338 const Type *ParamTy = FT->getParamType(i);
1339 if ((*AI)->getType() == ParamTy) {
1340 Args.push_back(*AI);
1341 } else {
1342 Instruction *Cast = new CastInst(*AI, ParamTy, "tmp");
1343 InsertNewInstBefore(Cast, *Caller);
1344 Args.push_back(Cast);
1345 }
1346 }
1347
1348 // If the function takes more arguments than the call was taking, add them
1349 // now...
1350 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
1351 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
1352
1353 // If we are removing arguments to the function, emit an obnoxious warning...
1354 if (FT->getNumParams() < NumActualArgs)
1355 if (!FT->isVarArg()) {
1356 std::cerr << "WARNING: While resolving call to function '"
1357 << Callee->getName() << "' arguments were dropped!\n";
1358 } else {
1359 // Add all of the arguments in their promoted form to the arg list...
1360 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
1361 const Type *PTy = getPromotedType((*AI)->getType());
1362 if (PTy != (*AI)->getType()) {
1363 // Must promote to pass through va_arg area!
1364 Instruction *Cast = new CastInst(*AI, PTy, "tmp");
1365 InsertNewInstBefore(Cast, *Caller);
1366 Args.push_back(Cast);
1367 } else {
1368 Args.push_back(*AI);
1369 }
1370 }
1371 }
1372
1373 if (FT->getReturnType() == Type::VoidTy)
1374 Caller->setName(""); // Void type should not have a name...
1375
1376 Instruction *NC;
1377 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
1378 NC = new InvokeInst(Callee, II->getNormalDest(), II->getExceptionalDest(),
1379 Args, Caller->getName(), Caller);
1380 } else {
1381 NC = new CallInst(Callee, Args, Caller->getName(), Caller);
1382 }
1383
1384 // Insert a cast of the return type as necessary...
1385 Value *NV = NC;
1386 if (Caller->getType() != NV->getType() && !Caller->use_empty()) {
1387 if (NV->getType() != Type::VoidTy) {
1388 NV = NC = new CastInst(NC, Caller->getType(), "tmp");
1389 InsertNewInstBefore(NC, *Caller);
1390 AddUsesToWorkList(*Caller);
1391 } else {
1392 NV = Constant::getNullValue(Caller->getType());
1393 }
1394 }
1395
1396 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
1397 Caller->replaceAllUsesWith(NV);
1398 Caller->getParent()->getInstList().erase(Caller);
1399 removeFromWorkList(Caller);
1400 return true;
1401}
1402
1403
Chris Lattner48a44f72002-05-02 17:06:02 +00001404
Chris Lattnerbbbdd852002-05-06 18:06:38 +00001405// PHINode simplification
1406//
Chris Lattner113f4f42002-06-25 16:13:24 +00001407Instruction *InstCombiner::visitPHINode(PHINode &PN) {
Chris Lattnerbbbdd852002-05-06 18:06:38 +00001408 // If the PHI node only has one incoming value, eliminate the PHI node...
Chris Lattnere6794492002-08-12 21:17:25 +00001409 if (PN.getNumIncomingValues() == 1)
1410 return ReplaceInstUsesWith(PN, PN.getIncomingValue(0));
Chris Lattner9cd1e662002-08-20 15:35:35 +00001411
1412 // Otherwise if all of the incoming values are the same for the PHI, replace
1413 // the PHI node with the incoming value.
1414 //
Chris Lattnerf6c0efa2002-08-22 20:22:01 +00001415 Value *InVal = 0;
1416 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
1417 if (PN.getIncomingValue(i) != &PN) // Not the PHI node itself...
1418 if (InVal && PN.getIncomingValue(i) != InVal)
1419 return 0; // Not the same, bail out.
1420 else
1421 InVal = PN.getIncomingValue(i);
1422
1423 // The only case that could cause InVal to be null is if we have a PHI node
1424 // that only has entries for itself. In this case, there is no entry into the
1425 // loop, so kill the PHI.
1426 //
1427 if (InVal == 0) InVal = Constant::getNullValue(PN.getType());
Chris Lattnerbbbdd852002-05-06 18:06:38 +00001428
Chris Lattner9cd1e662002-08-20 15:35:35 +00001429 // All of the incoming values are the same, replace the PHI node now.
1430 return ReplaceInstUsesWith(PN, InVal);
Chris Lattnerbbbdd852002-05-06 18:06:38 +00001431}
1432
Chris Lattner48a44f72002-05-02 17:06:02 +00001433
Chris Lattner113f4f42002-06-25 16:13:24 +00001434Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
Chris Lattner471bd762003-05-22 19:07:21 +00001435 // Is it 'getelementptr %P, long 0' or 'getelementptr %P'
Chris Lattner113f4f42002-06-25 16:13:24 +00001436 // If so, eliminate the noop.
Chris Lattnerae7a0d32002-08-02 19:29:35 +00001437 if ((GEP.getNumOperands() == 2 &&
Chris Lattner136dab72002-09-11 01:21:33 +00001438 GEP.getOperand(1) == Constant::getNullValue(Type::LongTy)) ||
Chris Lattnere6794492002-08-12 21:17:25 +00001439 GEP.getNumOperands() == 1)
1440 return ReplaceInstUsesWith(GEP, GEP.getOperand(0));
Chris Lattner48a44f72002-05-02 17:06:02 +00001441
Chris Lattnerae7a0d32002-08-02 19:29:35 +00001442 // Combine Indices - If the source pointer to this getelementptr instruction
1443 // is a getelementptr instruction, combine the indices of the two
1444 // getelementptr instructions into a single instruction.
1445 //
Chris Lattnerc59af1d2002-08-17 22:21:59 +00001446 if (GetElementPtrInst *Src = dyn_cast<GetElementPtrInst>(GEP.getOperand(0))) {
Chris Lattnerae7a0d32002-08-02 19:29:35 +00001447 std::vector<Value *> Indices;
Chris Lattnerca081252001-12-14 16:52:21 +00001448
Chris Lattnerae7a0d32002-08-02 19:29:35 +00001449 // Can we combine the two pointer arithmetics offsets?
Chris Lattner471bd762003-05-22 19:07:21 +00001450 if (Src->getNumOperands() == 2 && isa<Constant>(Src->getOperand(1)) &&
1451 isa<Constant>(GEP.getOperand(1))) {
Chris Lattner235af562003-03-05 22:33:14 +00001452 // Replace: gep (gep %P, long C1), long C2, ...
1453 // With: gep %P, long (C1+C2), ...
Chris Lattner34428442003-05-27 16:40:51 +00001454 Value *Sum = ConstantExpr::get(Instruction::Add,
1455 cast<Constant>(Src->getOperand(1)),
1456 cast<Constant>(GEP.getOperand(1)));
Chris Lattner235af562003-03-05 22:33:14 +00001457 assert(Sum && "Constant folding of longs failed!?");
1458 GEP.setOperand(0, Src->getOperand(0));
1459 GEP.setOperand(1, Sum);
1460 AddUsesToWorkList(*Src); // Reduce use count of Src
1461 return &GEP;
Chris Lattner471bd762003-05-22 19:07:21 +00001462 } else if (Src->getNumOperands() == 2) {
Chris Lattner235af562003-03-05 22:33:14 +00001463 // Replace: gep (gep %P, long B), long A, ...
1464 // With: T = long A+B; gep %P, T, ...
1465 //
1466 Value *Sum = BinaryOperator::create(Instruction::Add, Src->getOperand(1),
1467 GEP.getOperand(1),
1468 Src->getName()+".sum", &GEP);
1469 GEP.setOperand(0, Src->getOperand(0));
1470 GEP.setOperand(1, Sum);
1471 WorkList.push_back(cast<Instruction>(Sum));
1472 return &GEP;
Chris Lattner5d606a02002-11-04 16:43:32 +00001473 } else if (*GEP.idx_begin() == Constant::getNullValue(Type::LongTy) &&
Chris Lattnera8339e32002-09-17 21:05:42 +00001474 Src->getNumOperands() != 1) {
Chris Lattnerae7a0d32002-08-02 19:29:35 +00001475 // Otherwise we can do the fold if the first index of the GEP is a zero
1476 Indices.insert(Indices.end(), Src->idx_begin(), Src->idx_end());
1477 Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
Chris Lattner5d606a02002-11-04 16:43:32 +00001478 } else if (Src->getOperand(Src->getNumOperands()-1) ==
1479 Constant::getNullValue(Type::LongTy)) {
1480 // If the src gep ends with a constant array index, merge this get into
1481 // it, even if we have a non-zero array index.
1482 Indices.insert(Indices.end(), Src->idx_begin(), Src->idx_end()-1);
1483 Indices.insert(Indices.end(), GEP.idx_begin(), GEP.idx_end());
Chris Lattnerae7a0d32002-08-02 19:29:35 +00001484 }
1485
1486 if (!Indices.empty())
1487 return new GetElementPtrInst(Src->getOperand(0), Indices, GEP.getName());
Chris Lattnerc59af1d2002-08-17 22:21:59 +00001488
1489 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(GEP.getOperand(0))) {
1490 // GEP of global variable. If all of the indices for this GEP are
1491 // constants, we can promote this to a constexpr instead of an instruction.
1492
1493 // Scan for nonconstants...
1494 std::vector<Constant*> Indices;
1495 User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
1496 for (; I != E && isa<Constant>(*I); ++I)
1497 Indices.push_back(cast<Constant>(*I));
1498
1499 if (I == E) { // If they are all constants...
Chris Lattner46b3d302003-04-16 22:40:51 +00001500 Constant *CE =
Chris Lattnerc59af1d2002-08-17 22:21:59 +00001501 ConstantExpr::getGetElementPtr(ConstantPointerRef::get(GV), Indices);
1502
1503 // Replace all uses of the GEP with the new constexpr...
1504 return ReplaceInstUsesWith(GEP, CE);
1505 }
Chris Lattnerca081252001-12-14 16:52:21 +00001506 }
1507
Chris Lattnerca081252001-12-14 16:52:21 +00001508 return 0;
1509}
1510
Chris Lattner1085bdf2002-11-04 16:18:53 +00001511Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
1512 // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
1513 if (AI.isArrayAllocation()) // Check C != 1
1514 if (const ConstantUInt *C = dyn_cast<ConstantUInt>(AI.getArraySize())) {
1515 const Type *NewTy = ArrayType::get(AI.getAllocatedType(), C->getValue());
Chris Lattnera2620ac2002-11-09 00:49:43 +00001516 AllocationInst *New = 0;
Chris Lattner1085bdf2002-11-04 16:18:53 +00001517
1518 // Create and insert the replacement instruction...
1519 if (isa<MallocInst>(AI))
1520 New = new MallocInst(NewTy, 0, AI.getName(), &AI);
Chris Lattnera2620ac2002-11-09 00:49:43 +00001521 else {
1522 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
Chris Lattner1085bdf2002-11-04 16:18:53 +00001523 New = new AllocaInst(NewTy, 0, AI.getName(), &AI);
Chris Lattnera2620ac2002-11-09 00:49:43 +00001524 }
Chris Lattner1085bdf2002-11-04 16:18:53 +00001525
1526 // Scan to the end of the allocation instructions, to skip over a block of
1527 // allocas if possible...
1528 //
1529 BasicBlock::iterator It = New;
1530 while (isa<AllocationInst>(*It)) ++It;
1531
1532 // Now that I is pointing to the first non-allocation-inst in the block,
1533 // insert our getelementptr instruction...
1534 //
1535 std::vector<Value*> Idx(2, Constant::getNullValue(Type::LongTy));
1536 Value *V = new GetElementPtrInst(New, Idx, New->getName()+".sub", It);
1537
1538 // Now make everything use the getelementptr instead of the original
1539 // allocation.
1540 ReplaceInstUsesWith(AI, V);
1541 return &AI;
1542 }
1543 return 0;
1544}
1545
Chris Lattner0f1d8a32003-06-26 05:06:25 +00001546/// GetGEPGlobalInitializer - Given a constant, and a getelementptr
1547/// constantexpr, return the constant value being addressed by the constant
1548/// expression, or null if something is funny.
1549///
1550static Constant *GetGEPGlobalInitializer(Constant *C, ConstantExpr *CE) {
1551 if (CE->getOperand(1) != Constant::getNullValue(Type::LongTy))
1552 return 0; // Do not allow stepping over the value!
1553
1554 // Loop over all of the operands, tracking down which value we are
1555 // addressing...
1556 for (unsigned i = 2, e = CE->getNumOperands(); i != e; ++i)
1557 if (ConstantUInt *CU = dyn_cast<ConstantUInt>(CE->getOperand(i))) {
1558 ConstantStruct *CS = cast<ConstantStruct>(C);
1559 if (CU->getValue() >= CS->getValues().size()) return 0;
1560 C = cast<Constant>(CS->getValues()[CU->getValue()]);
1561 } else if (ConstantSInt *CS = dyn_cast<ConstantSInt>(CE->getOperand(i))) {
1562 ConstantArray *CA = cast<ConstantArray>(C);
1563 if ((uint64_t)CS->getValue() >= CA->getValues().size()) return 0;
1564 C = cast<Constant>(CA->getValues()[CS->getValue()]);
1565 } else
1566 return 0;
1567 return C;
1568}
1569
1570Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
1571 Value *Op = LI.getOperand(0);
1572 if (ConstantPointerRef *CPR = dyn_cast<ConstantPointerRef>(Op))
1573 Op = CPR->getValue();
1574
1575 // Instcombine load (constant global) into the value loaded...
1576 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
Chris Lattnerbdb0ce02003-07-22 21:46:59 +00001577 if (GV->isConstant() && !GV->isExternal())
Chris Lattner0f1d8a32003-06-26 05:06:25 +00001578 return ReplaceInstUsesWith(LI, GV->getInitializer());
1579
1580 // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded...
1581 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op))
1582 if (CE->getOpcode() == Instruction::GetElementPtr)
1583 if (ConstantPointerRef *G=dyn_cast<ConstantPointerRef>(CE->getOperand(0)))
1584 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(G->getValue()))
Chris Lattnerbdb0ce02003-07-22 21:46:59 +00001585 if (GV->isConstant() && !GV->isExternal())
Chris Lattner0f1d8a32003-06-26 05:06:25 +00001586 if (Constant *V = GetGEPGlobalInitializer(GV->getInitializer(), CE))
1587 return ReplaceInstUsesWith(LI, V);
1588 return 0;
1589}
1590
1591
Chris Lattner9eef8a72003-06-04 04:46:00 +00001592Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
1593 // Change br (not X), label True, label False to: br X, label False, True
Chris Lattner45789ac2003-06-05 20:12:51 +00001594 if (BI.isConditional() && !isa<Constant>(BI.getCondition()))
Chris Lattnere967b342003-06-04 05:10:11 +00001595 if (Value *V = dyn_castNotVal(BI.getCondition())) {
1596 BasicBlock *TrueDest = BI.getSuccessor(0);
1597 BasicBlock *FalseDest = BI.getSuccessor(1);
1598 // Swap Destinations and condition...
1599 BI.setCondition(V);
1600 BI.setSuccessor(0, FalseDest);
1601 BI.setSuccessor(1, TrueDest);
1602 return &BI;
1603 }
Chris Lattner9eef8a72003-06-04 04:46:00 +00001604 return 0;
1605}
Chris Lattner1085bdf2002-11-04 16:18:53 +00001606
Chris Lattnerca081252001-12-14 16:52:21 +00001607
Chris Lattner99f48c62002-09-02 04:59:56 +00001608void InstCombiner::removeFromWorkList(Instruction *I) {
1609 WorkList.erase(std::remove(WorkList.begin(), WorkList.end(), I),
1610 WorkList.end());
1611}
1612
Chris Lattner113f4f42002-06-25 16:13:24 +00001613bool InstCombiner::runOnFunction(Function &F) {
Chris Lattner260ab202002-04-18 17:39:14 +00001614 bool Changed = false;
Chris Lattnerca081252001-12-14 16:52:21 +00001615
Chris Lattner260ab202002-04-18 17:39:14 +00001616 WorkList.insert(WorkList.end(), inst_begin(F), inst_end(F));
Chris Lattnerca081252001-12-14 16:52:21 +00001617
1618 while (!WorkList.empty()) {
1619 Instruction *I = WorkList.back(); // Get an instruction from the worklist
1620 WorkList.pop_back();
1621
Misha Brukman632df282002-10-29 23:06:16 +00001622 // Check to see if we can DCE or ConstantPropagate the instruction...
Chris Lattner99f48c62002-09-02 04:59:56 +00001623 // Check to see if we can DIE the instruction...
1624 if (isInstructionTriviallyDead(I)) {
1625 // Add operands to the worklist...
1626 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
1627 if (Instruction *Op = dyn_cast<Instruction>(I->getOperand(i)))
1628 WorkList.push_back(Op);
1629
1630 ++NumDeadInst;
1631 BasicBlock::iterator BBI = I;
1632 if (dceInstruction(BBI)) {
1633 removeFromWorkList(I);
1634 continue;
1635 }
1636 }
1637
Misha Brukman632df282002-10-29 23:06:16 +00001638 // Instruction isn't dead, see if we can constant propagate it...
Chris Lattner99f48c62002-09-02 04:59:56 +00001639 if (Constant *C = ConstantFoldInstruction(I)) {
1640 // Add operands to the worklist...
1641 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
1642 if (Instruction *Op = dyn_cast<Instruction>(I->getOperand(i)))
1643 WorkList.push_back(Op);
Chris Lattnerc6509f42002-12-05 22:41:53 +00001644 ReplaceInstUsesWith(*I, C);
1645
Chris Lattner99f48c62002-09-02 04:59:56 +00001646 ++NumConstProp;
1647 BasicBlock::iterator BBI = I;
1648 if (dceInstruction(BBI)) {
1649 removeFromWorkList(I);
1650 continue;
1651 }
1652 }
1653
Chris Lattnerca081252001-12-14 16:52:21 +00001654 // Now that we have an instruction, try combining it to simplify it...
Chris Lattnerae7a0d32002-08-02 19:29:35 +00001655 if (Instruction *Result = visit(*I)) {
Chris Lattner0b18c1d2002-05-10 15:38:35 +00001656 ++NumCombined;
Chris Lattner260ab202002-04-18 17:39:14 +00001657 // Should we replace the old instruction with a new one?
Chris Lattner053c0932002-05-14 15:24:07 +00001658 if (Result != I) {
1659 // Instructions can end up on the worklist more than once. Make sure
1660 // we do not process an instruction that has been deleted.
Chris Lattner99f48c62002-09-02 04:59:56 +00001661 removeFromWorkList(I);
Chris Lattner260ab202002-04-18 17:39:14 +00001662 ReplaceInstWithInst(I, Result);
Chris Lattner113f4f42002-06-25 16:13:24 +00001663 } else {
Chris Lattnerae7a0d32002-08-02 19:29:35 +00001664 BasicBlock::iterator II = I;
1665
1666 // If the instruction was modified, it's possible that it is now dead.
1667 // if so, remove it.
1668 if (dceInstruction(II)) {
1669 // Instructions may end up in the worklist more than once. Erase them
1670 // all.
Chris Lattner99f48c62002-09-02 04:59:56 +00001671 removeFromWorkList(I);
Chris Lattnerae7a0d32002-08-02 19:29:35 +00001672 Result = 0;
1673 }
Chris Lattner053c0932002-05-14 15:24:07 +00001674 }
Chris Lattner260ab202002-04-18 17:39:14 +00001675
Chris Lattnerae7a0d32002-08-02 19:29:35 +00001676 if (Result) {
1677 WorkList.push_back(Result);
1678 AddUsesToWorkList(*Result);
1679 }
Chris Lattner260ab202002-04-18 17:39:14 +00001680 Changed = true;
Chris Lattnerca081252001-12-14 16:52:21 +00001681 }
1682 }
1683
Chris Lattner260ab202002-04-18 17:39:14 +00001684 return Changed;
Chris Lattner04805fa2002-02-26 21:46:54 +00001685}
1686
1687Pass *createInstructionCombiningPass() {
Chris Lattner260ab202002-04-18 17:39:14 +00001688 return new InstCombiner();
Chris Lattner04805fa2002-02-26 21:46:54 +00001689}