blob: 83544743ff79990b89f4de611e8a1636b1721fc1 [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
18// 2. Logical operators with constant operands are always grouped so that
19// 'or's are performed first, then 'and's, then 'xor's.
20// 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//
244static inline Constant *dyn_castMaskingAnd(Value *V) {
245 if (Instruction *I = dyn_cast<Instruction>(V))
246 if (I->getOpcode() == Instruction::And)
247 return dyn_cast<Constant>(I->getOperand(1));
248
249 // If this is a constant, it acts just like we were masking with it.
250 return dyn_cast<Constant>(V);
251}
Chris Lattner3082c5a2003-02-18 19:28:33 +0000252
253// Log2 - Calculate the log base 2 for the specified value if it is exactly a
254// power of 2.
255static unsigned Log2(uint64_t Val) {
256 assert(Val > 1 && "Values 0 and 1 should be handled elsewhere!");
257 unsigned Count = 0;
258 while (Val != 1) {
259 if (Val & 1) return 0; // Multiple bits set?
260 Val >>= 1;
261 ++Count;
262 }
263 return Count;
Chris Lattner31ae8632002-08-14 17:51:49 +0000264}
265
Chris Lattner113f4f42002-06-25 16:13:24 +0000266Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000267 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +0000268 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
Chris Lattner9fa53de2002-05-06 16:49:18 +0000269
270 // Eliminate 'add int %X, 0'
Chris Lattnere6794492002-08-12 21:17:25 +0000271 if (RHS == Constant::getNullValue(I.getType()))
272 return ReplaceInstUsesWith(I, LHS);
Chris Lattner9fa53de2002-05-06 16:49:18 +0000273
Chris Lattner147e9752002-05-08 22:46:53 +0000274 // -A + B --> B - A
Chris Lattnerbb74e222003-03-10 23:06:50 +0000275 if (Value *V = dyn_castNegVal(LHS))
Chris Lattner147e9752002-05-08 22:46:53 +0000276 return BinaryOperator::create(Instruction::Sub, RHS, V);
Chris Lattner9fa53de2002-05-06 16:49:18 +0000277
278 // A + -B --> A - B
Chris Lattnerbb74e222003-03-10 23:06:50 +0000279 if (!isa<Constant>(RHS))
280 if (Value *V = dyn_castNegVal(RHS))
281 return BinaryOperator::create(Instruction::Sub, LHS, V);
Chris Lattner260ab202002-04-18 17:39:14 +0000282
Chris Lattner57c8d992003-02-18 19:57:07 +0000283 // X*C + X --> X * (C+1)
284 if (dyn_castFoldableMul(LHS) == RHS) {
Chris Lattner34428442003-05-27 16:40:51 +0000285 Constant *CP1 =
286 ConstantExpr::get(Instruction::Add,
287 cast<Constant>(cast<Instruction>(LHS)->getOperand(1)),
288 ConstantInt::get(I.getType(), 1));
Chris Lattner57c8d992003-02-18 19:57:07 +0000289 return BinaryOperator::create(Instruction::Mul, RHS, CP1);
290 }
291
292 // X + X*C --> X * (C+1)
293 if (dyn_castFoldableMul(RHS) == LHS) {
Chris Lattner34428442003-05-27 16:40:51 +0000294 Constant *CP1 =
295 ConstantExpr::get(Instruction::Add,
296 cast<Constant>(cast<Instruction>(RHS)->getOperand(1)),
297 ConstantInt::get(I.getType(), 1));
Chris Lattner57c8d992003-02-18 19:57:07 +0000298 return BinaryOperator::create(Instruction::Mul, LHS, CP1);
299 }
300
Chris Lattner7fb29e12003-03-11 00:12:48 +0000301 // (A & C1)+(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
302 if (Constant *C1 = dyn_castMaskingAnd(LHS))
303 if (Constant *C2 = dyn_castMaskingAnd(RHS))
Chris Lattner34428442003-05-27 16:40:51 +0000304 if (ConstantExpr::get(Instruction::And, C1, C2)->isNullValue())
Chris Lattner7fb29e12003-03-11 00:12:48 +0000305 return BinaryOperator::create(Instruction::Or, LHS, RHS);
306
Chris Lattner113f4f42002-06-25 16:13:24 +0000307 return Changed ? &I : 0;
Chris Lattner260ab202002-04-18 17:39:14 +0000308}
309
Chris Lattnerbdb0ce02003-07-22 21:46:59 +0000310// isSignBit - Return true if the value represented by the constant only has the
311// highest order bit set.
312static bool isSignBit(ConstantInt *CI) {
313 unsigned NumBits = CI->getType()->getPrimitiveSize()*8;
314 return (CI->getRawValue() & ~(-1LL << NumBits)) == (1ULL << (NumBits-1));
315}
316
Chris Lattnerdfae8be2003-07-24 17:35:25 +0000317static unsigned getTypeSizeInBits(const Type *Ty) {
318 return Ty == Type::BoolTy ? 1 : Ty->getPrimitiveSize()*8;
319}
320
Chris Lattner113f4f42002-06-25 16:13:24 +0000321Instruction *InstCombiner::visitSub(BinaryOperator &I) {
Chris Lattner113f4f42002-06-25 16:13:24 +0000322 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000323
Chris Lattnere6794492002-08-12 21:17:25 +0000324 if (Op0 == Op1) // sub X, X -> 0
325 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner260ab202002-04-18 17:39:14 +0000326
Chris Lattnere6794492002-08-12 21:17:25 +0000327 // If this is a 'B = x-(-A)', change to B = x+A...
Chris Lattnerbb74e222003-03-10 23:06:50 +0000328 if (Value *V = dyn_castNegVal(Op1))
Chris Lattner147e9752002-05-08 22:46:53 +0000329 return BinaryOperator::create(Instruction::Add, Op0, V);
Chris Lattner9fa53de2002-05-06 16:49:18 +0000330
Chris Lattner3082c5a2003-02-18 19:28:33 +0000331 // Replace (-1 - A) with (~A)...
332 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0))
333 if (C->isAllOnesValue())
334 return BinaryOperator::createNot(Op1);
Chris Lattnerad3c4952002-05-09 01:29:19 +0000335
Chris Lattner3082c5a2003-02-18 19:28:33 +0000336 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1))
337 if (Op1I->use_size() == 1) {
338 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
339 // is not used by anyone else...
340 //
341 if (Op1I->getOpcode() == Instruction::Sub) {
342 // Swap the two operands of the subexpr...
343 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
344 Op1I->setOperand(0, IIOp1);
345 Op1I->setOperand(1, IIOp0);
346
347 // Create the new top level add instruction...
348 return BinaryOperator::create(Instruction::Add, Op0, Op1);
349 }
350
351 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
352 //
353 if (Op1I->getOpcode() == Instruction::And &&
354 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
355 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
356
357 Instruction *NewNot = BinaryOperator::createNot(OtherOp, "B.not", &I);
358 return BinaryOperator::create(Instruction::And, Op0, NewNot);
359 }
Chris Lattner57c8d992003-02-18 19:57:07 +0000360
361 // X - X*C --> X * (1-C)
362 if (dyn_castFoldableMul(Op1I) == Op0) {
Chris Lattner34428442003-05-27 16:40:51 +0000363 Constant *CP1 =
364 ConstantExpr::get(Instruction::Sub,
365 ConstantInt::get(I.getType(), 1),
366 cast<Constant>(cast<Instruction>(Op1)->getOperand(1)));
Chris Lattner57c8d992003-02-18 19:57:07 +0000367 assert(CP1 && "Couldn't constant fold 1-C?");
368 return BinaryOperator::create(Instruction::Mul, Op0, CP1);
369 }
Chris Lattnerad3c4952002-05-09 01:29:19 +0000370 }
Chris Lattner3082c5a2003-02-18 19:28:33 +0000371
Chris Lattner57c8d992003-02-18 19:57:07 +0000372 // X*C - X --> X * (C-1)
373 if (dyn_castFoldableMul(Op0) == Op1) {
Chris Lattner34428442003-05-27 16:40:51 +0000374 Constant *CP1 =
375 ConstantExpr::get(Instruction::Sub,
376 cast<Constant>(cast<Instruction>(Op0)->getOperand(1)),
377 ConstantInt::get(I.getType(), 1));
Chris Lattner57c8d992003-02-18 19:57:07 +0000378 assert(CP1 && "Couldn't constant fold C - 1?");
379 return BinaryOperator::create(Instruction::Mul, Op1, CP1);
380 }
381
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000382 return 0;
Chris Lattner260ab202002-04-18 17:39:14 +0000383}
384
Chris Lattner113f4f42002-06-25 16:13:24 +0000385Instruction *InstCombiner::visitMul(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000386 bool Changed = SimplifyCommutative(I);
Chris Lattner3082c5a2003-02-18 19:28:33 +0000387 Value *Op0 = I.getOperand(0);
Chris Lattner260ab202002-04-18 17:39:14 +0000388
Chris Lattnere6794492002-08-12 21:17:25 +0000389 // Simplify mul instructions with a constant RHS...
Chris Lattner3082c5a2003-02-18 19:28:33 +0000390 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
391 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
392 const Type *Ty = CI->getType();
Chris Lattner6077c312003-07-23 15:22:26 +0000393 int64_t Val = (int64_t)cast<ConstantInt>(CI)->getRawValue();
Chris Lattner3082c5a2003-02-18 19:28:33 +0000394 switch (Val) {
Chris Lattner35236d82003-06-25 17:09:20 +0000395 case -1: // X * -1 -> -X
396 return BinaryOperator::createNeg(Op0, I.getName());
Chris Lattner3082c5a2003-02-18 19:28:33 +0000397 case 0:
398 return ReplaceInstUsesWith(I, Op1); // Eliminate 'mul double %X, 0'
399 case 1:
400 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul int %X, 1'
401 case 2: // Convert 'mul int %X, 2' to 'add int %X, %X'
402 return BinaryOperator::create(Instruction::Add, Op0, Op0, I.getName());
403 }
Chris Lattner31ba1292002-04-29 22:24:47 +0000404
Chris Lattner3082c5a2003-02-18 19:28:33 +0000405 if (uint64_t C = Log2(Val)) // Replace X*(2^C) with X << C
406 return new ShiftInst(Instruction::Shl, Op0,
407 ConstantUInt::get(Type::UByteTy, C));
408 } else {
409 ConstantFP *Op1F = cast<ConstantFP>(Op1);
410 if (Op1F->isNullValue())
411 return ReplaceInstUsesWith(I, Op1);
Chris Lattner31ba1292002-04-29 22:24:47 +0000412
Chris Lattner3082c5a2003-02-18 19:28:33 +0000413 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
414 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
415 if (Op1F->getValue() == 1.0)
416 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0'
417 }
Chris Lattner260ab202002-04-18 17:39:14 +0000418 }
419
Chris Lattner934a64cf2003-03-10 23:23:04 +0000420 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
421 if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
422 return BinaryOperator::create(Instruction::Mul, Op0v, Op1v);
423
Chris Lattner113f4f42002-06-25 16:13:24 +0000424 return Changed ? &I : 0;
Chris Lattner260ab202002-04-18 17:39:14 +0000425}
426
Chris Lattner113f4f42002-06-25 16:13:24 +0000427Instruction *InstCombiner::visitDiv(BinaryOperator &I) {
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000428 // div X, 1 == X
Chris Lattner3082c5a2003-02-18 19:28:33 +0000429 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I.getOperand(1))) {
Chris Lattnere6794492002-08-12 21:17:25 +0000430 if (RHS->equalsInt(1))
431 return ReplaceInstUsesWith(I, I.getOperand(0));
Chris Lattner3082c5a2003-02-18 19:28:33 +0000432
433 // Check to see if this is an unsigned division with an exact power of 2,
434 // if so, convert to a right shift.
435 if (ConstantUInt *C = dyn_cast<ConstantUInt>(RHS))
436 if (uint64_t Val = C->getValue()) // Don't break X / 0
437 if (uint64_t C = Log2(Val))
438 return new ShiftInst(Instruction::Shr, I.getOperand(0),
439 ConstantUInt::get(Type::UByteTy, C));
440 }
441
442 // 0 / X == 0, we don't need to preserve faults!
443 if (ConstantInt *LHS = dyn_cast<ConstantInt>(I.getOperand(0)))
444 if (LHS->equalsInt(0))
445 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
446
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000447 return 0;
448}
449
450
Chris Lattner113f4f42002-06-25 16:13:24 +0000451Instruction *InstCombiner::visitRem(BinaryOperator &I) {
Chris Lattner3082c5a2003-02-18 19:28:33 +0000452 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I.getOperand(1))) {
453 if (RHS->equalsInt(1)) // X % 1 == 0
454 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
455
456 // Check to see if this is an unsigned remainder with an exact power of 2,
457 // if so, convert to a bitwise and.
458 if (ConstantUInt *C = dyn_cast<ConstantUInt>(RHS))
459 if (uint64_t Val = C->getValue()) // Don't break X % 0 (divide by zero)
460 if (Log2(Val))
461 return BinaryOperator::create(Instruction::And, I.getOperand(0),
462 ConstantUInt::get(I.getType(), Val-1));
463 }
464
465 // 0 % X == 0, we don't need to preserve faults!
466 if (ConstantInt *LHS = dyn_cast<ConstantInt>(I.getOperand(0)))
467 if (LHS->equalsInt(0))
Chris Lattnere6794492002-08-12 21:17:25 +0000468 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
469
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000470 return 0;
471}
472
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000473// isMaxValueMinusOne - return true if this is Max-1
Chris Lattnere6794492002-08-12 21:17:25 +0000474static bool isMaxValueMinusOne(const ConstantInt *C) {
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000475 if (const ConstantUInt *CU = dyn_cast<ConstantUInt>(C)) {
476 // Calculate -1 casted to the right type...
477 unsigned TypeBits = C->getType()->getPrimitiveSize()*8;
478 uint64_t Val = ~0ULL; // All ones
479 Val >>= 64-TypeBits; // Shift out unwanted 1 bits...
480 return CU->getValue() == Val-1;
481 }
482
483 const ConstantSInt *CS = cast<ConstantSInt>(C);
484
485 // Calculate 0111111111..11111
486 unsigned TypeBits = C->getType()->getPrimitiveSize()*8;
487 int64_t Val = INT64_MAX; // All ones
488 Val >>= 64-TypeBits; // Shift out unwanted 1 bits...
489 return CS->getValue() == Val-1;
490}
491
492// isMinValuePlusOne - return true if this is Min+1
Chris Lattnere6794492002-08-12 21:17:25 +0000493static bool isMinValuePlusOne(const ConstantInt *C) {
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000494 if (const ConstantUInt *CU = dyn_cast<ConstantUInt>(C))
495 return CU->getValue() == 1;
496
497 const ConstantSInt *CS = cast<ConstantSInt>(C);
498
499 // Calculate 1111111111000000000000
500 unsigned TypeBits = C->getType()->getPrimitiveSize()*8;
501 int64_t Val = -1; // All ones
502 Val <<= TypeBits-1; // Shift over to the right spot
503 return CS->getValue() == Val+1;
504}
505
506
Chris Lattner113f4f42002-06-25 16:13:24 +0000507Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000508 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +0000509 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000510
511 // and X, X = X and X, 0 == 0
Chris Lattnere6794492002-08-12 21:17:25 +0000512 if (Op0 == Op1 || Op1 == Constant::getNullValue(I.getType()))
513 return ReplaceInstUsesWith(I, Op1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000514
515 // and X, -1 == X
Chris Lattner49b47ae2003-07-23 17:57:01 +0000516 if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
Chris Lattnere6794492002-08-12 21:17:25 +0000517 if (RHS->isAllOnesValue())
518 return ReplaceInstUsesWith(I, Op0);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000519
Chris Lattner33217db2003-07-23 19:36:21 +0000520 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
521 Value *X = Op0I->getOperand(0);
Chris Lattner16464b32003-07-23 19:25:52 +0000522 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
523 if (Op0I->getOpcode() == Instruction::Xor) {
Chris Lattner33217db2003-07-23 19:36:21 +0000524 if ((*RHS & *Op0CI)->isNullValue()) {
525 // (X ^ C1) & C2 --> (X & C2) iff (C1&C2) == 0
526 return BinaryOperator::create(Instruction::And, X, RHS);
527 } else if (isOnlyUse(Op0)) {
Chris Lattner16464b32003-07-23 19:25:52 +0000528 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
529 std::string Op0Name = Op0I->getName(); Op0I->setName("");
530 Instruction *And = BinaryOperator::create(Instruction::And,
Chris Lattner33217db2003-07-23 19:36:21 +0000531 X, RHS, Op0Name);
Chris Lattner16464b32003-07-23 19:25:52 +0000532 InsertNewInstBefore(And, I);
533 return BinaryOperator::create(Instruction::Xor, And, *RHS & *Op0CI);
534 }
535 } else if (Op0I->getOpcode() == Instruction::Or) {
536 // (X | C1) & C2 --> X & C2 iff C1 & C1 == 0
537 if ((*RHS & *Op0CI)->isNullValue())
Chris Lattner33217db2003-07-23 19:36:21 +0000538 return BinaryOperator::create(Instruction::And, X, RHS);
Chris Lattner16464b32003-07-23 19:25:52 +0000539
540 Constant *Together = *RHS & *Op0CI;
541 if (Together == RHS) // (X | C) & C --> C
542 return ReplaceInstUsesWith(I, RHS);
543
544 if (isOnlyUse(Op0)) {
545 if (Together != Op0CI) {
546 // (X | C1) & C2 --> (X | (C1&C2)) & C2
547 std::string Op0Name = Op0I->getName(); Op0I->setName("");
Chris Lattner33217db2003-07-23 19:36:21 +0000548 Instruction *Or = BinaryOperator::create(Instruction::Or, X,
549 Together, Op0Name);
Chris Lattner16464b32003-07-23 19:25:52 +0000550 InsertNewInstBefore(Or, I);
551 return BinaryOperator::create(Instruction::And, Or, RHS);
552 }
553 }
Chris Lattner49b47ae2003-07-23 17:57:01 +0000554 }
Chris Lattner33217db2003-07-23 19:36:21 +0000555 }
Chris Lattner49b47ae2003-07-23 17:57:01 +0000556 }
557
Chris Lattnerbb74e222003-03-10 23:06:50 +0000558 Value *Op0NotVal = dyn_castNotVal(Op0);
559 Value *Op1NotVal = dyn_castNotVal(Op1);
Chris Lattner3082c5a2003-02-18 19:28:33 +0000560
561 // (~A & ~B) == (~(A | B)) - Demorgan's Law
Chris Lattnerbb74e222003-03-10 23:06:50 +0000562 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Chris Lattner3082c5a2003-02-18 19:28:33 +0000563 Instruction *Or = BinaryOperator::create(Instruction::Or, Op0NotVal,
Chris Lattner49b47ae2003-07-23 17:57:01 +0000564 Op1NotVal,I.getName()+".demorgan");
565 InsertNewInstBefore(Or, I);
Chris Lattner3082c5a2003-02-18 19:28:33 +0000566 return BinaryOperator::createNot(Or);
567 }
568
569 if (Op0NotVal == Op1 || Op1NotVal == Op0) // A & ~A == ~A & A == 0
570 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner65217ff2002-08-23 18:32:43 +0000571
Chris Lattner113f4f42002-06-25 16:13:24 +0000572 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000573}
574
575
576
Chris Lattner113f4f42002-06-25 16:13:24 +0000577Instruction *InstCombiner::visitOr(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000578 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +0000579 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000580
581 // or X, X = X or X, 0 == X
Chris Lattnere6794492002-08-12 21:17:25 +0000582 if (Op0 == Op1 || Op1 == Constant::getNullValue(I.getType()))
583 return ReplaceInstUsesWith(I, Op0);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000584
585 // or X, -1 == -1
Chris Lattner8f0d1562003-07-23 18:29:44 +0000586 if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
Chris Lattnere6794492002-08-12 21:17:25 +0000587 if (RHS->isAllOnesValue())
588 return ReplaceInstUsesWith(I, Op1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000589
Chris Lattner8f0d1562003-07-23 18:29:44 +0000590 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
591 // (X & C1) | C2 --> (X | C2) & (C1|C2)
592 if (Op0I->getOpcode() == Instruction::And && isOnlyUse(Op0))
593 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
594 std::string Op0Name = Op0I->getName(); Op0I->setName("");
595 Instruction *Or = BinaryOperator::create(Instruction::Or,
596 Op0I->getOperand(0), RHS,
597 Op0Name);
598 InsertNewInstBefore(Or, I);
599 return BinaryOperator::create(Instruction::And, Or, *RHS | *Op0CI);
600 }
601
602 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
603 if (Op0I->getOpcode() == Instruction::Xor && isOnlyUse(Op0))
604 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
605 std::string Op0Name = Op0I->getName(); Op0I->setName("");
606 Instruction *Or = BinaryOperator::create(Instruction::Or,
607 Op0I->getOperand(0), RHS,
608 Op0Name);
609 InsertNewInstBefore(Or, I);
610 return BinaryOperator::create(Instruction::Xor, Or, *Op0CI & *~*RHS);
611 }
612 }
613 }
614
Chris Lattner3e327a42003-03-10 23:13:59 +0000615 Value *Op0NotVal = dyn_castNotVal(Op0);
616 Value *Op1NotVal = dyn_castNotVal(Op1);
Chris Lattner3082c5a2003-02-18 19:28:33 +0000617
Chris Lattner3e327a42003-03-10 23:13:59 +0000618 if (Op1 == Op0NotVal) // ~A | A == -1
619 return ReplaceInstUsesWith(I,
620 ConstantIntegral::getAllOnesValue(I.getType()));
621
622 if (Op0 == Op1NotVal) // A | ~A == -1
623 return ReplaceInstUsesWith(I,
624 ConstantIntegral::getAllOnesValue(I.getType()));
625
626 // (~A | ~B) == (~(A & B)) - Demorgan's Law
627 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
628 Instruction *And = BinaryOperator::create(Instruction::And, Op0NotVal,
629 Op1NotVal,I.getName()+".demorgan",
630 &I);
631 WorkList.push_back(And);
632 return BinaryOperator::createNot(And);
633 }
Chris Lattner3082c5a2003-02-18 19:28:33 +0000634
Chris Lattner113f4f42002-06-25 16:13:24 +0000635 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000636}
637
638
639
Chris Lattner113f4f42002-06-25 16:13:24 +0000640Instruction *InstCombiner::visitXor(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000641 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +0000642 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000643
644 // xor X, X = 0
Chris Lattnere6794492002-08-12 21:17:25 +0000645 if (Op0 == Op1)
646 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000647
Chris Lattner97638592003-07-23 21:37:07 +0000648 if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000649 // xor X, 0 == X
Chris Lattner97638592003-07-23 21:37:07 +0000650 if (RHS->isNullValue())
Chris Lattnere6794492002-08-12 21:17:25 +0000651 return ReplaceInstUsesWith(I, Op0);
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000652
Chris Lattner97638592003-07-23 21:37:07 +0000653 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Chris Lattnerb8d6e402002-08-20 18:24:26 +0000654 // xor (setcc A, B), true = not (setcc A, B) = setncc A, B
Chris Lattner97638592003-07-23 21:37:07 +0000655 if (SetCondInst *SCI = dyn_cast<SetCondInst>(Op0I))
656 if (RHS == ConstantBool::True && SCI->use_size() == 1)
Chris Lattnerb8d6e402002-08-20 18:24:26 +0000657 return new SetCondInst(SCI->getInverseCondition(),
658 SCI->getOperand(0), SCI->getOperand(1));
Chris Lattner97638592003-07-23 21:37:07 +0000659
660 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
661 if (Op0I->getOpcode() == Instruction::And) {
662 // (X & C1) ^ C2 --> (X & C1) | C2 iff (C1&C2) == 0
663 if ((*RHS & *Op0CI)->isNullValue())
664 return BinaryOperator::create(Instruction::Or, Op0, RHS);
665 } else if (Op0I->getOpcode() == Instruction::Or) {
666 // (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
667 if ((*RHS & *Op0CI) == RHS)
668 return BinaryOperator::create(Instruction::And, Op0, ~*RHS);
669 }
Chris Lattnerb8d6e402002-08-20 18:24:26 +0000670 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000671 }
672
Chris Lattnerbb74e222003-03-10 23:06:50 +0000673 if (Value *X = dyn_castNotVal(Op0)) // ~A ^ A == -1
Chris Lattner3082c5a2003-02-18 19:28:33 +0000674 if (X == Op1)
675 return ReplaceInstUsesWith(I,
676 ConstantIntegral::getAllOnesValue(I.getType()));
677
Chris Lattnerbb74e222003-03-10 23:06:50 +0000678 if (Value *X = dyn_castNotVal(Op1)) // A ^ ~A == -1
Chris Lattner3082c5a2003-02-18 19:28:33 +0000679 if (X == Op0)
680 return ReplaceInstUsesWith(I,
681 ConstantIntegral::getAllOnesValue(I.getType()));
682
Chris Lattner1bbb7b62003-03-10 18:24:17 +0000683 if (Instruction *Op1I = dyn_cast<Instruction>(Op1))
684 if (Op1I->getOpcode() == Instruction::Or)
685 if (Op1I->getOperand(0) == Op0) { // B^(B|A) == (A|B)^B
686 cast<BinaryOperator>(Op1I)->swapOperands();
687 I.swapOperands();
688 std::swap(Op0, Op1);
689 } else if (Op1I->getOperand(1) == Op0) { // B^(A|B) == (A|B)^B
690 I.swapOperands();
691 std::swap(Op0, Op1);
692 }
693
694 if (Instruction *Op0I = dyn_cast<Instruction>(Op0))
695 if (Op0I->getOpcode() == Instruction::Or && Op0I->use_size() == 1) {
696 if (Op0I->getOperand(0) == Op1) // (B|A)^B == (A|B)^B
697 cast<BinaryOperator>(Op0I)->swapOperands();
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000698 if (Op0I->getOperand(1) == Op1) { // (A|B)^B == A & ~B
Chris Lattner1bbb7b62003-03-10 18:24:17 +0000699 Value *NotB = BinaryOperator::createNot(Op1, Op1->getName()+".not", &I);
700 WorkList.push_back(cast<Instruction>(NotB));
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000701 return BinaryOperator::create(Instruction::And, Op0I->getOperand(0),
702 NotB);
Chris Lattner1bbb7b62003-03-10 18:24:17 +0000703 }
704 }
705
Chris Lattner7fb29e12003-03-11 00:12:48 +0000706 // (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1^C2 == 0
707 if (Constant *C1 = dyn_castMaskingAnd(Op0))
708 if (Constant *C2 = dyn_castMaskingAnd(Op1))
Chris Lattner34428442003-05-27 16:40:51 +0000709 if (ConstantExpr::get(Instruction::And, C1, C2)->isNullValue())
Chris Lattner7fb29e12003-03-11 00:12:48 +0000710 return BinaryOperator::create(Instruction::Or, Op0, Op1);
711
Chris Lattner113f4f42002-06-25 16:13:24 +0000712 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000713}
714
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000715// AddOne, SubOne - Add or subtract a constant one from an integer constant...
716static Constant *AddOne(ConstantInt *C) {
Chris Lattner34428442003-05-27 16:40:51 +0000717 Constant *Result = ConstantExpr::get(Instruction::Add, C,
718 ConstantInt::get(C->getType(), 1));
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000719 assert(Result && "Constant folding integer addition failed!");
720 return Result;
721}
722static Constant *SubOne(ConstantInt *C) {
Chris Lattner34428442003-05-27 16:40:51 +0000723 Constant *Result = ConstantExpr::get(Instruction::Sub, C,
724 ConstantInt::get(C->getType(), 1));
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000725 assert(Result && "Constant folding integer addition failed!");
726 return Result;
727}
728
Chris Lattner1fc23f32002-05-09 20:11:54 +0000729// isTrueWhenEqual - Return true if the specified setcondinst instruction is
730// true when both operands are equal...
731//
Chris Lattner113f4f42002-06-25 16:13:24 +0000732static bool isTrueWhenEqual(Instruction &I) {
733 return I.getOpcode() == Instruction::SetEQ ||
734 I.getOpcode() == Instruction::SetGE ||
735 I.getOpcode() == Instruction::SetLE;
Chris Lattner1fc23f32002-05-09 20:11:54 +0000736}
737
Chris Lattner113f4f42002-06-25 16:13:24 +0000738Instruction *InstCombiner::visitSetCondInst(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000739 bool Changed = SimplifyCommutative(I);
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000740 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
741 const Type *Ty = Op0->getType();
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000742
743 // setcc X, X
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000744 if (Op0 == Op1)
745 return ReplaceInstUsesWith(I, ConstantBool::get(isTrueWhenEqual(I)));
Chris Lattner1fc23f32002-05-09 20:11:54 +0000746
747 // setcc <global*>, 0 - Global value addresses are never null!
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000748 if (isa<GlobalValue>(Op0) && isa<ConstantPointerNull>(Op1))
749 return ReplaceInstUsesWith(I, ConstantBool::get(!isTrueWhenEqual(I)));
750
751 // setcc's with boolean values can always be turned into bitwise operations
752 if (Ty == Type::BoolTy) {
753 // If this is <, >, or !=, we can change this into a simple xor instruction
754 if (!isTrueWhenEqual(I))
755 return BinaryOperator::create(Instruction::Xor, Op0, Op1, I.getName());
756
757 // Otherwise we need to make a temporary intermediate instruction and insert
758 // it into the instruction stream. This is what we are after:
759 //
760 // seteq bool %A, %B -> ~(A^B)
761 // setle bool %A, %B -> ~A | B
762 // setge bool %A, %B -> A | ~B
763 //
764 if (I.getOpcode() == Instruction::SetEQ) { // seteq case
765 Instruction *Xor = BinaryOperator::create(Instruction::Xor, Op0, Op1,
766 I.getName()+"tmp");
767 InsertNewInstBefore(Xor, I);
Chris Lattner31ae8632002-08-14 17:51:49 +0000768 return BinaryOperator::createNot(Xor, I.getName());
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000769 }
770
771 // Handle the setXe cases...
772 assert(I.getOpcode() == Instruction::SetGE ||
773 I.getOpcode() == Instruction::SetLE);
774
775 if (I.getOpcode() == Instruction::SetGE)
776 std::swap(Op0, Op1); // Change setge -> setle
777
778 // Now we just have the SetLE case.
Chris Lattner31ae8632002-08-14 17:51:49 +0000779 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000780 InsertNewInstBefore(Not, I);
781 return BinaryOperator::create(Instruction::Or, Not, Op1, I.getName());
782 }
783
784 // Check to see if we are doing one of many comparisons against constant
785 // integers at the end of their ranges...
786 //
787 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnerd492a0b2003-07-23 17:02:11 +0000788 // Simplify seteq and setne instructions...
789 if (I.getOpcode() == Instruction::SetEQ ||
790 I.getOpcode() == Instruction::SetNE) {
791 bool isSetNE = I.getOpcode() == Instruction::SetNE;
792
793 if (CI->isNullValue()) { // Simplify [seteq|setne] X, 0
794 CastInst *Val = new CastInst(Op0, Type::BoolTy, I.getName()+".not");
795 if (isSetNE) return Val;
796
Chris Lattnere967b342003-06-04 05:10:11 +0000797 // seteq X, 0 -> not (cast X to bool)
Chris Lattnere967b342003-06-04 05:10:11 +0000798 InsertNewInstBefore(Val, I);
799 return BinaryOperator::createNot(Val, I.getName());
800 }
Chris Lattnerd492a0b2003-07-23 17:02:11 +0000801
Chris Lattnercfbce7c2003-07-23 17:26:36 +0000802 // If the first operand is (and|or|xor) with a constant, and the second
Chris Lattnerd492a0b2003-07-23 17:02:11 +0000803 // operand is a constant, simplify a bit.
804 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
805 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1)))
806 if (BO->getOpcode() == Instruction::Or) {
807 // If bits are being or'd in that are not present in the constant we
808 // are comparing against, then the comparison could never succeed!
809 if (!(*BOC & *~*CI)->isNullValue())
810 return ReplaceInstUsesWith(I, ConstantBool::get(isSetNE));
811 } else if (BO->getOpcode() == Instruction::And) {
812 // If bits are being compared against that are and'd out, then the
813 // comparison can never succeed!
814 if (!(*CI & *~*BOC)->isNullValue())
815 return ReplaceInstUsesWith(I, ConstantBool::get(isSetNE));
Chris Lattnercfbce7c2003-07-23 17:26:36 +0000816 } else if (BO->getOpcode() == Instruction::Xor) {
817 // For the xor case, we can always just xor the two constants
818 // together, potentially eliminating the explicit xor.
819 return BinaryOperator::create(I.getOpcode(), BO->getOperand(0),
820 *CI ^ *BOC);
Chris Lattnerd492a0b2003-07-23 17:02:11 +0000821 }
Chris Lattnere967b342003-06-04 05:10:11 +0000822 }
Chris Lattner791ac1a2003-06-01 03:35:25 +0000823
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000824 // Check to see if we are comparing against the minimum or maximum value...
Chris Lattnere6794492002-08-12 21:17:25 +0000825 if (CI->isMinValue()) {
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000826 if (I.getOpcode() == Instruction::SetLT) // A < MIN -> FALSE
827 return ReplaceInstUsesWith(I, ConstantBool::False);
828 if (I.getOpcode() == Instruction::SetGE) // A >= MIN -> TRUE
829 return ReplaceInstUsesWith(I, ConstantBool::True);
830 if (I.getOpcode() == Instruction::SetLE) // A <= MIN -> A == MIN
831 return BinaryOperator::create(Instruction::SetEQ, Op0,Op1, I.getName());
832 if (I.getOpcode() == Instruction::SetGT) // A > MIN -> A != MIN
833 return BinaryOperator::create(Instruction::SetNE, Op0,Op1, I.getName());
834
Chris Lattnere6794492002-08-12 21:17:25 +0000835 } else if (CI->isMaxValue()) {
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000836 if (I.getOpcode() == Instruction::SetGT) // A > MAX -> FALSE
837 return ReplaceInstUsesWith(I, ConstantBool::False);
838 if (I.getOpcode() == Instruction::SetLE) // A <= MAX -> TRUE
839 return ReplaceInstUsesWith(I, ConstantBool::True);
840 if (I.getOpcode() == Instruction::SetGE) // A >= MAX -> A == MAX
841 return BinaryOperator::create(Instruction::SetEQ, Op0,Op1, I.getName());
842 if (I.getOpcode() == Instruction::SetLT) // A < MAX -> A != MAX
843 return BinaryOperator::create(Instruction::SetNE, Op0,Op1, I.getName());
844
845 // Comparing against a value really close to min or max?
846 } else if (isMinValuePlusOne(CI)) {
847 if (I.getOpcode() == Instruction::SetLT) // A < MIN+1 -> A == MIN
848 return BinaryOperator::create(Instruction::SetEQ, Op0,
849 SubOne(CI), I.getName());
850 if (I.getOpcode() == Instruction::SetGE) // A >= MIN-1 -> A != MIN
851 return BinaryOperator::create(Instruction::SetNE, Op0,
852 SubOne(CI), I.getName());
853
854 } else if (isMaxValueMinusOne(CI)) {
855 if (I.getOpcode() == Instruction::SetGT) // A > MAX-1 -> A == MAX
856 return BinaryOperator::create(Instruction::SetEQ, Op0,
857 AddOne(CI), I.getName());
858 if (I.getOpcode() == Instruction::SetLE) // A <= MAX-1 -> A != MAX
859 return BinaryOperator::create(Instruction::SetNE, Op0,
860 AddOne(CI), I.getName());
861 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000862 }
863
Chris Lattner113f4f42002-06-25 16:13:24 +0000864 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000865}
866
867
868
Chris Lattnere8d6c602003-03-10 19:16:08 +0000869Instruction *InstCombiner::visitShiftInst(ShiftInst &I) {
Chris Lattner113f4f42002-06-25 16:13:24 +0000870 assert(I.getOperand(1)->getType() == Type::UByteTy);
871 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000872
873 // shl X, 0 == X and shr X, 0 == X
874 // shl 0, X == 0 and shr 0, X == 0
875 if (Op1 == Constant::getNullValue(Type::UByteTy) ||
Chris Lattnere6794492002-08-12 21:17:25 +0000876 Op0 == Constant::getNullValue(Op0->getType()))
877 return ReplaceInstUsesWith(I, Op0);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000878
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000879 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(Op1)) {
Chris Lattner3204d4e2003-07-24 17:52:58 +0000880 // shl uint X, 32 = 0 and shr ubyte Y, 9 = 0, ... just don't eliminate shr
881 // of a signed value.
882 //
Chris Lattnere8d6c602003-03-10 19:16:08 +0000883 unsigned TypeBits = Op0->getType()->getPrimitiveSize()*8;
884 if (CUI->getValue() >= TypeBits &&
885 (!Op0->getType()->isSigned() || I.getOpcode() == Instruction::Shl))
886 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
Chris Lattner55f3d942002-09-10 23:04:09 +0000887
Chris Lattner3204d4e2003-07-24 17:52:58 +0000888 // If this is a shift of a shift, see if we can fold the two together...
889 if (ShiftInst *Op0SI = dyn_cast<ShiftInst>(Op0)) {
Chris Lattnerab780df2003-07-24 18:38:56 +0000890 if (ConstantUInt *ShiftAmt1C =
891 dyn_cast<ConstantUInt>(Op0SI->getOperand(1))) {
Chris Lattner3204d4e2003-07-24 17:52:58 +0000892 unsigned ShiftAmt1 = ShiftAmt1C->getValue();
893 unsigned ShiftAmt2 = CUI->getValue();
894
895 // Check for (A << c1) << c2 and (A >> c1) >> c2
896 if (I.getOpcode() == Op0SI->getOpcode()) {
897 unsigned Amt = ShiftAmt1+ShiftAmt2; // Fold into one big shift...
898 return new ShiftInst(I.getOpcode(), Op0SI->getOperand(0),
899 ConstantUInt::get(Type::UByteTy, Amt));
900 }
901
Chris Lattnerab780df2003-07-24 18:38:56 +0000902 // Check for (A << c1) >> c2 or visaversa. If we are dealing with
903 // signed types, we can only support the (A >> c1) << c2 configuration,
904 // because it can not turn an arbitrary bit of A into a sign bit.
905 if (I.getType()->isUnsigned() || I.getOpcode() == Instruction::Shl) {
Chris Lattner3204d4e2003-07-24 17:52:58 +0000906 // Calculate bitmask for what gets shifted off the edge...
907 Constant *C = ConstantIntegral::getAllOnesValue(I.getType());
908 if (I.getOpcode() == Instruction::Shr)
909 C = ConstantExpr::getShift(Instruction::Shr, C, ShiftAmt1C);
910 else
911 C = ConstantExpr::getShift(Instruction::Shl, C, ShiftAmt1C);
912
913 Instruction *Mask =
914 BinaryOperator::create(Instruction::And, Op0SI->getOperand(0),
915 C, Op0SI->getOperand(0)->getName()+".mask");
916 InsertNewInstBefore(Mask, I);
917
918 // Figure out what flavor of shift we should use...
919 if (ShiftAmt1 == ShiftAmt2)
920 return ReplaceInstUsesWith(I, Mask); // (A << c) >> c === A & c2
921 else if (ShiftAmt1 < ShiftAmt2) {
922 return new ShiftInst(I.getOpcode(), Mask,
923 ConstantUInt::get(Type::UByteTy, ShiftAmt2-ShiftAmt1));
924 } else {
925 return new ShiftInst(Op0SI->getOpcode(), Mask,
926 ConstantUInt::get(Type::UByteTy, ShiftAmt1-ShiftAmt2));
927 }
928 }
929 }
930 }
Chris Lattnerab780df2003-07-24 18:38:56 +0000931
932 // Check to see if we are shifting left by 1. If so, turn it into an add
933 // instruction.
934 if (I.getOpcode() == Instruction::Shl && CUI->equalsInt(1))
935 // Convert 'shl int %X, 1' to 'add int %X, %X'
936 return BinaryOperator::create(Instruction::Add, Op0, Op0, I.getName());
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000937 }
Chris Lattner2e0fb392002-10-08 16:16:40 +0000938
939 // shr int -1, X = -1 (for any arithmetic shift rights of ~0)
Chris Lattner3204d4e2003-07-24 17:52:58 +0000940 if (I.getOpcode() == Instruction::Shr)
941 if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(Op0))
942 if (CSI->isAllOnesValue())
943 return ReplaceInstUsesWith(I, CSI);
Chris Lattner2e0fb392002-10-08 16:16:40 +0000944
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000945 return 0;
946}
947
948
Chris Lattner48a44f72002-05-02 17:06:02 +0000949// isEliminableCastOfCast - Return true if it is valid to eliminate the CI
950// instruction.
951//
Chris Lattnerdfae8be2003-07-24 17:35:25 +0000952static inline bool isEliminableCastOfCast(const Type *SrcTy, const Type *MidTy,
953 const Type *DstTy) {
Chris Lattner48a44f72002-05-02 17:06:02 +0000954
Chris Lattner650b6da2002-08-02 20:00:25 +0000955 // It is legal to eliminate the instruction if casting A->B->A if the sizes
956 // are identical and the bits don't get reinterpreted (for example
Chris Lattner0bb75912002-08-14 23:21:10 +0000957 // int->float->int would not be allowed)
Misha Brukmane5838c42003-05-20 18:45:36 +0000958 if (SrcTy == DstTy && SrcTy->isLosslesslyConvertibleTo(MidTy))
Chris Lattner650b6da2002-08-02 20:00:25 +0000959 return true;
Chris Lattner48a44f72002-05-02 17:06:02 +0000960
961 // Allow free casting and conversion of sizes as long as the sign doesn't
962 // change...
Chris Lattnerb0b412e2002-09-03 01:08:28 +0000963 if (SrcTy->isIntegral() && MidTy->isIntegral() && DstTy->isIntegral()) {
Chris Lattner650b6da2002-08-02 20:00:25 +0000964 unsigned SrcSize = SrcTy->getPrimitiveSize();
965 unsigned MidSize = MidTy->getPrimitiveSize();
966 unsigned DstSize = DstTy->getPrimitiveSize();
Chris Lattner650b6da2002-08-02 20:00:25 +0000967
Chris Lattner3732aca2002-08-15 16:15:25 +0000968 // Cases where we are monotonically decreasing the size of the type are
969 // always ok, regardless of what sign changes are going on.
970 //
Chris Lattner0bb75912002-08-14 23:21:10 +0000971 if (SrcSize >= MidSize && MidSize >= DstSize)
Chris Lattner650b6da2002-08-02 20:00:25 +0000972 return true;
Chris Lattner3732aca2002-08-15 16:15:25 +0000973
Chris Lattner555518c2002-09-23 23:39:43 +0000974 // Cases where the source and destination type are the same, but the middle
975 // type is bigger are noops.
976 //
977 if (SrcSize == DstSize && MidSize > SrcSize)
978 return true;
979
Chris Lattner3732aca2002-08-15 16:15:25 +0000980 // If we are monotonically growing, things are more complex.
981 //
982 if (SrcSize <= MidSize && MidSize <= DstSize) {
983 // We have eight combinations of signedness to worry about. Here's the
984 // table:
985 static const int SignTable[8] = {
986 // CODE, SrcSigned, MidSigned, DstSigned, Comment
987 1, // U U U Always ok
988 1, // U U S Always ok
989 3, // U S U Ok iff SrcSize != MidSize
990 3, // U S S Ok iff SrcSize != MidSize
991 0, // S U U Never ok
992 2, // S U S Ok iff MidSize == DstSize
993 1, // S S U Always ok
994 1, // S S S Always ok
995 };
996
997 // Choose an action based on the current entry of the signtable that this
998 // cast of cast refers to...
999 unsigned Row = SrcTy->isSigned()*4+MidTy->isSigned()*2+DstTy->isSigned();
1000 switch (SignTable[Row]) {
1001 case 0: return false; // Never ok
1002 case 1: return true; // Always ok
1003 case 2: return MidSize == DstSize; // Ok iff MidSize == DstSize
1004 case 3: // Ok iff SrcSize != MidSize
1005 return SrcSize != MidSize || SrcTy == Type::BoolTy;
1006 default: assert(0 && "Bad entry in sign table!");
1007 }
Chris Lattner3732aca2002-08-15 16:15:25 +00001008 }
Chris Lattner650b6da2002-08-02 20:00:25 +00001009 }
Chris Lattner48a44f72002-05-02 17:06:02 +00001010
1011 // Otherwise, we cannot succeed. Specifically we do not want to allow things
1012 // like: short -> ushort -> uint, because this can create wrong results if
1013 // the input short is negative!
1014 //
1015 return false;
1016}
1017
Chris Lattnerdfae8be2003-07-24 17:35:25 +00001018static bool ValueRequiresCast(const Value *V, const Type *Ty) {
1019 if (V->getType() == Ty || isa<Constant>(V)) return false;
1020 if (const CastInst *CI = dyn_cast<CastInst>(V))
1021 if (isEliminableCastOfCast(CI->getOperand(0)->getType(), CI->getType(), Ty))
1022 return false;
1023 return true;
1024}
1025
1026/// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
1027/// InsertBefore instruction. This is specialized a bit to avoid inserting
1028/// casts that are known to not do anything...
1029///
1030Value *InstCombiner::InsertOperandCastBefore(Value *V, const Type *DestTy,
1031 Instruction *InsertBefore) {
1032 if (V->getType() == DestTy) return V;
1033 if (Constant *C = dyn_cast<Constant>(V))
1034 return ConstantExpr::getCast(C, DestTy);
1035
1036 CastInst *CI = new CastInst(V, DestTy, V->getName());
1037 InsertNewInstBefore(CI, *InsertBefore);
1038 return CI;
1039}
Chris Lattner48a44f72002-05-02 17:06:02 +00001040
1041// CastInst simplification
Chris Lattner260ab202002-04-18 17:39:14 +00001042//
Chris Lattner113f4f42002-06-25 16:13:24 +00001043Instruction *InstCombiner::visitCastInst(CastInst &CI) {
Chris Lattner55d4bda2003-06-23 21:59:52 +00001044 Value *Src = CI.getOperand(0);
1045
Chris Lattner48a44f72002-05-02 17:06:02 +00001046 // If the user is casting a value to the same type, eliminate this cast
1047 // instruction...
Chris Lattner55d4bda2003-06-23 21:59:52 +00001048 if (CI.getType() == Src->getType())
1049 return ReplaceInstUsesWith(CI, Src);
Chris Lattner48a44f72002-05-02 17:06:02 +00001050
Chris Lattner48a44f72002-05-02 17:06:02 +00001051 // If casting the result of another cast instruction, try to eliminate this
1052 // one!
1053 //
Chris Lattner55d4bda2003-06-23 21:59:52 +00001054 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) {
Chris Lattnerdfae8be2003-07-24 17:35:25 +00001055 if (isEliminableCastOfCast(CSrc->getOperand(0)->getType(),
1056 CSrc->getType(), CI.getType())) {
Chris Lattner48a44f72002-05-02 17:06:02 +00001057 // This instruction now refers directly to the cast's src operand. This
1058 // has a good chance of making CSrc dead.
Chris Lattner113f4f42002-06-25 16:13:24 +00001059 CI.setOperand(0, CSrc->getOperand(0));
1060 return &CI;
Chris Lattner48a44f72002-05-02 17:06:02 +00001061 }
1062
Chris Lattner650b6da2002-08-02 20:00:25 +00001063 // If this is an A->B->A cast, and we are dealing with integral types, try
1064 // to convert this into a logical 'and' instruction.
1065 //
1066 if (CSrc->getOperand(0)->getType() == CI.getType() &&
Chris Lattnerb0b412e2002-09-03 01:08:28 +00001067 CI.getType()->isInteger() && CSrc->getType()->isInteger() &&
Chris Lattner650b6da2002-08-02 20:00:25 +00001068 CI.getType()->isUnsigned() && CSrc->getType()->isUnsigned() &&
1069 CSrc->getType()->getPrimitiveSize() < CI.getType()->getPrimitiveSize()){
1070 assert(CSrc->getType() != Type::ULongTy &&
1071 "Cannot have type bigger than ulong!");
Chris Lattner196897c2003-05-26 23:41:32 +00001072 uint64_t AndValue = (1ULL << CSrc->getType()->getPrimitiveSize()*8)-1;
Chris Lattner650b6da2002-08-02 20:00:25 +00001073 Constant *AndOp = ConstantUInt::get(CI.getType(), AndValue);
1074 return BinaryOperator::create(Instruction::And, CSrc->getOperand(0),
1075 AndOp);
1076 }
1077 }
1078
Chris Lattnerd0d51602003-06-21 23:12:02 +00001079 // If casting the result of a getelementptr instruction with no offset, turn
1080 // this into a cast of the original pointer!
1081 //
Chris Lattner55d4bda2003-06-23 21:59:52 +00001082 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
Chris Lattnerd0d51602003-06-21 23:12:02 +00001083 bool AllZeroOperands = true;
1084 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i)
1085 if (!isa<Constant>(GEP->getOperand(i)) ||
1086 !cast<Constant>(GEP->getOperand(i))->isNullValue()) {
1087 AllZeroOperands = false;
1088 break;
1089 }
1090 if (AllZeroOperands) {
1091 CI.setOperand(0, GEP->getOperand(0));
1092 return &CI;
1093 }
1094 }
1095
Chris Lattner55d4bda2003-06-23 21:59:52 +00001096 // If this is a cast to bool (which is effectively a "!=0" test), then we can
1097 // perform a few optimizations...
1098 //
1099 if (CI.getType() == Type::BoolTy) {
1100 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Src)) {
1101 Value *Op0 = BO->getOperand(0), *Op1 = BO->getOperand(1);
1102
Chris Lattnerbdb0ce02003-07-22 21:46:59 +00001103 switch (BO->getOpcode()) {
1104 case Instruction::Sub:
1105 case Instruction::Xor:
1106 // Replace (cast ([sub|xor] A, B) to bool) with (setne A, B)
Chris Lattner55d4bda2003-06-23 21:59:52 +00001107 return new SetCondInst(Instruction::SetNE, Op0, Op1);
1108
1109 // Replace (cast (add A, B) to bool) with (setne A, -B) if B is
1110 // efficiently invertible, or if the add has just this one use.
Chris Lattnerbdb0ce02003-07-22 21:46:59 +00001111 case Instruction::Add:
Chris Lattner55d4bda2003-06-23 21:59:52 +00001112 if (Value *NegVal = dyn_castNegVal(Op1))
1113 return new SetCondInst(Instruction::SetNE, Op0, NegVal);
1114 else if (Value *NegVal = dyn_castNegVal(Op0))
1115 return new SetCondInst(Instruction::SetNE, NegVal, Op1);
1116 else if (BO->use_size() == 1) {
1117 Instruction *Neg = BinaryOperator::createNeg(Op1, BO->getName());
1118 BO->setName("");
1119 InsertNewInstBefore(Neg, CI);
1120 return new SetCondInst(Instruction::SetNE, Op0, Neg);
1121 }
Chris Lattnerbdb0ce02003-07-22 21:46:59 +00001122 break;
1123
1124 case Instruction::And:
1125 // Replace (cast (and X, (1 << size(X)-1)) to bool) with x < 0,
1126 // converting X to be a signed value as appropriate. Don't worry about
1127 // bool values, as they will be optimized other ways if they occur in
1128 // this configuration.
1129 if (ConstantInt *CInt = dyn_cast<ConstantInt>(Op1))
1130 if (isSignBit(CInt)) {
1131 // If 'X' is not signed, insert a cast now...
1132 if (!CInt->getType()->isSigned()) {
1133 const Type *DestTy;
1134 switch (CInt->getType()->getPrimitiveID()) {
1135 case Type::UByteTyID: DestTy = Type::SByteTy; break;
1136 case Type::UShortTyID: DestTy = Type::ShortTy; break;
1137 case Type::UIntTyID: DestTy = Type::IntTy; break;
1138 case Type::ULongTyID: DestTy = Type::LongTy; break;
1139 default: assert(0 && "Invalid unsigned integer type!"); abort();
1140 }
1141 CastInst *NewCI = new CastInst(Op0, DestTy,
1142 Op0->getName()+".signed");
1143 InsertNewInstBefore(NewCI, CI);
1144 Op0 = NewCI;
1145 }
1146 return new SetCondInst(Instruction::SetLT, Op0,
1147 Constant::getNullValue(Op0->getType()));
1148 }
1149 break;
1150 default: break;
1151 }
Chris Lattner55d4bda2003-06-23 21:59:52 +00001152 }
1153 }
1154
Chris Lattnerdfae8be2003-07-24 17:35:25 +00001155 // If the source value is an instruction with only this use, we can attempt to
1156 // propagate the cast into the instruction. Also, only handle integral types
1157 // for now.
1158 if (Instruction *SrcI = dyn_cast<Instruction>(Src))
1159 if (SrcI->use_size() == 1 && Src->getType()->isIntegral() &&
1160 CI.getType()->isInteger()) { // Don't mess with casts to bool here
1161 const Type *DestTy = CI.getType();
1162 unsigned SrcBitSize = getTypeSizeInBits(Src->getType());
1163 unsigned DestBitSize = getTypeSizeInBits(DestTy);
1164
1165 Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
1166 Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
1167
1168 switch (SrcI->getOpcode()) {
1169 case Instruction::Add:
1170 case Instruction::Mul:
1171 case Instruction::And:
1172 case Instruction::Or:
1173 case Instruction::Xor:
1174 // If we are discarding information, or just changing the sign, rewrite.
1175 if (DestBitSize <= SrcBitSize && DestBitSize != 1) {
1176 // Don't insert two casts if they cannot be eliminated. We allow two
1177 // casts to be inserted if the sizes are the same. This could only be
1178 // converting signedness, which is a noop.
1179 if (DestBitSize == SrcBitSize || !ValueRequiresCast(Op1, DestTy) ||
1180 !ValueRequiresCast(Op0, DestTy)) {
1181 Value *Op0c = InsertOperandCastBefore(Op0, DestTy, SrcI);
1182 Value *Op1c = InsertOperandCastBefore(Op1, DestTy, SrcI);
1183 return BinaryOperator::create(cast<BinaryOperator>(SrcI)
1184 ->getOpcode(), Op0c, Op1c);
1185 }
1186 }
1187 break;
1188 case Instruction::Shl:
1189 // Allow changing the sign of the source operand. Do not allow changing
1190 // the size of the shift, UNLESS the shift amount is a constant. We
1191 // mush not change variable sized shifts to a smaller size, because it
1192 // is undefined to shift more bits out than exist in the value.
1193 if (DestBitSize == SrcBitSize ||
1194 (DestBitSize < SrcBitSize && isa<Constant>(Op1))) {
1195 Value *Op0c = InsertOperandCastBefore(Op0, DestTy, SrcI);
1196 return new ShiftInst(Instruction::Shl, Op0c, Op1);
1197 }
1198 break;
1199 }
1200 }
1201
Chris Lattner260ab202002-04-18 17:39:14 +00001202 return 0;
Chris Lattnerca081252001-12-14 16:52:21 +00001203}
1204
Chris Lattner970c33a2003-06-19 17:00:31 +00001205// CallInst simplification
1206//
1207Instruction *InstCombiner::visitCallInst(CallInst &CI) {
1208 if (transformConstExprCastCall(&CI)) return 0;
1209 return 0;
1210}
1211
1212// InvokeInst simplification
1213//
1214Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
1215 if (transformConstExprCastCall(&II)) return 0;
1216 return 0;
1217}
1218
1219// getPromotedType - Return the specified type promoted as it would be to pass
1220// though a va_arg area...
1221static const Type *getPromotedType(const Type *Ty) {
1222 switch (Ty->getPrimitiveID()) {
1223 case Type::SByteTyID:
1224 case Type::ShortTyID: return Type::IntTy;
1225 case Type::UByteTyID:
1226 case Type::UShortTyID: return Type::UIntTy;
1227 case Type::FloatTyID: return Type::DoubleTy;
1228 default: return Ty;
1229 }
1230}
1231
1232// transformConstExprCastCall - If the callee is a constexpr cast of a function,
1233// attempt to move the cast to the arguments of the call/invoke.
1234//
1235bool InstCombiner::transformConstExprCastCall(CallSite CS) {
1236 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
1237 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
1238 if (CE->getOpcode() != Instruction::Cast ||
1239 !isa<ConstantPointerRef>(CE->getOperand(0)))
1240 return false;
1241 ConstantPointerRef *CPR = cast<ConstantPointerRef>(CE->getOperand(0));
1242 if (!isa<Function>(CPR->getValue())) return false;
1243 Function *Callee = cast<Function>(CPR->getValue());
1244 Instruction *Caller = CS.getInstruction();
1245
1246 // Okay, this is a cast from a function to a different type. Unless doing so
1247 // would cause a type conversion of one of our arguments, change this call to
1248 // be a direct call with arguments casted to the appropriate types.
1249 //
1250 const FunctionType *FT = Callee->getFunctionType();
1251 const Type *OldRetTy = Caller->getType();
1252
1253 if (Callee->isExternal() &&
1254 !OldRetTy->isLosslesslyConvertibleTo(FT->getReturnType()))
1255 return false; // Cannot transform this return value...
1256
1257 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
1258 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
1259
1260 CallSite::arg_iterator AI = CS.arg_begin();
1261 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
1262 const Type *ParamTy = FT->getParamType(i);
1263 bool isConvertible = (*AI)->getType()->isLosslesslyConvertibleTo(ParamTy);
1264 if (Callee->isExternal() && !isConvertible) return false;
1265 }
1266
1267 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
1268 Callee->isExternal())
1269 return false; // Do not delete arguments unless we have a function body...
1270
1271 // Okay, we decided that this is a safe thing to do: go ahead and start
1272 // inserting cast instructions as necessary...
1273 std::vector<Value*> Args;
1274 Args.reserve(NumActualArgs);
1275
1276 AI = CS.arg_begin();
1277 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
1278 const Type *ParamTy = FT->getParamType(i);
1279 if ((*AI)->getType() == ParamTy) {
1280 Args.push_back(*AI);
1281 } else {
1282 Instruction *Cast = new CastInst(*AI, ParamTy, "tmp");
1283 InsertNewInstBefore(Cast, *Caller);
1284 Args.push_back(Cast);
1285 }
1286 }
1287
1288 // If the function takes more arguments than the call was taking, add them
1289 // now...
1290 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
1291 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
1292
1293 // If we are removing arguments to the function, emit an obnoxious warning...
1294 if (FT->getNumParams() < NumActualArgs)
1295 if (!FT->isVarArg()) {
1296 std::cerr << "WARNING: While resolving call to function '"
1297 << Callee->getName() << "' arguments were dropped!\n";
1298 } else {
1299 // Add all of the arguments in their promoted form to the arg list...
1300 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
1301 const Type *PTy = getPromotedType((*AI)->getType());
1302 if (PTy != (*AI)->getType()) {
1303 // Must promote to pass through va_arg area!
1304 Instruction *Cast = new CastInst(*AI, PTy, "tmp");
1305 InsertNewInstBefore(Cast, *Caller);
1306 Args.push_back(Cast);
1307 } else {
1308 Args.push_back(*AI);
1309 }
1310 }
1311 }
1312
1313 if (FT->getReturnType() == Type::VoidTy)
1314 Caller->setName(""); // Void type should not have a name...
1315
1316 Instruction *NC;
1317 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
1318 NC = new InvokeInst(Callee, II->getNormalDest(), II->getExceptionalDest(),
1319 Args, Caller->getName(), Caller);
1320 } else {
1321 NC = new CallInst(Callee, Args, Caller->getName(), Caller);
1322 }
1323
1324 // Insert a cast of the return type as necessary...
1325 Value *NV = NC;
1326 if (Caller->getType() != NV->getType() && !Caller->use_empty()) {
1327 if (NV->getType() != Type::VoidTy) {
1328 NV = NC = new CastInst(NC, Caller->getType(), "tmp");
1329 InsertNewInstBefore(NC, *Caller);
1330 AddUsesToWorkList(*Caller);
1331 } else {
1332 NV = Constant::getNullValue(Caller->getType());
1333 }
1334 }
1335
1336 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
1337 Caller->replaceAllUsesWith(NV);
1338 Caller->getParent()->getInstList().erase(Caller);
1339 removeFromWorkList(Caller);
1340 return true;
1341}
1342
1343
Chris Lattner48a44f72002-05-02 17:06:02 +00001344
Chris Lattnerbbbdd852002-05-06 18:06:38 +00001345// PHINode simplification
1346//
Chris Lattner113f4f42002-06-25 16:13:24 +00001347Instruction *InstCombiner::visitPHINode(PHINode &PN) {
Chris Lattnerbbbdd852002-05-06 18:06:38 +00001348 // If the PHI node only has one incoming value, eliminate the PHI node...
Chris Lattnere6794492002-08-12 21:17:25 +00001349 if (PN.getNumIncomingValues() == 1)
1350 return ReplaceInstUsesWith(PN, PN.getIncomingValue(0));
Chris Lattner9cd1e662002-08-20 15:35:35 +00001351
1352 // Otherwise if all of the incoming values are the same for the PHI, replace
1353 // the PHI node with the incoming value.
1354 //
Chris Lattnerf6c0efa2002-08-22 20:22:01 +00001355 Value *InVal = 0;
1356 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
1357 if (PN.getIncomingValue(i) != &PN) // Not the PHI node itself...
1358 if (InVal && PN.getIncomingValue(i) != InVal)
1359 return 0; // Not the same, bail out.
1360 else
1361 InVal = PN.getIncomingValue(i);
1362
1363 // The only case that could cause InVal to be null is if we have a PHI node
1364 // that only has entries for itself. In this case, there is no entry into the
1365 // loop, so kill the PHI.
1366 //
1367 if (InVal == 0) InVal = Constant::getNullValue(PN.getType());
Chris Lattnerbbbdd852002-05-06 18:06:38 +00001368
Chris Lattner9cd1e662002-08-20 15:35:35 +00001369 // All of the incoming values are the same, replace the PHI node now.
1370 return ReplaceInstUsesWith(PN, InVal);
Chris Lattnerbbbdd852002-05-06 18:06:38 +00001371}
1372
Chris Lattner48a44f72002-05-02 17:06:02 +00001373
Chris Lattner113f4f42002-06-25 16:13:24 +00001374Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
Chris Lattner471bd762003-05-22 19:07:21 +00001375 // Is it 'getelementptr %P, long 0' or 'getelementptr %P'
Chris Lattner113f4f42002-06-25 16:13:24 +00001376 // If so, eliminate the noop.
Chris Lattnerae7a0d32002-08-02 19:29:35 +00001377 if ((GEP.getNumOperands() == 2 &&
Chris Lattner136dab72002-09-11 01:21:33 +00001378 GEP.getOperand(1) == Constant::getNullValue(Type::LongTy)) ||
Chris Lattnere6794492002-08-12 21:17:25 +00001379 GEP.getNumOperands() == 1)
1380 return ReplaceInstUsesWith(GEP, GEP.getOperand(0));
Chris Lattner48a44f72002-05-02 17:06:02 +00001381
Chris Lattnerae7a0d32002-08-02 19:29:35 +00001382 // Combine Indices - If the source pointer to this getelementptr instruction
1383 // is a getelementptr instruction, combine the indices of the two
1384 // getelementptr instructions into a single instruction.
1385 //
Chris Lattnerc59af1d2002-08-17 22:21:59 +00001386 if (GetElementPtrInst *Src = dyn_cast<GetElementPtrInst>(GEP.getOperand(0))) {
Chris Lattnerae7a0d32002-08-02 19:29:35 +00001387 std::vector<Value *> Indices;
Chris Lattnerca081252001-12-14 16:52:21 +00001388
Chris Lattnerae7a0d32002-08-02 19:29:35 +00001389 // Can we combine the two pointer arithmetics offsets?
Chris Lattner471bd762003-05-22 19:07:21 +00001390 if (Src->getNumOperands() == 2 && isa<Constant>(Src->getOperand(1)) &&
1391 isa<Constant>(GEP.getOperand(1))) {
Chris Lattner235af562003-03-05 22:33:14 +00001392 // Replace: gep (gep %P, long C1), long C2, ...
1393 // With: gep %P, long (C1+C2), ...
Chris Lattner34428442003-05-27 16:40:51 +00001394 Value *Sum = ConstantExpr::get(Instruction::Add,
1395 cast<Constant>(Src->getOperand(1)),
1396 cast<Constant>(GEP.getOperand(1)));
Chris Lattner235af562003-03-05 22:33:14 +00001397 assert(Sum && "Constant folding of longs failed!?");
1398 GEP.setOperand(0, Src->getOperand(0));
1399 GEP.setOperand(1, Sum);
1400 AddUsesToWorkList(*Src); // Reduce use count of Src
1401 return &GEP;
Chris Lattner471bd762003-05-22 19:07:21 +00001402 } else if (Src->getNumOperands() == 2) {
Chris Lattner235af562003-03-05 22:33:14 +00001403 // Replace: gep (gep %P, long B), long A, ...
1404 // With: T = long A+B; gep %P, T, ...
1405 //
1406 Value *Sum = BinaryOperator::create(Instruction::Add, Src->getOperand(1),
1407 GEP.getOperand(1),
1408 Src->getName()+".sum", &GEP);
1409 GEP.setOperand(0, Src->getOperand(0));
1410 GEP.setOperand(1, Sum);
1411 WorkList.push_back(cast<Instruction>(Sum));
1412 return &GEP;
Chris Lattner5d606a02002-11-04 16:43:32 +00001413 } else if (*GEP.idx_begin() == Constant::getNullValue(Type::LongTy) &&
Chris Lattnera8339e32002-09-17 21:05:42 +00001414 Src->getNumOperands() != 1) {
Chris Lattnerae7a0d32002-08-02 19:29:35 +00001415 // Otherwise we can do the fold if the first index of the GEP is a zero
1416 Indices.insert(Indices.end(), Src->idx_begin(), Src->idx_end());
1417 Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
Chris Lattner5d606a02002-11-04 16:43:32 +00001418 } else if (Src->getOperand(Src->getNumOperands()-1) ==
1419 Constant::getNullValue(Type::LongTy)) {
1420 // If the src gep ends with a constant array index, merge this get into
1421 // it, even if we have a non-zero array index.
1422 Indices.insert(Indices.end(), Src->idx_begin(), Src->idx_end()-1);
1423 Indices.insert(Indices.end(), GEP.idx_begin(), GEP.idx_end());
Chris Lattnerae7a0d32002-08-02 19:29:35 +00001424 }
1425
1426 if (!Indices.empty())
1427 return new GetElementPtrInst(Src->getOperand(0), Indices, GEP.getName());
Chris Lattnerc59af1d2002-08-17 22:21:59 +00001428
1429 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(GEP.getOperand(0))) {
1430 // GEP of global variable. If all of the indices for this GEP are
1431 // constants, we can promote this to a constexpr instead of an instruction.
1432
1433 // Scan for nonconstants...
1434 std::vector<Constant*> Indices;
1435 User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
1436 for (; I != E && isa<Constant>(*I); ++I)
1437 Indices.push_back(cast<Constant>(*I));
1438
1439 if (I == E) { // If they are all constants...
Chris Lattner46b3d302003-04-16 22:40:51 +00001440 Constant *CE =
Chris Lattnerc59af1d2002-08-17 22:21:59 +00001441 ConstantExpr::getGetElementPtr(ConstantPointerRef::get(GV), Indices);
1442
1443 // Replace all uses of the GEP with the new constexpr...
1444 return ReplaceInstUsesWith(GEP, CE);
1445 }
Chris Lattnerca081252001-12-14 16:52:21 +00001446 }
1447
Chris Lattnerca081252001-12-14 16:52:21 +00001448 return 0;
1449}
1450
Chris Lattner1085bdf2002-11-04 16:18:53 +00001451Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
1452 // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
1453 if (AI.isArrayAllocation()) // Check C != 1
1454 if (const ConstantUInt *C = dyn_cast<ConstantUInt>(AI.getArraySize())) {
1455 const Type *NewTy = ArrayType::get(AI.getAllocatedType(), C->getValue());
Chris Lattnera2620ac2002-11-09 00:49:43 +00001456 AllocationInst *New = 0;
Chris Lattner1085bdf2002-11-04 16:18:53 +00001457
1458 // Create and insert the replacement instruction...
1459 if (isa<MallocInst>(AI))
1460 New = new MallocInst(NewTy, 0, AI.getName(), &AI);
Chris Lattnera2620ac2002-11-09 00:49:43 +00001461 else {
1462 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
Chris Lattner1085bdf2002-11-04 16:18:53 +00001463 New = new AllocaInst(NewTy, 0, AI.getName(), &AI);
Chris Lattnera2620ac2002-11-09 00:49:43 +00001464 }
Chris Lattner1085bdf2002-11-04 16:18:53 +00001465
1466 // Scan to the end of the allocation instructions, to skip over a block of
1467 // allocas if possible...
1468 //
1469 BasicBlock::iterator It = New;
1470 while (isa<AllocationInst>(*It)) ++It;
1471
1472 // Now that I is pointing to the first non-allocation-inst in the block,
1473 // insert our getelementptr instruction...
1474 //
1475 std::vector<Value*> Idx(2, Constant::getNullValue(Type::LongTy));
1476 Value *V = new GetElementPtrInst(New, Idx, New->getName()+".sub", It);
1477
1478 // Now make everything use the getelementptr instead of the original
1479 // allocation.
1480 ReplaceInstUsesWith(AI, V);
1481 return &AI;
1482 }
1483 return 0;
1484}
1485
Chris Lattner0f1d8a32003-06-26 05:06:25 +00001486/// GetGEPGlobalInitializer - Given a constant, and a getelementptr
1487/// constantexpr, return the constant value being addressed by the constant
1488/// expression, or null if something is funny.
1489///
1490static Constant *GetGEPGlobalInitializer(Constant *C, ConstantExpr *CE) {
1491 if (CE->getOperand(1) != Constant::getNullValue(Type::LongTy))
1492 return 0; // Do not allow stepping over the value!
1493
1494 // Loop over all of the operands, tracking down which value we are
1495 // addressing...
1496 for (unsigned i = 2, e = CE->getNumOperands(); i != e; ++i)
1497 if (ConstantUInt *CU = dyn_cast<ConstantUInt>(CE->getOperand(i))) {
1498 ConstantStruct *CS = cast<ConstantStruct>(C);
1499 if (CU->getValue() >= CS->getValues().size()) return 0;
1500 C = cast<Constant>(CS->getValues()[CU->getValue()]);
1501 } else if (ConstantSInt *CS = dyn_cast<ConstantSInt>(CE->getOperand(i))) {
1502 ConstantArray *CA = cast<ConstantArray>(C);
1503 if ((uint64_t)CS->getValue() >= CA->getValues().size()) return 0;
1504 C = cast<Constant>(CA->getValues()[CS->getValue()]);
1505 } else
1506 return 0;
1507 return C;
1508}
1509
1510Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
1511 Value *Op = LI.getOperand(0);
1512 if (ConstantPointerRef *CPR = dyn_cast<ConstantPointerRef>(Op))
1513 Op = CPR->getValue();
1514
1515 // Instcombine load (constant global) into the value loaded...
1516 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
Chris Lattnerbdb0ce02003-07-22 21:46:59 +00001517 if (GV->isConstant() && !GV->isExternal())
Chris Lattner0f1d8a32003-06-26 05:06:25 +00001518 return ReplaceInstUsesWith(LI, GV->getInitializer());
1519
1520 // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded...
1521 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op))
1522 if (CE->getOpcode() == Instruction::GetElementPtr)
1523 if (ConstantPointerRef *G=dyn_cast<ConstantPointerRef>(CE->getOperand(0)))
1524 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(G->getValue()))
Chris Lattnerbdb0ce02003-07-22 21:46:59 +00001525 if (GV->isConstant() && !GV->isExternal())
Chris Lattner0f1d8a32003-06-26 05:06:25 +00001526 if (Constant *V = GetGEPGlobalInitializer(GV->getInitializer(), CE))
1527 return ReplaceInstUsesWith(LI, V);
1528 return 0;
1529}
1530
1531
Chris Lattner9eef8a72003-06-04 04:46:00 +00001532Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
1533 // Change br (not X), label True, label False to: br X, label False, True
Chris Lattner45789ac2003-06-05 20:12:51 +00001534 if (BI.isConditional() && !isa<Constant>(BI.getCondition()))
Chris Lattnere967b342003-06-04 05:10:11 +00001535 if (Value *V = dyn_castNotVal(BI.getCondition())) {
1536 BasicBlock *TrueDest = BI.getSuccessor(0);
1537 BasicBlock *FalseDest = BI.getSuccessor(1);
1538 // Swap Destinations and condition...
1539 BI.setCondition(V);
1540 BI.setSuccessor(0, FalseDest);
1541 BI.setSuccessor(1, TrueDest);
1542 return &BI;
1543 }
Chris Lattner9eef8a72003-06-04 04:46:00 +00001544 return 0;
1545}
Chris Lattner1085bdf2002-11-04 16:18:53 +00001546
Chris Lattnerca081252001-12-14 16:52:21 +00001547
Chris Lattner99f48c62002-09-02 04:59:56 +00001548void InstCombiner::removeFromWorkList(Instruction *I) {
1549 WorkList.erase(std::remove(WorkList.begin(), WorkList.end(), I),
1550 WorkList.end());
1551}
1552
Chris Lattner113f4f42002-06-25 16:13:24 +00001553bool InstCombiner::runOnFunction(Function &F) {
Chris Lattner260ab202002-04-18 17:39:14 +00001554 bool Changed = false;
Chris Lattnerca081252001-12-14 16:52:21 +00001555
Chris Lattner260ab202002-04-18 17:39:14 +00001556 WorkList.insert(WorkList.end(), inst_begin(F), inst_end(F));
Chris Lattnerca081252001-12-14 16:52:21 +00001557
1558 while (!WorkList.empty()) {
1559 Instruction *I = WorkList.back(); // Get an instruction from the worklist
1560 WorkList.pop_back();
1561
Misha Brukman632df282002-10-29 23:06:16 +00001562 // Check to see if we can DCE or ConstantPropagate the instruction...
Chris Lattner99f48c62002-09-02 04:59:56 +00001563 // Check to see if we can DIE the instruction...
1564 if (isInstructionTriviallyDead(I)) {
1565 // Add operands to the worklist...
1566 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
1567 if (Instruction *Op = dyn_cast<Instruction>(I->getOperand(i)))
1568 WorkList.push_back(Op);
1569
1570 ++NumDeadInst;
1571 BasicBlock::iterator BBI = I;
1572 if (dceInstruction(BBI)) {
1573 removeFromWorkList(I);
1574 continue;
1575 }
1576 }
1577
Misha Brukman632df282002-10-29 23:06:16 +00001578 // Instruction isn't dead, see if we can constant propagate it...
Chris Lattner99f48c62002-09-02 04:59:56 +00001579 if (Constant *C = ConstantFoldInstruction(I)) {
1580 // Add operands to the worklist...
1581 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
1582 if (Instruction *Op = dyn_cast<Instruction>(I->getOperand(i)))
1583 WorkList.push_back(Op);
Chris Lattnerc6509f42002-12-05 22:41:53 +00001584 ReplaceInstUsesWith(*I, C);
1585
Chris Lattner99f48c62002-09-02 04:59:56 +00001586 ++NumConstProp;
1587 BasicBlock::iterator BBI = I;
1588 if (dceInstruction(BBI)) {
1589 removeFromWorkList(I);
1590 continue;
1591 }
1592 }
1593
Chris Lattnerca081252001-12-14 16:52:21 +00001594 // Now that we have an instruction, try combining it to simplify it...
Chris Lattnerae7a0d32002-08-02 19:29:35 +00001595 if (Instruction *Result = visit(*I)) {
Chris Lattner0b18c1d2002-05-10 15:38:35 +00001596 ++NumCombined;
Chris Lattner260ab202002-04-18 17:39:14 +00001597 // Should we replace the old instruction with a new one?
Chris Lattner053c0932002-05-14 15:24:07 +00001598 if (Result != I) {
1599 // Instructions can end up on the worklist more than once. Make sure
1600 // we do not process an instruction that has been deleted.
Chris Lattner99f48c62002-09-02 04:59:56 +00001601 removeFromWorkList(I);
Chris Lattner260ab202002-04-18 17:39:14 +00001602 ReplaceInstWithInst(I, Result);
Chris Lattner113f4f42002-06-25 16:13:24 +00001603 } else {
Chris Lattnerae7a0d32002-08-02 19:29:35 +00001604 BasicBlock::iterator II = I;
1605
1606 // If the instruction was modified, it's possible that it is now dead.
1607 // if so, remove it.
1608 if (dceInstruction(II)) {
1609 // Instructions may end up in the worklist more than once. Erase them
1610 // all.
Chris Lattner99f48c62002-09-02 04:59:56 +00001611 removeFromWorkList(I);
Chris Lattnerae7a0d32002-08-02 19:29:35 +00001612 Result = 0;
1613 }
Chris Lattner053c0932002-05-14 15:24:07 +00001614 }
Chris Lattner260ab202002-04-18 17:39:14 +00001615
Chris Lattnerae7a0d32002-08-02 19:29:35 +00001616 if (Result) {
1617 WorkList.push_back(Result);
1618 AddUsesToWorkList(*Result);
1619 }
Chris Lattner260ab202002-04-18 17:39:14 +00001620 Changed = true;
Chris Lattnerca081252001-12-14 16:52:21 +00001621 }
1622 }
1623
Chris Lattner260ab202002-04-18 17:39:14 +00001624 return Changed;
Chris Lattner04805fa2002-02-26 21:46:54 +00001625}
1626
1627Pass *createInstructionCombiningPass() {
Chris Lattner260ab202002-04-18 17:39:14 +00001628 return new InstCombiner();
Chris Lattner04805fa2002-02-26 21:46:54 +00001629}