blob: b31ec635c85a8ea1bc846992d56ed12aa653af05 [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 Lattner216c7b82003-09-10 05:29:43 +000015// This pass guarantees that the following canonicalizations are performed on
Chris Lattnerbfb1d032003-07-23 21:41:57 +000016// 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:
Chris Lattneraec3d942003-10-07 22:32:43 +0000102 Instruction *visitCallSite(CallSite CS);
Chris Lattner970c33a2003-06-19 17:00:31 +0000103 bool transformConstExprCastCall(CallSite CS);
104
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000105 // InsertNewInstBefore - insert an instruction New before instruction Old
106 // in the program. Add the new instruction to the worklist.
107 //
108 void InsertNewInstBefore(Instruction *New, Instruction &Old) {
Chris Lattner65217ff2002-08-23 18:32:43 +0000109 assert(New && New->getParent() == 0 &&
110 "New instruction already inserted into a basic block!");
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000111 BasicBlock *BB = Old.getParent();
112 BB->getInstList().insert(&Old, New); // Insert inst
113 WorkList.push_back(New); // Add to worklist
114 }
115
Chris Lattner3ac7c262003-08-13 20:16:26 +0000116 public:
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000117 // ReplaceInstUsesWith - This method is to be used when an instruction is
118 // found to be dead, replacable with another preexisting expression. Here
119 // we add all uses of I to the worklist, replace all uses of I with the new
120 // value, then return I, so that the inst combiner will know that I was
121 // modified.
122 //
123 Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
124 AddUsesToWorkList(I); // Add all modified instrs to worklist
125 I.replaceAllUsesWith(V);
126 return &I;
127 }
Chris Lattner3ac7c262003-08-13 20:16:26 +0000128 private:
Chris Lattnerdfae8be2003-07-24 17:35:25 +0000129 /// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
130 /// InsertBefore instruction. This is specialized a bit to avoid inserting
131 /// casts that are known to not do anything...
132 ///
133 Value *InsertOperandCastBefore(Value *V, const Type *DestTy,
134 Instruction *InsertBefore);
135
Chris Lattner7fb29e12003-03-11 00:12:48 +0000136 // SimplifyCommutative - This performs a few simplifications for commutative
137 // operators...
138 bool SimplifyCommutative(BinaryOperator &I);
Chris Lattnerba1cb382003-09-19 17:17:26 +0000139
140 Instruction *OptAndOp(Instruction *Op, ConstantIntegral *OpRHS,
141 ConstantIntegral *AndRHS, BinaryOperator &TheAnd);
Chris Lattner260ab202002-04-18 17:39:14 +0000142 };
Chris Lattnerb28b6802002-07-23 18:06:35 +0000143
Chris Lattnerc8b70922002-07-26 21:12:46 +0000144 RegisterOpt<InstCombiner> X("instcombine", "Combine redundant instructions");
Chris Lattner260ab202002-04-18 17:39:14 +0000145}
146
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000147// getComplexity: Assign a complexity or rank value to LLVM Values...
148// 0 -> Constant, 1 -> Other, 2 -> Argument, 2 -> Unary, 3 -> OtherInst
149static unsigned getComplexity(Value *V) {
150 if (isa<Instruction>(V)) {
151 if (BinaryOperator::isNeg(V) || BinaryOperator::isNot(V))
152 return 2;
153 return 3;
154 }
155 if (isa<Argument>(V)) return 2;
156 return isa<Constant>(V) ? 0 : 1;
157}
Chris Lattner260ab202002-04-18 17:39:14 +0000158
Chris Lattner7fb29e12003-03-11 00:12:48 +0000159// isOnlyUse - Return true if this instruction will be deleted if we stop using
160// it.
161static bool isOnlyUse(Value *V) {
162 return V->use_size() == 1 || isa<Constant>(V);
163}
164
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000165// SimplifyCommutative - This performs a few simplifications for commutative
166// operators:
Chris Lattner260ab202002-04-18 17:39:14 +0000167//
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000168// 1. Order operands such that they are listed from right (least complex) to
169// left (most complex). This puts constants before unary operators before
170// binary operators.
171//
Chris Lattner7fb29e12003-03-11 00:12:48 +0000172// 2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
173// 3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000174//
Chris Lattner7fb29e12003-03-11 00:12:48 +0000175bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000176 bool Changed = false;
177 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
178 Changed = !I.swapOperands();
179
180 if (!I.isAssociative()) return Changed;
181 Instruction::BinaryOps Opcode = I.getOpcode();
Chris Lattner7fb29e12003-03-11 00:12:48 +0000182 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
183 if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
184 if (isa<Constant>(I.getOperand(1))) {
Chris Lattner34428442003-05-27 16:40:51 +0000185 Constant *Folded = ConstantExpr::get(I.getOpcode(),
186 cast<Constant>(I.getOperand(1)),
187 cast<Constant>(Op->getOperand(1)));
Chris Lattner7fb29e12003-03-11 00:12:48 +0000188 I.setOperand(0, Op->getOperand(0));
189 I.setOperand(1, Folded);
190 return true;
191 } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
192 if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
193 isOnlyUse(Op) && isOnlyUse(Op1)) {
194 Constant *C1 = cast<Constant>(Op->getOperand(1));
195 Constant *C2 = cast<Constant>(Op1->getOperand(1));
196
197 // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattner34428442003-05-27 16:40:51 +0000198 Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
Chris Lattner7fb29e12003-03-11 00:12:48 +0000199 Instruction *New = BinaryOperator::create(Opcode, Op->getOperand(0),
200 Op1->getOperand(0),
201 Op1->getName(), &I);
202 WorkList.push_back(New);
203 I.setOperand(0, New);
204 I.setOperand(1, Folded);
205 return true;
206 }
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000207 }
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000208 return Changed;
Chris Lattner260ab202002-04-18 17:39:14 +0000209}
Chris Lattnerca081252001-12-14 16:52:21 +0000210
Chris Lattnerbb74e222003-03-10 23:06:50 +0000211// dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
212// if the LHS is a constant zero (which is the 'negate' form).
Chris Lattner9fa53de2002-05-06 16:49:18 +0000213//
Chris Lattnerbb74e222003-03-10 23:06:50 +0000214static inline Value *dyn_castNegVal(Value *V) {
215 if (BinaryOperator::isNeg(V))
216 return BinaryOperator::getNegArgument(cast<BinaryOperator>(V));
217
Chris Lattner9244df62003-04-30 22:19:10 +0000218 // Constants can be considered to be negated values if they can be folded...
219 if (Constant *C = dyn_cast<Constant>(V))
Chris Lattner34428442003-05-27 16:40:51 +0000220 return ConstantExpr::get(Instruction::Sub,
221 Constant::getNullValue(V->getType()), C);
Chris Lattnerbb74e222003-03-10 23:06:50 +0000222 return 0;
Chris Lattner9fa53de2002-05-06 16:49:18 +0000223}
224
Chris Lattnerbb74e222003-03-10 23:06:50 +0000225static inline Value *dyn_castNotVal(Value *V) {
226 if (BinaryOperator::isNot(V))
227 return BinaryOperator::getNotArgument(cast<BinaryOperator>(V));
228
229 // Constants can be considered to be not'ed values...
Chris Lattnerdd65d862003-04-30 22:34:06 +0000230 if (ConstantIntegral *C = dyn_cast<ConstantIntegral>(V))
Chris Lattner34428442003-05-27 16:40:51 +0000231 return ConstantExpr::get(Instruction::Xor,
232 ConstantIntegral::getAllOnesValue(C->getType()),C);
Chris Lattnerbb74e222003-03-10 23:06:50 +0000233 return 0;
234}
235
Chris Lattner7fb29e12003-03-11 00:12:48 +0000236// dyn_castFoldableMul - If this value is a multiply that can be folded into
237// other computations (because it has a constant operand), return the
238// non-constant operand of the multiply.
239//
240static inline Value *dyn_castFoldableMul(Value *V) {
241 if (V->use_size() == 1 && V->getType()->isInteger())
242 if (Instruction *I = dyn_cast<Instruction>(V))
243 if (I->getOpcode() == Instruction::Mul)
244 if (isa<Constant>(I->getOperand(1)))
245 return I->getOperand(0);
246 return 0;
Chris Lattner3082c5a2003-02-18 19:28:33 +0000247}
Chris Lattner31ae8632002-08-14 17:51:49 +0000248
Chris Lattner7fb29e12003-03-11 00:12:48 +0000249// dyn_castMaskingAnd - If this value is an And instruction masking a value with
250// a constant, return the constant being anded with.
251//
Chris Lattner01d56392003-08-12 19:17:27 +0000252template<class ValueType>
253static inline Constant *dyn_castMaskingAnd(ValueType *V) {
Chris Lattner7fb29e12003-03-11 00:12:48 +0000254 if (Instruction *I = dyn_cast<Instruction>(V))
255 if (I->getOpcode() == Instruction::And)
256 return dyn_cast<Constant>(I->getOperand(1));
257
258 // If this is a constant, it acts just like we were masking with it.
259 return dyn_cast<Constant>(V);
260}
Chris Lattner3082c5a2003-02-18 19:28:33 +0000261
262// Log2 - Calculate the log base 2 for the specified value if it is exactly a
263// power of 2.
264static unsigned Log2(uint64_t Val) {
265 assert(Val > 1 && "Values 0 and 1 should be handled elsewhere!");
266 unsigned Count = 0;
267 while (Val != 1) {
268 if (Val & 1) return 0; // Multiple bits set?
269 Val >>= 1;
270 ++Count;
271 }
272 return Count;
Chris Lattner31ae8632002-08-14 17:51:49 +0000273}
274
Chris Lattnerb8b97502003-08-13 19:01:45 +0000275
276/// AssociativeOpt - Perform an optimization on an associative operator. This
277/// function is designed to check a chain of associative operators for a
278/// potential to apply a certain optimization. Since the optimization may be
279/// applicable if the expression was reassociated, this checks the chain, then
280/// reassociates the expression as necessary to expose the optimization
281/// opportunity. This makes use of a special Functor, which must define
282/// 'shouldApply' and 'apply' methods.
283///
284template<typename Functor>
285Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
286 unsigned Opcode = Root.getOpcode();
287 Value *LHS = Root.getOperand(0);
288
289 // Quick check, see if the immediate LHS matches...
290 if (F.shouldApply(LHS))
291 return F.apply(Root);
292
293 // Otherwise, if the LHS is not of the same opcode as the root, return.
294 Instruction *LHSI = dyn_cast<Instruction>(LHS);
295 while (LHSI && LHSI->getOpcode() == Opcode && LHSI->use_size() == 1) {
296 // Should we apply this transform to the RHS?
297 bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
298
299 // If not to the RHS, check to see if we should apply to the LHS...
300 if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
301 cast<BinaryOperator>(LHSI)->swapOperands(); // Make the LHS the RHS
302 ShouldApply = true;
303 }
304
305 // If the functor wants to apply the optimization to the RHS of LHSI,
306 // reassociate the expression from ((? op A) op B) to (? op (A op B))
307 if (ShouldApply) {
308 BasicBlock *BB = Root.getParent();
309 // All of the instructions have a single use and have no side-effects,
310 // because of this, we can pull them all into the current basic block.
311 if (LHSI->getParent() != BB) {
312 // Move all of the instructions from root to LHSI into the current
313 // block.
314 Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
315 Instruction *LastUse = &Root;
316 while (TmpLHSI->getParent() == BB) {
317 LastUse = TmpLHSI;
318 TmpLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
319 }
320
321 // Loop over all of the instructions in other blocks, moving them into
322 // the current one.
323 Value *TmpLHS = TmpLHSI;
324 do {
325 TmpLHSI = cast<Instruction>(TmpLHS);
326 // Remove from current block...
327 TmpLHSI->getParent()->getInstList().remove(TmpLHSI);
328 // Insert before the last instruction...
329 BB->getInstList().insert(LastUse, TmpLHSI);
330 TmpLHS = TmpLHSI->getOperand(0);
331 } while (TmpLHSI != LHSI);
332 }
333
334 // Now all of the instructions are in the current basic block, go ahead
335 // and perform the reassociation.
336 Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
337
338 // First move the selected RHS to the LHS of the root...
339 Root.setOperand(0, LHSI->getOperand(1));
340
341 // Make what used to be the LHS of the root be the user of the root...
342 Value *ExtraOperand = TmpLHSI->getOperand(1);
343 Root.replaceAllUsesWith(TmpLHSI); // Users now use TmpLHSI
344 TmpLHSI->setOperand(1, &Root); // TmpLHSI now uses the root
345 BB->getInstList().remove(&Root); // Remove root from the BB
346 BB->getInstList().insert(TmpLHSI, &Root); // Insert root before TmpLHSI
347
348 // Now propagate the ExtraOperand down the chain of instructions until we
349 // get to LHSI.
350 while (TmpLHSI != LHSI) {
351 Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
352 Value *NextOp = NextLHSI->getOperand(1);
353 NextLHSI->setOperand(1, ExtraOperand);
354 TmpLHSI = NextLHSI;
355 ExtraOperand = NextOp;
356 }
357
358 // Now that the instructions are reassociated, have the functor perform
359 // the transformation...
360 return F.apply(Root);
361 }
362
363 LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
364 }
365 return 0;
366}
367
368
369// AddRHS - Implements: X + X --> X << 1
370struct AddRHS {
371 Value *RHS;
372 AddRHS(Value *rhs) : RHS(rhs) {}
373 bool shouldApply(Value *LHS) const { return LHS == RHS; }
374 Instruction *apply(BinaryOperator &Add) const {
375 return new ShiftInst(Instruction::Shl, Add.getOperand(0),
376 ConstantInt::get(Type::UByteTy, 1));
377 }
378};
379
380// AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
381// iff C1&C2 == 0
382struct AddMaskingAnd {
383 Constant *C2;
384 AddMaskingAnd(Constant *c) : C2(c) {}
385 bool shouldApply(Value *LHS) const {
386 if (Constant *C1 = dyn_castMaskingAnd(LHS))
387 return ConstantExpr::get(Instruction::And, C1, C2)->isNullValue();
388 return false;
389 }
390 Instruction *apply(BinaryOperator &Add) const {
391 return BinaryOperator::create(Instruction::Or, Add.getOperand(0),
392 Add.getOperand(1));
393 }
394};
395
396
397
Chris Lattner113f4f42002-06-25 16:13:24 +0000398Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000399 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +0000400 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
Chris Lattner9fa53de2002-05-06 16:49:18 +0000401
Chris Lattnerb8b97502003-08-13 19:01:45 +0000402 // X + 0 --> X
Chris Lattnere6794492002-08-12 21:17:25 +0000403 if (RHS == Constant::getNullValue(I.getType()))
404 return ReplaceInstUsesWith(I, LHS);
Chris Lattner9fa53de2002-05-06 16:49:18 +0000405
Chris Lattnerb8b97502003-08-13 19:01:45 +0000406 // X + X --> X << 1
407 if (I.getType()->isInteger())
408 if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS))) return Result;
Chris Lattnerede3fe02003-08-13 04:18:28 +0000409
Chris Lattner147e9752002-05-08 22:46:53 +0000410 // -A + B --> B - A
Chris Lattnerbb74e222003-03-10 23:06:50 +0000411 if (Value *V = dyn_castNegVal(LHS))
Chris Lattner147e9752002-05-08 22:46:53 +0000412 return BinaryOperator::create(Instruction::Sub, RHS, V);
Chris Lattner9fa53de2002-05-06 16:49:18 +0000413
414 // A + -B --> A - B
Chris Lattnerbb74e222003-03-10 23:06:50 +0000415 if (!isa<Constant>(RHS))
416 if (Value *V = dyn_castNegVal(RHS))
417 return BinaryOperator::create(Instruction::Sub, LHS, V);
Chris Lattner260ab202002-04-18 17:39:14 +0000418
Chris Lattner57c8d992003-02-18 19:57:07 +0000419 // X*C + X --> X * (C+1)
420 if (dyn_castFoldableMul(LHS) == RHS) {
Chris Lattner34428442003-05-27 16:40:51 +0000421 Constant *CP1 =
422 ConstantExpr::get(Instruction::Add,
423 cast<Constant>(cast<Instruction>(LHS)->getOperand(1)),
424 ConstantInt::get(I.getType(), 1));
Chris Lattner57c8d992003-02-18 19:57:07 +0000425 return BinaryOperator::create(Instruction::Mul, RHS, CP1);
426 }
427
428 // X + X*C --> X * (C+1)
429 if (dyn_castFoldableMul(RHS) == LHS) {
Chris Lattner34428442003-05-27 16:40:51 +0000430 Constant *CP1 =
431 ConstantExpr::get(Instruction::Add,
432 cast<Constant>(cast<Instruction>(RHS)->getOperand(1)),
433 ConstantInt::get(I.getType(), 1));
Chris Lattner57c8d992003-02-18 19:57:07 +0000434 return BinaryOperator::create(Instruction::Mul, LHS, CP1);
435 }
436
Chris Lattnerb8b97502003-08-13 19:01:45 +0000437 // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
438 if (Constant *C2 = dyn_castMaskingAnd(RHS))
439 if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2))) return R;
Chris Lattner7fb29e12003-03-11 00:12:48 +0000440
Chris Lattnerb9cde762003-10-02 15:11:26 +0000441 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
442 if (Instruction *ILHS = dyn_cast<Instruction>(LHS)) {
443 switch (ILHS->getOpcode()) {
444 case Instruction::Xor:
445 // ~X + C --> (C-1) - X
446 if (ConstantInt *XorRHS = dyn_cast<ConstantInt>(ILHS->getOperand(1)))
447 if (XorRHS->isAllOnesValue())
448 return BinaryOperator::create(Instruction::Sub,
449 *CRHS - *ConstantInt::get(I.getType(), 1),
450 ILHS->getOperand(0));
451 break;
452 default: break;
453 }
454 }
455 }
456
Chris Lattner113f4f42002-06-25 16:13:24 +0000457 return Changed ? &I : 0;
Chris Lattner260ab202002-04-18 17:39:14 +0000458}
459
Chris Lattnerbdb0ce02003-07-22 21:46:59 +0000460// isSignBit - Return true if the value represented by the constant only has the
461// highest order bit set.
462static bool isSignBit(ConstantInt *CI) {
463 unsigned NumBits = CI->getType()->getPrimitiveSize()*8;
464 return (CI->getRawValue() & ~(-1LL << NumBits)) == (1ULL << (NumBits-1));
465}
466
Chris Lattnerdfae8be2003-07-24 17:35:25 +0000467static unsigned getTypeSizeInBits(const Type *Ty) {
468 return Ty == Type::BoolTy ? 1 : Ty->getPrimitiveSize()*8;
469}
470
Chris Lattner113f4f42002-06-25 16:13:24 +0000471Instruction *InstCombiner::visitSub(BinaryOperator &I) {
Chris Lattner113f4f42002-06-25 16:13:24 +0000472 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000473
Chris Lattnere6794492002-08-12 21:17:25 +0000474 if (Op0 == Op1) // sub X, X -> 0
475 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner260ab202002-04-18 17:39:14 +0000476
Chris Lattnere6794492002-08-12 21:17:25 +0000477 // If this is a 'B = x-(-A)', change to B = x+A...
Chris Lattnerbb74e222003-03-10 23:06:50 +0000478 if (Value *V = dyn_castNegVal(Op1))
Chris Lattner147e9752002-05-08 22:46:53 +0000479 return BinaryOperator::create(Instruction::Add, Op0, V);
Chris Lattner9fa53de2002-05-06 16:49:18 +0000480
Chris Lattner3082c5a2003-02-18 19:28:33 +0000481 // Replace (-1 - A) with (~A)...
482 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0))
483 if (C->isAllOnesValue())
484 return BinaryOperator::createNot(Op1);
Chris Lattnerad3c4952002-05-09 01:29:19 +0000485
Chris Lattner3082c5a2003-02-18 19:28:33 +0000486 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1))
487 if (Op1I->use_size() == 1) {
488 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
489 // is not used by anyone else...
490 //
491 if (Op1I->getOpcode() == Instruction::Sub) {
492 // Swap the two operands of the subexpr...
493 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
494 Op1I->setOperand(0, IIOp1);
495 Op1I->setOperand(1, IIOp0);
496
497 // Create the new top level add instruction...
498 return BinaryOperator::create(Instruction::Add, Op0, Op1);
499 }
500
501 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
502 //
503 if (Op1I->getOpcode() == Instruction::And &&
504 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
505 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
506
507 Instruction *NewNot = BinaryOperator::createNot(OtherOp, "B.not", &I);
508 return BinaryOperator::create(Instruction::And, Op0, NewNot);
509 }
Chris Lattner57c8d992003-02-18 19:57:07 +0000510
511 // X - X*C --> X * (1-C)
512 if (dyn_castFoldableMul(Op1I) == Op0) {
Chris Lattner34428442003-05-27 16:40:51 +0000513 Constant *CP1 =
514 ConstantExpr::get(Instruction::Sub,
515 ConstantInt::get(I.getType(), 1),
516 cast<Constant>(cast<Instruction>(Op1)->getOperand(1)));
Chris Lattner57c8d992003-02-18 19:57:07 +0000517 assert(CP1 && "Couldn't constant fold 1-C?");
518 return BinaryOperator::create(Instruction::Mul, Op0, CP1);
519 }
Chris Lattnerad3c4952002-05-09 01:29:19 +0000520 }
Chris Lattner3082c5a2003-02-18 19:28:33 +0000521
Chris Lattner57c8d992003-02-18 19:57:07 +0000522 // X*C - X --> X * (C-1)
523 if (dyn_castFoldableMul(Op0) == Op1) {
Chris Lattner34428442003-05-27 16:40:51 +0000524 Constant *CP1 =
525 ConstantExpr::get(Instruction::Sub,
526 cast<Constant>(cast<Instruction>(Op0)->getOperand(1)),
527 ConstantInt::get(I.getType(), 1));
Chris Lattner57c8d992003-02-18 19:57:07 +0000528 assert(CP1 && "Couldn't constant fold C - 1?");
529 return BinaryOperator::create(Instruction::Mul, Op1, CP1);
530 }
531
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000532 return 0;
Chris Lattner260ab202002-04-18 17:39:14 +0000533}
534
Chris Lattner113f4f42002-06-25 16:13:24 +0000535Instruction *InstCombiner::visitMul(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000536 bool Changed = SimplifyCommutative(I);
Chris Lattner3082c5a2003-02-18 19:28:33 +0000537 Value *Op0 = I.getOperand(0);
Chris Lattner260ab202002-04-18 17:39:14 +0000538
Chris Lattnere6794492002-08-12 21:17:25 +0000539 // Simplify mul instructions with a constant RHS...
Chris Lattner3082c5a2003-02-18 19:28:33 +0000540 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
541 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnerede3fe02003-08-13 04:18:28 +0000542
543 // ((X << C1)*C2) == (X * (C2 << C1))
544 if (ShiftInst *SI = dyn_cast<ShiftInst>(Op0))
545 if (SI->getOpcode() == Instruction::Shl)
546 if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
547 return BinaryOperator::create(Instruction::Mul, SI->getOperand(0),
548 *CI << *ShOp);
549
Chris Lattnercce81be2003-09-11 22:24:54 +0000550 if (CI->isNullValue())
551 return ReplaceInstUsesWith(I, Op1); // X * 0 == 0
552 if (CI->equalsInt(1)) // X * 1 == X
553 return ReplaceInstUsesWith(I, Op0);
554 if (CI->isAllOnesValue()) // X * -1 == 0 - X
Chris Lattner35236d82003-06-25 17:09:20 +0000555 return BinaryOperator::createNeg(Op0, I.getName());
Chris Lattner31ba1292002-04-29 22:24:47 +0000556
Chris Lattnercce81be2003-09-11 22:24:54 +0000557 int64_t Val = (int64_t)cast<ConstantInt>(CI)->getRawValue();
Chris Lattner3082c5a2003-02-18 19:28:33 +0000558 if (uint64_t C = Log2(Val)) // Replace X*(2^C) with X << C
559 return new ShiftInst(Instruction::Shl, Op0,
560 ConstantUInt::get(Type::UByteTy, C));
561 } else {
562 ConstantFP *Op1F = cast<ConstantFP>(Op1);
563 if (Op1F->isNullValue())
564 return ReplaceInstUsesWith(I, Op1);
Chris Lattner31ba1292002-04-29 22:24:47 +0000565
Chris Lattner3082c5a2003-02-18 19:28:33 +0000566 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
567 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
568 if (Op1F->getValue() == 1.0)
569 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0'
570 }
Chris Lattner260ab202002-04-18 17:39:14 +0000571 }
572
Chris Lattner934a64cf2003-03-10 23:23:04 +0000573 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
574 if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
575 return BinaryOperator::create(Instruction::Mul, Op0v, Op1v);
576
Chris Lattner113f4f42002-06-25 16:13:24 +0000577 return Changed ? &I : 0;
Chris Lattner260ab202002-04-18 17:39:14 +0000578}
579
Chris Lattner113f4f42002-06-25 16:13:24 +0000580Instruction *InstCombiner::visitDiv(BinaryOperator &I) {
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000581 // div X, 1 == X
Chris Lattner3082c5a2003-02-18 19:28:33 +0000582 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I.getOperand(1))) {
Chris Lattnere6794492002-08-12 21:17:25 +0000583 if (RHS->equalsInt(1))
584 return ReplaceInstUsesWith(I, I.getOperand(0));
Chris Lattner3082c5a2003-02-18 19:28:33 +0000585
586 // Check to see if this is an unsigned division with an exact power of 2,
587 // if so, convert to a right shift.
588 if (ConstantUInt *C = dyn_cast<ConstantUInt>(RHS))
589 if (uint64_t Val = C->getValue()) // Don't break X / 0
590 if (uint64_t C = Log2(Val))
591 return new ShiftInst(Instruction::Shr, I.getOperand(0),
592 ConstantUInt::get(Type::UByteTy, C));
593 }
594
595 // 0 / X == 0, we don't need to preserve faults!
596 if (ConstantInt *LHS = dyn_cast<ConstantInt>(I.getOperand(0)))
597 if (LHS->equalsInt(0))
598 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
599
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000600 return 0;
601}
602
603
Chris Lattner113f4f42002-06-25 16:13:24 +0000604Instruction *InstCombiner::visitRem(BinaryOperator &I) {
Chris Lattner3082c5a2003-02-18 19:28:33 +0000605 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I.getOperand(1))) {
606 if (RHS->equalsInt(1)) // X % 1 == 0
607 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
608
609 // Check to see if this is an unsigned remainder with an exact power of 2,
610 // if so, convert to a bitwise and.
611 if (ConstantUInt *C = dyn_cast<ConstantUInt>(RHS))
612 if (uint64_t Val = C->getValue()) // Don't break X % 0 (divide by zero)
613 if (Log2(Val))
614 return BinaryOperator::create(Instruction::And, I.getOperand(0),
615 ConstantUInt::get(I.getType(), Val-1));
616 }
617
618 // 0 % X == 0, we don't need to preserve faults!
619 if (ConstantInt *LHS = dyn_cast<ConstantInt>(I.getOperand(0)))
620 if (LHS->equalsInt(0))
Chris Lattnere6794492002-08-12 21:17:25 +0000621 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
622
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000623 return 0;
624}
625
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000626// isMaxValueMinusOne - return true if this is Max-1
Chris Lattnere6794492002-08-12 21:17:25 +0000627static bool isMaxValueMinusOne(const ConstantInt *C) {
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000628 if (const ConstantUInt *CU = dyn_cast<ConstantUInt>(C)) {
629 // Calculate -1 casted to the right type...
630 unsigned TypeBits = C->getType()->getPrimitiveSize()*8;
631 uint64_t Val = ~0ULL; // All ones
632 Val >>= 64-TypeBits; // Shift out unwanted 1 bits...
633 return CU->getValue() == Val-1;
634 }
635
636 const ConstantSInt *CS = cast<ConstantSInt>(C);
637
638 // Calculate 0111111111..11111
639 unsigned TypeBits = C->getType()->getPrimitiveSize()*8;
640 int64_t Val = INT64_MAX; // All ones
641 Val >>= 64-TypeBits; // Shift out unwanted 1 bits...
642 return CS->getValue() == Val-1;
643}
644
645// isMinValuePlusOne - return true if this is Min+1
Chris Lattnere6794492002-08-12 21:17:25 +0000646static bool isMinValuePlusOne(const ConstantInt *C) {
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000647 if (const ConstantUInt *CU = dyn_cast<ConstantUInt>(C))
648 return CU->getValue() == 1;
649
650 const ConstantSInt *CS = cast<ConstantSInt>(C);
651
652 // Calculate 1111111111000000000000
653 unsigned TypeBits = C->getType()->getPrimitiveSize()*8;
654 int64_t Val = -1; // All ones
655 Val <<= TypeBits-1; // Shift over to the right spot
656 return CS->getValue() == Val+1;
657}
658
Chris Lattner3ac7c262003-08-13 20:16:26 +0000659/// getSetCondCode - Encode a setcc opcode into a three bit mask. These bits
660/// are carefully arranged to allow folding of expressions such as:
661///
662/// (A < B) | (A > B) --> (A != B)
663///
664/// Bit value '4' represents that the comparison is true if A > B, bit value '2'
665/// represents that the comparison is true if A == B, and bit value '1' is true
666/// if A < B.
667///
668static unsigned getSetCondCode(const SetCondInst *SCI) {
669 switch (SCI->getOpcode()) {
670 // False -> 0
671 case Instruction::SetGT: return 1;
672 case Instruction::SetEQ: return 2;
673 case Instruction::SetGE: return 3;
674 case Instruction::SetLT: return 4;
675 case Instruction::SetNE: return 5;
676 case Instruction::SetLE: return 6;
677 // True -> 7
678 default:
679 assert(0 && "Invalid SetCC opcode!");
680 return 0;
681 }
682}
683
684/// getSetCCValue - This is the complement of getSetCondCode, which turns an
685/// opcode and two operands into either a constant true or false, or a brand new
686/// SetCC instruction.
687static Value *getSetCCValue(unsigned Opcode, Value *LHS, Value *RHS) {
688 switch (Opcode) {
689 case 0: return ConstantBool::False;
690 case 1: return new SetCondInst(Instruction::SetGT, LHS, RHS);
691 case 2: return new SetCondInst(Instruction::SetEQ, LHS, RHS);
692 case 3: return new SetCondInst(Instruction::SetGE, LHS, RHS);
693 case 4: return new SetCondInst(Instruction::SetLT, LHS, RHS);
694 case 5: return new SetCondInst(Instruction::SetNE, LHS, RHS);
695 case 6: return new SetCondInst(Instruction::SetLE, LHS, RHS);
696 case 7: return ConstantBool::True;
697 default: assert(0 && "Illegal SetCCCode!"); return 0;
698 }
699}
700
701// FoldSetCCLogical - Implements (setcc1 A, B) & (setcc2 A, B) --> (setcc3 A, B)
702struct FoldSetCCLogical {
703 InstCombiner &IC;
704 Value *LHS, *RHS;
705 FoldSetCCLogical(InstCombiner &ic, SetCondInst *SCI)
706 : IC(ic), LHS(SCI->getOperand(0)), RHS(SCI->getOperand(1)) {}
707 bool shouldApply(Value *V) const {
708 if (SetCondInst *SCI = dyn_cast<SetCondInst>(V))
709 return (SCI->getOperand(0) == LHS && SCI->getOperand(1) == RHS ||
710 SCI->getOperand(0) == RHS && SCI->getOperand(1) == LHS);
711 return false;
712 }
713 Instruction *apply(BinaryOperator &Log) const {
714 SetCondInst *SCI = cast<SetCondInst>(Log.getOperand(0));
715 if (SCI->getOperand(0) != LHS) {
716 assert(SCI->getOperand(1) == LHS);
717 SCI->swapOperands(); // Swap the LHS and RHS of the SetCC
718 }
719
720 unsigned LHSCode = getSetCondCode(SCI);
721 unsigned RHSCode = getSetCondCode(cast<SetCondInst>(Log.getOperand(1)));
722 unsigned Code;
723 switch (Log.getOpcode()) {
724 case Instruction::And: Code = LHSCode & RHSCode; break;
725 case Instruction::Or: Code = LHSCode | RHSCode; break;
726 case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
Chris Lattner2caaaba2003-09-22 20:33:34 +0000727 default: assert(0 && "Illegal logical opcode!"); return 0;
Chris Lattner3ac7c262003-08-13 20:16:26 +0000728 }
729
730 Value *RV = getSetCCValue(Code, LHS, RHS);
731 if (Instruction *I = dyn_cast<Instruction>(RV))
732 return I;
733 // Otherwise, it's a constant boolean value...
734 return IC.ReplaceInstUsesWith(Log, RV);
735 }
736};
737
738
Chris Lattnerba1cb382003-09-19 17:17:26 +0000739// OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
740// the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
741// guaranteed to be either a shift instruction or a binary operator.
742Instruction *InstCombiner::OptAndOp(Instruction *Op,
743 ConstantIntegral *OpRHS,
744 ConstantIntegral *AndRHS,
745 BinaryOperator &TheAnd) {
746 Value *X = Op->getOperand(0);
747 switch (Op->getOpcode()) {
748 case Instruction::Xor:
749 if ((*AndRHS & *OpRHS)->isNullValue()) {
750 // (X ^ C1) & C2 --> (X & C2) iff (C1&C2) == 0
751 return BinaryOperator::create(Instruction::And, X, AndRHS);
752 } else if (Op->use_size() == 1) {
753 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
754 std::string OpName = Op->getName(); Op->setName("");
755 Instruction *And = BinaryOperator::create(Instruction::And,
756 X, AndRHS, OpName);
757 InsertNewInstBefore(And, TheAnd);
758 return BinaryOperator::create(Instruction::Xor, And, *AndRHS & *OpRHS);
759 }
760 break;
761 case Instruction::Or:
762 // (X | C1) & C2 --> X & C2 iff C1 & C1 == 0
763 if ((*AndRHS & *OpRHS)->isNullValue())
764 return BinaryOperator::create(Instruction::And, X, AndRHS);
765 else {
766 Constant *Together = *AndRHS & *OpRHS;
767 if (Together == AndRHS) // (X | C) & C --> C
768 return ReplaceInstUsesWith(TheAnd, AndRHS);
769
770 if (Op->use_size() == 1 && Together != OpRHS) {
771 // (X | C1) & C2 --> (X | (C1&C2)) & C2
772 std::string Op0Name = Op->getName(); Op->setName("");
773 Instruction *Or = BinaryOperator::create(Instruction::Or, X,
774 Together, Op0Name);
775 InsertNewInstBefore(Or, TheAnd);
776 return BinaryOperator::create(Instruction::And, Or, AndRHS);
777 }
778 }
779 break;
780 case Instruction::Add:
781 if (Op->use_size() == 1) {
782 // Adding a one to a single bit bit-field should be turned into an XOR
783 // of the bit. First thing to check is to see if this AND is with a
784 // single bit constant.
785 unsigned long long AndRHSV = cast<ConstantInt>(AndRHS)->getRawValue();
786
787 // Clear bits that are not part of the constant.
788 AndRHSV &= (1ULL << AndRHS->getType()->getPrimitiveSize()*8)-1;
789
790 // If there is only one bit set...
791 if ((AndRHSV & (AndRHSV-1)) == 0) {
792 // Ok, at this point, we know that we are masking the result of the
793 // ADD down to exactly one bit. If the constant we are adding has
794 // no bits set below this bit, then we can eliminate the ADD.
795 unsigned long long AddRHS = cast<ConstantInt>(OpRHS)->getRawValue();
796
797 // Check to see if any bits below the one bit set in AndRHSV are set.
798 if ((AddRHS & (AndRHSV-1)) == 0) {
799 // If not, the only thing that can effect the output of the AND is
800 // the bit specified by AndRHSV. If that bit is set, the effect of
801 // the XOR is to toggle the bit. If it is clear, then the ADD has
802 // no effect.
803 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
804 TheAnd.setOperand(0, X);
805 return &TheAnd;
806 } else {
807 std::string Name = Op->getName(); Op->setName("");
808 // Pull the XOR out of the AND.
809 Instruction *NewAnd =
810 BinaryOperator::create(Instruction::And, X, AndRHS, Name);
811 InsertNewInstBefore(NewAnd, TheAnd);
812 return BinaryOperator::create(Instruction::Xor, NewAnd, AndRHS);
813 }
814 }
815 }
816 }
817 break;
Chris Lattner2da29172003-09-19 19:05:02 +0000818
819 case Instruction::Shl: {
820 // We know that the AND will not produce any of the bits shifted in, so if
821 // the anded constant includes them, clear them now!
822 //
823 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
824 Constant *CI = *AndRHS & *(*AllOne << *OpRHS);
825 if (CI != AndRHS) {
826 TheAnd.setOperand(1, CI);
827 return &TheAnd;
828 }
829 break;
830 }
831 case Instruction::Shr:
832 // We know that the AND will not produce any of the bits shifted in, so if
833 // the anded constant includes them, clear them now! This only applies to
834 // unsigned shifts, because a signed shr may bring in set bits!
835 //
836 if (AndRHS->getType()->isUnsigned()) {
837 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
838 Constant *CI = *AndRHS & *(*AllOne >> *OpRHS);
839 if (CI != AndRHS) {
840 TheAnd.setOperand(1, CI);
841 return &TheAnd;
842 }
843 }
844 break;
Chris Lattnerba1cb382003-09-19 17:17:26 +0000845 }
846 return 0;
847}
848
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000849
Chris Lattner113f4f42002-06-25 16:13:24 +0000850Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000851 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +0000852 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000853
854 // and X, X = X and X, 0 == 0
Chris Lattnere6794492002-08-12 21:17:25 +0000855 if (Op0 == Op1 || Op1 == Constant::getNullValue(I.getType()))
856 return ReplaceInstUsesWith(I, Op1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000857
858 // and X, -1 == X
Chris Lattner49b47ae2003-07-23 17:57:01 +0000859 if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
Chris Lattnere6794492002-08-12 21:17:25 +0000860 if (RHS->isAllOnesValue())
861 return ReplaceInstUsesWith(I, Op0);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000862
Chris Lattnerba1cb382003-09-19 17:17:26 +0000863 // Optimize a variety of ((val OP C1) & C2) combinations...
864 if (isa<BinaryOperator>(Op0) || isa<ShiftInst>(Op0)) {
865 Instruction *Op0I = cast<Instruction>(Op0);
Chris Lattner33217db2003-07-23 19:36:21 +0000866 Value *X = Op0I->getOperand(0);
Chris Lattner16464b32003-07-23 19:25:52 +0000867 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattnerba1cb382003-09-19 17:17:26 +0000868 if (Instruction *Res = OptAndOp(Op0I, Op0CI, RHS, I))
869 return Res;
Chris Lattner33217db2003-07-23 19:36:21 +0000870 }
Chris Lattner49b47ae2003-07-23 17:57:01 +0000871 }
872
Chris Lattnerbb74e222003-03-10 23:06:50 +0000873 Value *Op0NotVal = dyn_castNotVal(Op0);
874 Value *Op1NotVal = dyn_castNotVal(Op1);
Chris Lattner3082c5a2003-02-18 19:28:33 +0000875
876 // (~A & ~B) == (~(A | B)) - Demorgan's Law
Chris Lattnerbb74e222003-03-10 23:06:50 +0000877 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Chris Lattner3082c5a2003-02-18 19:28:33 +0000878 Instruction *Or = BinaryOperator::create(Instruction::Or, Op0NotVal,
Chris Lattner49b47ae2003-07-23 17:57:01 +0000879 Op1NotVal,I.getName()+".demorgan");
880 InsertNewInstBefore(Or, I);
Chris Lattner3082c5a2003-02-18 19:28:33 +0000881 return BinaryOperator::createNot(Or);
882 }
883
884 if (Op0NotVal == Op1 || Op1NotVal == Op0) // A & ~A == ~A & A == 0
885 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner65217ff2002-08-23 18:32:43 +0000886
Chris Lattner3ac7c262003-08-13 20:16:26 +0000887 // (setcc1 A, B) & (setcc2 A, B) --> (setcc3 A, B)
888 if (SetCondInst *RHS = dyn_cast<SetCondInst>(I.getOperand(1)))
889 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
890 return R;
891
Chris Lattner113f4f42002-06-25 16:13:24 +0000892 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000893}
894
895
896
Chris Lattner113f4f42002-06-25 16:13:24 +0000897Instruction *InstCombiner::visitOr(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000898 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +0000899 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000900
901 // or X, X = X or X, 0 == X
Chris Lattnere6794492002-08-12 21:17:25 +0000902 if (Op0 == Op1 || Op1 == Constant::getNullValue(I.getType()))
903 return ReplaceInstUsesWith(I, Op0);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000904
905 // or X, -1 == -1
Chris Lattner8f0d1562003-07-23 18:29:44 +0000906 if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
Chris Lattnere6794492002-08-12 21:17:25 +0000907 if (RHS->isAllOnesValue())
908 return ReplaceInstUsesWith(I, Op1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000909
Chris Lattner8f0d1562003-07-23 18:29:44 +0000910 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
911 // (X & C1) | C2 --> (X | C2) & (C1|C2)
912 if (Op0I->getOpcode() == Instruction::And && isOnlyUse(Op0))
913 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
914 std::string Op0Name = Op0I->getName(); Op0I->setName("");
915 Instruction *Or = BinaryOperator::create(Instruction::Or,
916 Op0I->getOperand(0), RHS,
917 Op0Name);
918 InsertNewInstBefore(Or, I);
919 return BinaryOperator::create(Instruction::And, Or, *RHS | *Op0CI);
920 }
921
922 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
923 if (Op0I->getOpcode() == Instruction::Xor && isOnlyUse(Op0))
924 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
925 std::string Op0Name = Op0I->getName(); Op0I->setName("");
926 Instruction *Or = BinaryOperator::create(Instruction::Or,
927 Op0I->getOperand(0), RHS,
928 Op0Name);
929 InsertNewInstBefore(Or, I);
930 return BinaryOperator::create(Instruction::Xor, Or, *Op0CI & *~*RHS);
931 }
932 }
933 }
934
Chris Lattner812aab72003-08-12 19:11:07 +0000935 // (A & C1)|(A & C2) == A & (C1|C2)
Chris Lattner01d56392003-08-12 19:17:27 +0000936 if (Instruction *LHS = dyn_cast<BinaryOperator>(Op0))
937 if (Instruction *RHS = dyn_cast<BinaryOperator>(Op1))
938 if (LHS->getOperand(0) == RHS->getOperand(0))
939 if (Constant *C0 = dyn_castMaskingAnd(LHS))
940 if (Constant *C1 = dyn_castMaskingAnd(RHS))
941 return BinaryOperator::create(Instruction::And, LHS->getOperand(0),
Chris Lattner812aab72003-08-12 19:11:07 +0000942 *C0 | *C1);
943
Chris Lattner3e327a42003-03-10 23:13:59 +0000944 Value *Op0NotVal = dyn_castNotVal(Op0);
945 Value *Op1NotVal = dyn_castNotVal(Op1);
Chris Lattner3082c5a2003-02-18 19:28:33 +0000946
Chris Lattner3e327a42003-03-10 23:13:59 +0000947 if (Op1 == Op0NotVal) // ~A | A == -1
948 return ReplaceInstUsesWith(I,
949 ConstantIntegral::getAllOnesValue(I.getType()));
950
951 if (Op0 == Op1NotVal) // A | ~A == -1
952 return ReplaceInstUsesWith(I,
953 ConstantIntegral::getAllOnesValue(I.getType()));
954
955 // (~A | ~B) == (~(A & B)) - Demorgan's Law
956 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
957 Instruction *And = BinaryOperator::create(Instruction::And, Op0NotVal,
958 Op1NotVal,I.getName()+".demorgan",
959 &I);
960 WorkList.push_back(And);
961 return BinaryOperator::createNot(And);
962 }
Chris Lattner3082c5a2003-02-18 19:28:33 +0000963
Chris Lattner3ac7c262003-08-13 20:16:26 +0000964 // (setcc1 A, B) | (setcc2 A, B) --> (setcc3 A, B)
965 if (SetCondInst *RHS = dyn_cast<SetCondInst>(I.getOperand(1)))
966 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
967 return R;
968
Chris Lattner113f4f42002-06-25 16:13:24 +0000969 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000970}
971
972
973
Chris Lattner113f4f42002-06-25 16:13:24 +0000974Instruction *InstCombiner::visitXor(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000975 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +0000976 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000977
978 // xor X, X = 0
Chris Lattnere6794492002-08-12 21:17:25 +0000979 if (Op0 == Op1)
980 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000981
Chris Lattner97638592003-07-23 21:37:07 +0000982 if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000983 // xor X, 0 == X
Chris Lattner97638592003-07-23 21:37:07 +0000984 if (RHS->isNullValue())
Chris Lattnere6794492002-08-12 21:17:25 +0000985 return ReplaceInstUsesWith(I, Op0);
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000986
Chris Lattner97638592003-07-23 21:37:07 +0000987 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Chris Lattnerb8d6e402002-08-20 18:24:26 +0000988 // xor (setcc A, B), true = not (setcc A, B) = setncc A, B
Chris Lattner97638592003-07-23 21:37:07 +0000989 if (SetCondInst *SCI = dyn_cast<SetCondInst>(Op0I))
990 if (RHS == ConstantBool::True && SCI->use_size() == 1)
Chris Lattnerb8d6e402002-08-20 18:24:26 +0000991 return new SetCondInst(SCI->getInverseCondition(),
992 SCI->getOperand(0), SCI->getOperand(1));
Chris Lattner97638592003-07-23 21:37:07 +0000993
994 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
995 if (Op0I->getOpcode() == Instruction::And) {
996 // (X & C1) ^ C2 --> (X & C1) | C2 iff (C1&C2) == 0
997 if ((*RHS & *Op0CI)->isNullValue())
998 return BinaryOperator::create(Instruction::Or, Op0, RHS);
999 } else if (Op0I->getOpcode() == Instruction::Or) {
1000 // (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
1001 if ((*RHS & *Op0CI) == RHS)
1002 return BinaryOperator::create(Instruction::And, Op0, ~*RHS);
1003 }
Chris Lattnerb8d6e402002-08-20 18:24:26 +00001004 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001005 }
1006
Chris Lattnerbb74e222003-03-10 23:06:50 +00001007 if (Value *X = dyn_castNotVal(Op0)) // ~A ^ A == -1
Chris Lattner3082c5a2003-02-18 19:28:33 +00001008 if (X == Op1)
1009 return ReplaceInstUsesWith(I,
1010 ConstantIntegral::getAllOnesValue(I.getType()));
1011
Chris Lattnerbb74e222003-03-10 23:06:50 +00001012 if (Value *X = dyn_castNotVal(Op1)) // A ^ ~A == -1
Chris Lattner3082c5a2003-02-18 19:28:33 +00001013 if (X == Op0)
1014 return ReplaceInstUsesWith(I,
1015 ConstantIntegral::getAllOnesValue(I.getType()));
1016
Chris Lattner1bbb7b62003-03-10 18:24:17 +00001017 if (Instruction *Op1I = dyn_cast<Instruction>(Op1))
1018 if (Op1I->getOpcode() == Instruction::Or)
1019 if (Op1I->getOperand(0) == Op0) { // B^(B|A) == (A|B)^B
1020 cast<BinaryOperator>(Op1I)->swapOperands();
1021 I.swapOperands();
1022 std::swap(Op0, Op1);
1023 } else if (Op1I->getOperand(1) == Op0) { // B^(A|B) == (A|B)^B
1024 I.swapOperands();
1025 std::swap(Op0, Op1);
1026 }
1027
1028 if (Instruction *Op0I = dyn_cast<Instruction>(Op0))
1029 if (Op0I->getOpcode() == Instruction::Or && Op0I->use_size() == 1) {
1030 if (Op0I->getOperand(0) == Op1) // (B|A)^B == (A|B)^B
1031 cast<BinaryOperator>(Op0I)->swapOperands();
Chris Lattnerdcf240a2003-03-10 21:43:22 +00001032 if (Op0I->getOperand(1) == Op1) { // (A|B)^B == A & ~B
Chris Lattner1bbb7b62003-03-10 18:24:17 +00001033 Value *NotB = BinaryOperator::createNot(Op1, Op1->getName()+".not", &I);
1034 WorkList.push_back(cast<Instruction>(NotB));
Chris Lattnerdcf240a2003-03-10 21:43:22 +00001035 return BinaryOperator::create(Instruction::And, Op0I->getOperand(0),
1036 NotB);
Chris Lattner1bbb7b62003-03-10 18:24:17 +00001037 }
1038 }
1039
Chris Lattner7fb29e12003-03-11 00:12:48 +00001040 // (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1^C2 == 0
1041 if (Constant *C1 = dyn_castMaskingAnd(Op0))
1042 if (Constant *C2 = dyn_castMaskingAnd(Op1))
Chris Lattner34428442003-05-27 16:40:51 +00001043 if (ConstantExpr::get(Instruction::And, C1, C2)->isNullValue())
Chris Lattner7fb29e12003-03-11 00:12:48 +00001044 return BinaryOperator::create(Instruction::Or, Op0, Op1);
1045
Chris Lattner3ac7c262003-08-13 20:16:26 +00001046 // (setcc1 A, B) ^ (setcc2 A, B) --> (setcc3 A, B)
1047 if (SetCondInst *RHS = dyn_cast<SetCondInst>(I.getOperand(1)))
1048 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
1049 return R;
1050
Chris Lattner113f4f42002-06-25 16:13:24 +00001051 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001052}
1053
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001054// AddOne, SubOne - Add or subtract a constant one from an integer constant...
1055static Constant *AddOne(ConstantInt *C) {
Chris Lattner34428442003-05-27 16:40:51 +00001056 Constant *Result = ConstantExpr::get(Instruction::Add, C,
1057 ConstantInt::get(C->getType(), 1));
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001058 assert(Result && "Constant folding integer addition failed!");
1059 return Result;
1060}
1061static Constant *SubOne(ConstantInt *C) {
Chris Lattner34428442003-05-27 16:40:51 +00001062 Constant *Result = ConstantExpr::get(Instruction::Sub, C,
1063 ConstantInt::get(C->getType(), 1));
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001064 assert(Result && "Constant folding integer addition failed!");
1065 return Result;
1066}
1067
Chris Lattner1fc23f32002-05-09 20:11:54 +00001068// isTrueWhenEqual - Return true if the specified setcondinst instruction is
1069// true when both operands are equal...
1070//
Chris Lattner113f4f42002-06-25 16:13:24 +00001071static bool isTrueWhenEqual(Instruction &I) {
1072 return I.getOpcode() == Instruction::SetEQ ||
1073 I.getOpcode() == Instruction::SetGE ||
1074 I.getOpcode() == Instruction::SetLE;
Chris Lattner1fc23f32002-05-09 20:11:54 +00001075}
1076
Chris Lattner113f4f42002-06-25 16:13:24 +00001077Instruction *InstCombiner::visitSetCondInst(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00001078 bool Changed = SimplifyCommutative(I);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001079 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1080 const Type *Ty = Op0->getType();
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001081
1082 // setcc X, X
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001083 if (Op0 == Op1)
1084 return ReplaceInstUsesWith(I, ConstantBool::get(isTrueWhenEqual(I)));
Chris Lattner1fc23f32002-05-09 20:11:54 +00001085
Chris Lattnerd07283a2003-08-13 05:38:46 +00001086 // setcc <global/alloca*>, 0 - Global/Stack value addresses are never null!
1087 if (isa<ConstantPointerNull>(Op1) &&
1088 (isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0)))
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001089 return ReplaceInstUsesWith(I, ConstantBool::get(!isTrueWhenEqual(I)));
1090
Chris Lattnerd07283a2003-08-13 05:38:46 +00001091
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001092 // setcc's with boolean values can always be turned into bitwise operations
1093 if (Ty == Type::BoolTy) {
1094 // If this is <, >, or !=, we can change this into a simple xor instruction
1095 if (!isTrueWhenEqual(I))
1096 return BinaryOperator::create(Instruction::Xor, Op0, Op1, I.getName());
1097
1098 // Otherwise we need to make a temporary intermediate instruction and insert
1099 // it into the instruction stream. This is what we are after:
1100 //
1101 // seteq bool %A, %B -> ~(A^B)
1102 // setle bool %A, %B -> ~A | B
1103 // setge bool %A, %B -> A | ~B
1104 //
1105 if (I.getOpcode() == Instruction::SetEQ) { // seteq case
1106 Instruction *Xor = BinaryOperator::create(Instruction::Xor, Op0, Op1,
1107 I.getName()+"tmp");
1108 InsertNewInstBefore(Xor, I);
Chris Lattner31ae8632002-08-14 17:51:49 +00001109 return BinaryOperator::createNot(Xor, I.getName());
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001110 }
1111
1112 // Handle the setXe cases...
1113 assert(I.getOpcode() == Instruction::SetGE ||
1114 I.getOpcode() == Instruction::SetLE);
1115
1116 if (I.getOpcode() == Instruction::SetGE)
1117 std::swap(Op0, Op1); // Change setge -> setle
1118
1119 // Now we just have the SetLE case.
Chris Lattner31ae8632002-08-14 17:51:49 +00001120 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001121 InsertNewInstBefore(Not, I);
1122 return BinaryOperator::create(Instruction::Or, Not, Op1, I.getName());
1123 }
1124
1125 // Check to see if we are doing one of many comparisons against constant
1126 // integers at the end of their ranges...
1127 //
1128 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnerd492a0b2003-07-23 17:02:11 +00001129 // Simplify seteq and setne instructions...
1130 if (I.getOpcode() == Instruction::SetEQ ||
1131 I.getOpcode() == Instruction::SetNE) {
1132 bool isSetNE = I.getOpcode() == Instruction::SetNE;
1133
Chris Lattnercfbce7c2003-07-23 17:26:36 +00001134 // If the first operand is (and|or|xor) with a constant, and the second
Chris Lattnerd492a0b2003-07-23 17:02:11 +00001135 // operand is a constant, simplify a bit.
Chris Lattnerc992add2003-08-13 05:33:12 +00001136 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0)) {
1137 switch (BO->getOpcode()) {
1138 case Instruction::Add:
1139 if (CI->isNullValue()) {
1140 // Replace ((add A, B) != 0) with (A != -B) if A or B is
1141 // efficiently invertible, or if the add has just this one use.
1142 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
1143 if (Value *NegVal = dyn_castNegVal(BOp1))
1144 return new SetCondInst(I.getOpcode(), BOp0, NegVal);
1145 else if (Value *NegVal = dyn_castNegVal(BOp0))
1146 return new SetCondInst(I.getOpcode(), NegVal, BOp1);
1147 else if (BO->use_size() == 1) {
1148 Instruction *Neg = BinaryOperator::createNeg(BOp1, BO->getName());
1149 BO->setName("");
1150 InsertNewInstBefore(Neg, I);
1151 return new SetCondInst(I.getOpcode(), BOp0, Neg);
1152 }
1153 }
1154 break;
1155 case Instruction::Xor:
1156 // For the xor case, we can xor two constants together, eliminating
1157 // the explicit xor.
1158 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
1159 return BinaryOperator::create(I.getOpcode(), BO->getOperand(0),
1160 *CI ^ *BOC);
1161
1162 // FALLTHROUGH
1163 case Instruction::Sub:
1164 // Replace (([sub|xor] A, B) != 0) with (A != B)
1165 if (CI->isNullValue())
1166 return new SetCondInst(I.getOpcode(), BO->getOperand(0),
1167 BO->getOperand(1));
1168 break;
1169
1170 case Instruction::Or:
1171 // If bits are being or'd in that are not present in the constant we
1172 // are comparing against, then the comparison could never succeed!
1173 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
Chris Lattnerd492a0b2003-07-23 17:02:11 +00001174 if (!(*BOC & *~*CI)->isNullValue())
1175 return ReplaceInstUsesWith(I, ConstantBool::get(isSetNE));
Chris Lattnerc992add2003-08-13 05:33:12 +00001176 break;
1177
1178 case Instruction::And:
1179 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
Chris Lattnerd492a0b2003-07-23 17:02:11 +00001180 // If bits are being compared against that are and'd out, then the
1181 // comparison can never succeed!
1182 if (!(*CI & *~*BOC)->isNullValue())
1183 return ReplaceInstUsesWith(I, ConstantBool::get(isSetNE));
Chris Lattnerc992add2003-08-13 05:33:12 +00001184
1185 // Replace (and X, (1 << size(X)-1) != 0) with x < 0, converting X
1186 // to be a signed value as appropriate.
1187 if (isSignBit(BOC)) {
1188 Value *X = BO->getOperand(0);
1189 // If 'X' is not signed, insert a cast now...
1190 if (!BOC->getType()->isSigned()) {
1191 const Type *DestTy;
1192 switch (BOC->getType()->getPrimitiveID()) {
1193 case Type::UByteTyID: DestTy = Type::SByteTy; break;
1194 case Type::UShortTyID: DestTy = Type::ShortTy; break;
1195 case Type::UIntTyID: DestTy = Type::IntTy; break;
1196 case Type::ULongTyID: DestTy = Type::LongTy; break;
1197 default: assert(0 && "Invalid unsigned integer type!"); abort();
1198 }
1199 CastInst *NewCI = new CastInst(X,DestTy,X->getName()+".signed");
1200 InsertNewInstBefore(NewCI, I);
1201 X = NewCI;
1202 }
1203 return new SetCondInst(isSetNE ? Instruction::SetLT :
1204 Instruction::SetGE, X,
1205 Constant::getNullValue(X->getType()));
1206 }
Chris Lattnerd492a0b2003-07-23 17:02:11 +00001207 }
Chris Lattnerc992add2003-08-13 05:33:12 +00001208 default: break;
1209 }
1210 }
Chris Lattnere967b342003-06-04 05:10:11 +00001211 }
Chris Lattner791ac1a2003-06-01 03:35:25 +00001212
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001213 // Check to see if we are comparing against the minimum or maximum value...
Chris Lattnere6794492002-08-12 21:17:25 +00001214 if (CI->isMinValue()) {
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001215 if (I.getOpcode() == Instruction::SetLT) // A < MIN -> FALSE
1216 return ReplaceInstUsesWith(I, ConstantBool::False);
1217 if (I.getOpcode() == Instruction::SetGE) // A >= MIN -> TRUE
1218 return ReplaceInstUsesWith(I, ConstantBool::True);
1219 if (I.getOpcode() == Instruction::SetLE) // A <= MIN -> A == MIN
1220 return BinaryOperator::create(Instruction::SetEQ, Op0,Op1, I.getName());
1221 if (I.getOpcode() == Instruction::SetGT) // A > MIN -> A != MIN
1222 return BinaryOperator::create(Instruction::SetNE, Op0,Op1, I.getName());
1223
Chris Lattnere6794492002-08-12 21:17:25 +00001224 } else if (CI->isMaxValue()) {
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001225 if (I.getOpcode() == Instruction::SetGT) // A > MAX -> FALSE
1226 return ReplaceInstUsesWith(I, ConstantBool::False);
1227 if (I.getOpcode() == Instruction::SetLE) // A <= MAX -> TRUE
1228 return ReplaceInstUsesWith(I, ConstantBool::True);
1229 if (I.getOpcode() == Instruction::SetGE) // A >= MAX -> A == MAX
1230 return BinaryOperator::create(Instruction::SetEQ, Op0,Op1, I.getName());
1231 if (I.getOpcode() == Instruction::SetLT) // A < MAX -> A != MAX
1232 return BinaryOperator::create(Instruction::SetNE, Op0,Op1, I.getName());
1233
1234 // Comparing against a value really close to min or max?
1235 } else if (isMinValuePlusOne(CI)) {
1236 if (I.getOpcode() == Instruction::SetLT) // A < MIN+1 -> A == MIN
1237 return BinaryOperator::create(Instruction::SetEQ, Op0,
1238 SubOne(CI), I.getName());
1239 if (I.getOpcode() == Instruction::SetGE) // A >= MIN-1 -> A != MIN
1240 return BinaryOperator::create(Instruction::SetNE, Op0,
1241 SubOne(CI), I.getName());
1242
1243 } else if (isMaxValueMinusOne(CI)) {
1244 if (I.getOpcode() == Instruction::SetGT) // A > MAX-1 -> A == MAX
1245 return BinaryOperator::create(Instruction::SetEQ, Op0,
1246 AddOne(CI), I.getName());
1247 if (I.getOpcode() == Instruction::SetLE) // A <= MAX-1 -> A != MAX
1248 return BinaryOperator::create(Instruction::SetNE, Op0,
1249 AddOne(CI), I.getName());
1250 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001251 }
1252
Chris Lattner113f4f42002-06-25 16:13:24 +00001253 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001254}
1255
1256
1257
Chris Lattnere8d6c602003-03-10 19:16:08 +00001258Instruction *InstCombiner::visitShiftInst(ShiftInst &I) {
Chris Lattner113f4f42002-06-25 16:13:24 +00001259 assert(I.getOperand(1)->getType() == Type::UByteTy);
1260 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00001261 bool isLeftShift = I.getOpcode() == Instruction::Shl;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001262
1263 // shl X, 0 == X and shr X, 0 == X
1264 // shl 0, X == 0 and shr 0, X == 0
1265 if (Op1 == Constant::getNullValue(Type::UByteTy) ||
Chris Lattnere6794492002-08-12 21:17:25 +00001266 Op0 == Constant::getNullValue(Op0->getType()))
1267 return ReplaceInstUsesWith(I, Op0);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001268
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00001269 // shr int -1, X = -1 (for any arithmetic shift rights of ~0)
1270 if (!isLeftShift)
1271 if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(Op0))
1272 if (CSI->isAllOnesValue())
1273 return ReplaceInstUsesWith(I, CSI);
1274
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001275 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(Op1)) {
Chris Lattner3204d4e2003-07-24 17:52:58 +00001276 // shl uint X, 32 = 0 and shr ubyte Y, 9 = 0, ... just don't eliminate shr
1277 // of a signed value.
1278 //
Chris Lattnere8d6c602003-03-10 19:16:08 +00001279 unsigned TypeBits = Op0->getType()->getPrimitiveSize()*8;
1280 if (CUI->getValue() >= TypeBits &&
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00001281 (!Op0->getType()->isSigned() || isLeftShift))
Chris Lattnere8d6c602003-03-10 19:16:08 +00001282 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
Chris Lattner55f3d942002-09-10 23:04:09 +00001283
Chris Lattnerede3fe02003-08-13 04:18:28 +00001284 // ((X*C1) << C2) == (X * (C1 << C2))
1285 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
1286 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
1287 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
1288 return BinaryOperator::create(Instruction::Mul, BO->getOperand(0),
1289 *BOOp << *CUI);
1290
1291
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00001292 // If the operand is an bitwise operator with a constant RHS, and the
1293 // shift is the only use, we can pull it out of the shift.
1294 if (Op0->use_size() == 1)
1295 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0))
1296 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
1297 bool isValid = true; // Valid only for And, Or, Xor
1298 bool highBitSet = false; // Transform if high bit of constant set?
1299
1300 switch (Op0BO->getOpcode()) {
1301 default: isValid = false; break; // Do not perform transform!
1302 case Instruction::Or:
1303 case Instruction::Xor:
1304 highBitSet = false;
1305 break;
1306 case Instruction::And:
1307 highBitSet = true;
1308 break;
1309 }
1310
1311 // If this is a signed shift right, and the high bit is modified
1312 // by the logical operation, do not perform the transformation.
1313 // The highBitSet boolean indicates the value of the high bit of
1314 // the constant which would cause it to be modified for this
1315 // operation.
1316 //
1317 if (isValid && !isLeftShift && !I.getType()->isUnsigned()) {
1318 uint64_t Val = Op0C->getRawValue();
1319 isValid = ((Val & (1 << (TypeBits-1))) != 0) == highBitSet;
1320 }
1321
1322 if (isValid) {
1323 Constant *NewRHS =
1324 ConstantFoldShiftInstruction(I.getOpcode(), Op0C, CUI);
1325
1326 Instruction *NewShift =
1327 new ShiftInst(I.getOpcode(), Op0BO->getOperand(0), CUI,
1328 Op0BO->getName());
1329 Op0BO->setName("");
1330 InsertNewInstBefore(NewShift, I);
1331
1332 return BinaryOperator::create(Op0BO->getOpcode(), NewShift,
1333 NewRHS);
1334 }
1335 }
1336
Chris Lattner3204d4e2003-07-24 17:52:58 +00001337 // If this is a shift of a shift, see if we can fold the two together...
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00001338 if (ShiftInst *Op0SI = dyn_cast<ShiftInst>(Op0))
Chris Lattnerab780df2003-07-24 18:38:56 +00001339 if (ConstantUInt *ShiftAmt1C =
1340 dyn_cast<ConstantUInt>(Op0SI->getOperand(1))) {
Chris Lattner3204d4e2003-07-24 17:52:58 +00001341 unsigned ShiftAmt1 = ShiftAmt1C->getValue();
1342 unsigned ShiftAmt2 = CUI->getValue();
1343
1344 // Check for (A << c1) << c2 and (A >> c1) >> c2
1345 if (I.getOpcode() == Op0SI->getOpcode()) {
1346 unsigned Amt = ShiftAmt1+ShiftAmt2; // Fold into one big shift...
1347 return new ShiftInst(I.getOpcode(), Op0SI->getOperand(0),
1348 ConstantUInt::get(Type::UByteTy, Amt));
1349 }
1350
Chris Lattnerab780df2003-07-24 18:38:56 +00001351 // Check for (A << c1) >> c2 or visaversa. If we are dealing with
1352 // signed types, we can only support the (A >> c1) << c2 configuration,
1353 // because it can not turn an arbitrary bit of A into a sign bit.
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00001354 if (I.getType()->isUnsigned() || isLeftShift) {
Chris Lattner3204d4e2003-07-24 17:52:58 +00001355 // Calculate bitmask for what gets shifted off the edge...
1356 Constant *C = ConstantIntegral::getAllOnesValue(I.getType());
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00001357 if (isLeftShift)
Chris Lattner3204d4e2003-07-24 17:52:58 +00001358 C = ConstantExpr::getShift(Instruction::Shl, C, ShiftAmt1C);
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00001359 else
1360 C = ConstantExpr::getShift(Instruction::Shr, C, ShiftAmt1C);
Chris Lattner3204d4e2003-07-24 17:52:58 +00001361
1362 Instruction *Mask =
1363 BinaryOperator::create(Instruction::And, Op0SI->getOperand(0),
1364 C, Op0SI->getOperand(0)->getName()+".mask");
1365 InsertNewInstBefore(Mask, I);
1366
1367 // Figure out what flavor of shift we should use...
1368 if (ShiftAmt1 == ShiftAmt2)
1369 return ReplaceInstUsesWith(I, Mask); // (A << c) >> c === A & c2
1370 else if (ShiftAmt1 < ShiftAmt2) {
1371 return new ShiftInst(I.getOpcode(), Mask,
1372 ConstantUInt::get(Type::UByteTy, ShiftAmt2-ShiftAmt1));
1373 } else {
1374 return new ShiftInst(Op0SI->getOpcode(), Mask,
1375 ConstantUInt::get(Type::UByteTy, ShiftAmt1-ShiftAmt2));
1376 }
1377 }
1378 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001379 }
Chris Lattner2e0fb392002-10-08 16:16:40 +00001380
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001381 return 0;
1382}
1383
1384
Chris Lattner48a44f72002-05-02 17:06:02 +00001385// isEliminableCastOfCast - Return true if it is valid to eliminate the CI
1386// instruction.
1387//
Chris Lattnerdfae8be2003-07-24 17:35:25 +00001388static inline bool isEliminableCastOfCast(const Type *SrcTy, const Type *MidTy,
1389 const Type *DstTy) {
Chris Lattner48a44f72002-05-02 17:06:02 +00001390
Chris Lattner650b6da2002-08-02 20:00:25 +00001391 // It is legal to eliminate the instruction if casting A->B->A if the sizes
1392 // are identical and the bits don't get reinterpreted (for example
Chris Lattner0bb75912002-08-14 23:21:10 +00001393 // int->float->int would not be allowed)
Misha Brukmane5838c42003-05-20 18:45:36 +00001394 if (SrcTy == DstTy && SrcTy->isLosslesslyConvertibleTo(MidTy))
Chris Lattner650b6da2002-08-02 20:00:25 +00001395 return true;
Chris Lattner48a44f72002-05-02 17:06:02 +00001396
1397 // Allow free casting and conversion of sizes as long as the sign doesn't
1398 // change...
Chris Lattnerb0b412e2002-09-03 01:08:28 +00001399 if (SrcTy->isIntegral() && MidTy->isIntegral() && DstTy->isIntegral()) {
Chris Lattner650b6da2002-08-02 20:00:25 +00001400 unsigned SrcSize = SrcTy->getPrimitiveSize();
1401 unsigned MidSize = MidTy->getPrimitiveSize();
1402 unsigned DstSize = DstTy->getPrimitiveSize();
Chris Lattner650b6da2002-08-02 20:00:25 +00001403
Chris Lattner3732aca2002-08-15 16:15:25 +00001404 // Cases where we are monotonically decreasing the size of the type are
1405 // always ok, regardless of what sign changes are going on.
1406 //
Chris Lattner0bb75912002-08-14 23:21:10 +00001407 if (SrcSize >= MidSize && MidSize >= DstSize)
Chris Lattner650b6da2002-08-02 20:00:25 +00001408 return true;
Chris Lattner3732aca2002-08-15 16:15:25 +00001409
Chris Lattner555518c2002-09-23 23:39:43 +00001410 // Cases where the source and destination type are the same, but the middle
1411 // type is bigger are noops.
1412 //
1413 if (SrcSize == DstSize && MidSize > SrcSize)
1414 return true;
1415
Chris Lattner3732aca2002-08-15 16:15:25 +00001416 // If we are monotonically growing, things are more complex.
1417 //
1418 if (SrcSize <= MidSize && MidSize <= DstSize) {
1419 // We have eight combinations of signedness to worry about. Here's the
1420 // table:
1421 static const int SignTable[8] = {
1422 // CODE, SrcSigned, MidSigned, DstSigned, Comment
1423 1, // U U U Always ok
1424 1, // U U S Always ok
1425 3, // U S U Ok iff SrcSize != MidSize
1426 3, // U S S Ok iff SrcSize != MidSize
1427 0, // S U U Never ok
1428 2, // S U S Ok iff MidSize == DstSize
1429 1, // S S U Always ok
1430 1, // S S S Always ok
1431 };
1432
1433 // Choose an action based on the current entry of the signtable that this
1434 // cast of cast refers to...
1435 unsigned Row = SrcTy->isSigned()*4+MidTy->isSigned()*2+DstTy->isSigned();
1436 switch (SignTable[Row]) {
1437 case 0: return false; // Never ok
1438 case 1: return true; // Always ok
1439 case 2: return MidSize == DstSize; // Ok iff MidSize == DstSize
1440 case 3: // Ok iff SrcSize != MidSize
1441 return SrcSize != MidSize || SrcTy == Type::BoolTy;
1442 default: assert(0 && "Bad entry in sign table!");
1443 }
Chris Lattner3732aca2002-08-15 16:15:25 +00001444 }
Chris Lattner650b6da2002-08-02 20:00:25 +00001445 }
Chris Lattner48a44f72002-05-02 17:06:02 +00001446
1447 // Otherwise, we cannot succeed. Specifically we do not want to allow things
1448 // like: short -> ushort -> uint, because this can create wrong results if
1449 // the input short is negative!
1450 //
1451 return false;
1452}
1453
Chris Lattnerdfae8be2003-07-24 17:35:25 +00001454static bool ValueRequiresCast(const Value *V, const Type *Ty) {
1455 if (V->getType() == Ty || isa<Constant>(V)) return false;
1456 if (const CastInst *CI = dyn_cast<CastInst>(V))
1457 if (isEliminableCastOfCast(CI->getOperand(0)->getType(), CI->getType(), Ty))
1458 return false;
1459 return true;
1460}
1461
1462/// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
1463/// InsertBefore instruction. This is specialized a bit to avoid inserting
1464/// casts that are known to not do anything...
1465///
1466Value *InstCombiner::InsertOperandCastBefore(Value *V, const Type *DestTy,
1467 Instruction *InsertBefore) {
1468 if (V->getType() == DestTy) return V;
1469 if (Constant *C = dyn_cast<Constant>(V))
1470 return ConstantExpr::getCast(C, DestTy);
1471
1472 CastInst *CI = new CastInst(V, DestTy, V->getName());
1473 InsertNewInstBefore(CI, *InsertBefore);
1474 return CI;
1475}
Chris Lattner48a44f72002-05-02 17:06:02 +00001476
1477// CastInst simplification
Chris Lattner260ab202002-04-18 17:39:14 +00001478//
Chris Lattner113f4f42002-06-25 16:13:24 +00001479Instruction *InstCombiner::visitCastInst(CastInst &CI) {
Chris Lattner55d4bda2003-06-23 21:59:52 +00001480 Value *Src = CI.getOperand(0);
1481
Chris Lattner48a44f72002-05-02 17:06:02 +00001482 // If the user is casting a value to the same type, eliminate this cast
1483 // instruction...
Chris Lattner55d4bda2003-06-23 21:59:52 +00001484 if (CI.getType() == Src->getType())
1485 return ReplaceInstUsesWith(CI, Src);
Chris Lattner48a44f72002-05-02 17:06:02 +00001486
Chris Lattner48a44f72002-05-02 17:06:02 +00001487 // If casting the result of another cast instruction, try to eliminate this
1488 // one!
1489 //
Chris Lattner55d4bda2003-06-23 21:59:52 +00001490 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) {
Chris Lattnerdfae8be2003-07-24 17:35:25 +00001491 if (isEliminableCastOfCast(CSrc->getOperand(0)->getType(),
1492 CSrc->getType(), CI.getType())) {
Chris Lattner48a44f72002-05-02 17:06:02 +00001493 // This instruction now refers directly to the cast's src operand. This
1494 // has a good chance of making CSrc dead.
Chris Lattner113f4f42002-06-25 16:13:24 +00001495 CI.setOperand(0, CSrc->getOperand(0));
1496 return &CI;
Chris Lattner48a44f72002-05-02 17:06:02 +00001497 }
1498
Chris Lattner650b6da2002-08-02 20:00:25 +00001499 // If this is an A->B->A cast, and we are dealing with integral types, try
1500 // to convert this into a logical 'and' instruction.
1501 //
1502 if (CSrc->getOperand(0)->getType() == CI.getType() &&
Chris Lattnerb0b412e2002-09-03 01:08:28 +00001503 CI.getType()->isInteger() && CSrc->getType()->isInteger() &&
Chris Lattner650b6da2002-08-02 20:00:25 +00001504 CI.getType()->isUnsigned() && CSrc->getType()->isUnsigned() &&
1505 CSrc->getType()->getPrimitiveSize() < CI.getType()->getPrimitiveSize()){
1506 assert(CSrc->getType() != Type::ULongTy &&
1507 "Cannot have type bigger than ulong!");
Chris Lattner196897c2003-05-26 23:41:32 +00001508 uint64_t AndValue = (1ULL << CSrc->getType()->getPrimitiveSize()*8)-1;
Chris Lattner650b6da2002-08-02 20:00:25 +00001509 Constant *AndOp = ConstantUInt::get(CI.getType(), AndValue);
1510 return BinaryOperator::create(Instruction::And, CSrc->getOperand(0),
1511 AndOp);
1512 }
1513 }
1514
Chris Lattnerd0d51602003-06-21 23:12:02 +00001515 // If casting the result of a getelementptr instruction with no offset, turn
1516 // this into a cast of the original pointer!
1517 //
Chris Lattner55d4bda2003-06-23 21:59:52 +00001518 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
Chris Lattnerd0d51602003-06-21 23:12:02 +00001519 bool AllZeroOperands = true;
1520 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i)
1521 if (!isa<Constant>(GEP->getOperand(i)) ||
1522 !cast<Constant>(GEP->getOperand(i))->isNullValue()) {
1523 AllZeroOperands = false;
1524 break;
1525 }
1526 if (AllZeroOperands) {
1527 CI.setOperand(0, GEP->getOperand(0));
1528 return &CI;
1529 }
1530 }
1531
Chris Lattnerdfae8be2003-07-24 17:35:25 +00001532 // If the source value is an instruction with only this use, we can attempt to
1533 // propagate the cast into the instruction. Also, only handle integral types
1534 // for now.
1535 if (Instruction *SrcI = dyn_cast<Instruction>(Src))
1536 if (SrcI->use_size() == 1 && Src->getType()->isIntegral() &&
1537 CI.getType()->isInteger()) { // Don't mess with casts to bool here
1538 const Type *DestTy = CI.getType();
1539 unsigned SrcBitSize = getTypeSizeInBits(Src->getType());
1540 unsigned DestBitSize = getTypeSizeInBits(DestTy);
1541
1542 Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
1543 Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
1544
1545 switch (SrcI->getOpcode()) {
1546 case Instruction::Add:
1547 case Instruction::Mul:
1548 case Instruction::And:
1549 case Instruction::Or:
1550 case Instruction::Xor:
1551 // If we are discarding information, or just changing the sign, rewrite.
1552 if (DestBitSize <= SrcBitSize && DestBitSize != 1) {
1553 // Don't insert two casts if they cannot be eliminated. We allow two
1554 // casts to be inserted if the sizes are the same. This could only be
1555 // converting signedness, which is a noop.
1556 if (DestBitSize == SrcBitSize || !ValueRequiresCast(Op1, DestTy) ||
1557 !ValueRequiresCast(Op0, DestTy)) {
1558 Value *Op0c = InsertOperandCastBefore(Op0, DestTy, SrcI);
1559 Value *Op1c = InsertOperandCastBefore(Op1, DestTy, SrcI);
1560 return BinaryOperator::create(cast<BinaryOperator>(SrcI)
1561 ->getOpcode(), Op0c, Op1c);
1562 }
1563 }
1564 break;
1565 case Instruction::Shl:
1566 // Allow changing the sign of the source operand. Do not allow changing
1567 // the size of the shift, UNLESS the shift amount is a constant. We
1568 // mush not change variable sized shifts to a smaller size, because it
1569 // is undefined to shift more bits out than exist in the value.
1570 if (DestBitSize == SrcBitSize ||
1571 (DestBitSize < SrcBitSize && isa<Constant>(Op1))) {
1572 Value *Op0c = InsertOperandCastBefore(Op0, DestTy, SrcI);
1573 return new ShiftInst(Instruction::Shl, Op0c, Op1);
1574 }
1575 break;
1576 }
1577 }
1578
Chris Lattner260ab202002-04-18 17:39:14 +00001579 return 0;
Chris Lattnerca081252001-12-14 16:52:21 +00001580}
1581
Chris Lattner970c33a2003-06-19 17:00:31 +00001582// CallInst simplification
1583//
1584Instruction *InstCombiner::visitCallInst(CallInst &CI) {
Chris Lattneraec3d942003-10-07 22:32:43 +00001585 return visitCallSite(&CI);
Chris Lattner970c33a2003-06-19 17:00:31 +00001586}
1587
1588// InvokeInst simplification
1589//
1590Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
Chris Lattneraec3d942003-10-07 22:32:43 +00001591 return visitCallSite(&II);
Chris Lattner970c33a2003-06-19 17:00:31 +00001592}
1593
1594// getPromotedType - Return the specified type promoted as it would be to pass
1595// though a va_arg area...
1596static const Type *getPromotedType(const Type *Ty) {
1597 switch (Ty->getPrimitiveID()) {
1598 case Type::SByteTyID:
1599 case Type::ShortTyID: return Type::IntTy;
1600 case Type::UByteTyID:
1601 case Type::UShortTyID: return Type::UIntTy;
1602 case Type::FloatTyID: return Type::DoubleTy;
1603 default: return Ty;
1604 }
1605}
1606
Chris Lattneraec3d942003-10-07 22:32:43 +00001607// visitCallSite - Improvements for call and invoke instructions.
1608//
1609Instruction *InstCombiner::visitCallSite(CallSite CS) {
1610 if (transformConstExprCastCall(CS)) return 0;
1611
1612
1613 return 0;
1614}
1615
Chris Lattner970c33a2003-06-19 17:00:31 +00001616// transformConstExprCastCall - If the callee is a constexpr cast of a function,
1617// attempt to move the cast to the arguments of the call/invoke.
1618//
1619bool InstCombiner::transformConstExprCastCall(CallSite CS) {
1620 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
1621 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
1622 if (CE->getOpcode() != Instruction::Cast ||
1623 !isa<ConstantPointerRef>(CE->getOperand(0)))
1624 return false;
1625 ConstantPointerRef *CPR = cast<ConstantPointerRef>(CE->getOperand(0));
1626 if (!isa<Function>(CPR->getValue())) return false;
1627 Function *Callee = cast<Function>(CPR->getValue());
1628 Instruction *Caller = CS.getInstruction();
1629
1630 // Okay, this is a cast from a function to a different type. Unless doing so
1631 // would cause a type conversion of one of our arguments, change this call to
1632 // be a direct call with arguments casted to the appropriate types.
1633 //
1634 const FunctionType *FT = Callee->getFunctionType();
1635 const Type *OldRetTy = Caller->getType();
1636
1637 if (Callee->isExternal() &&
1638 !OldRetTy->isLosslesslyConvertibleTo(FT->getReturnType()))
1639 return false; // Cannot transform this return value...
1640
1641 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
1642 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
1643
1644 CallSite::arg_iterator AI = CS.arg_begin();
1645 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
1646 const Type *ParamTy = FT->getParamType(i);
1647 bool isConvertible = (*AI)->getType()->isLosslesslyConvertibleTo(ParamTy);
1648 if (Callee->isExternal() && !isConvertible) return false;
1649 }
1650
1651 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
1652 Callee->isExternal())
1653 return false; // Do not delete arguments unless we have a function body...
1654
1655 // Okay, we decided that this is a safe thing to do: go ahead and start
1656 // inserting cast instructions as necessary...
1657 std::vector<Value*> Args;
1658 Args.reserve(NumActualArgs);
1659
1660 AI = CS.arg_begin();
1661 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
1662 const Type *ParamTy = FT->getParamType(i);
1663 if ((*AI)->getType() == ParamTy) {
1664 Args.push_back(*AI);
1665 } else {
1666 Instruction *Cast = new CastInst(*AI, ParamTy, "tmp");
1667 InsertNewInstBefore(Cast, *Caller);
1668 Args.push_back(Cast);
1669 }
1670 }
1671
1672 // If the function takes more arguments than the call was taking, add them
1673 // now...
1674 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
1675 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
1676
1677 // If we are removing arguments to the function, emit an obnoxious warning...
1678 if (FT->getNumParams() < NumActualArgs)
1679 if (!FT->isVarArg()) {
1680 std::cerr << "WARNING: While resolving call to function '"
1681 << Callee->getName() << "' arguments were dropped!\n";
1682 } else {
1683 // Add all of the arguments in their promoted form to the arg list...
1684 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
1685 const Type *PTy = getPromotedType((*AI)->getType());
1686 if (PTy != (*AI)->getType()) {
1687 // Must promote to pass through va_arg area!
1688 Instruction *Cast = new CastInst(*AI, PTy, "tmp");
1689 InsertNewInstBefore(Cast, *Caller);
1690 Args.push_back(Cast);
1691 } else {
1692 Args.push_back(*AI);
1693 }
1694 }
1695 }
1696
1697 if (FT->getReturnType() == Type::VoidTy)
1698 Caller->setName(""); // Void type should not have a name...
1699
1700 Instruction *NC;
1701 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
1702 NC = new InvokeInst(Callee, II->getNormalDest(), II->getExceptionalDest(),
1703 Args, Caller->getName(), Caller);
1704 } else {
1705 NC = new CallInst(Callee, Args, Caller->getName(), Caller);
1706 }
1707
1708 // Insert a cast of the return type as necessary...
1709 Value *NV = NC;
1710 if (Caller->getType() != NV->getType() && !Caller->use_empty()) {
1711 if (NV->getType() != Type::VoidTy) {
1712 NV = NC = new CastInst(NC, Caller->getType(), "tmp");
1713 InsertNewInstBefore(NC, *Caller);
1714 AddUsesToWorkList(*Caller);
1715 } else {
1716 NV = Constant::getNullValue(Caller->getType());
1717 }
1718 }
1719
1720 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
1721 Caller->replaceAllUsesWith(NV);
1722 Caller->getParent()->getInstList().erase(Caller);
1723 removeFromWorkList(Caller);
1724 return true;
1725}
1726
1727
Chris Lattner48a44f72002-05-02 17:06:02 +00001728
Chris Lattnerbbbdd852002-05-06 18:06:38 +00001729// PHINode simplification
1730//
Chris Lattner113f4f42002-06-25 16:13:24 +00001731Instruction *InstCombiner::visitPHINode(PHINode &PN) {
Chris Lattnerbbbdd852002-05-06 18:06:38 +00001732 // If the PHI node only has one incoming value, eliminate the PHI node...
Chris Lattnere6794492002-08-12 21:17:25 +00001733 if (PN.getNumIncomingValues() == 1)
1734 return ReplaceInstUsesWith(PN, PN.getIncomingValue(0));
Chris Lattner9cd1e662002-08-20 15:35:35 +00001735
1736 // Otherwise if all of the incoming values are the same for the PHI, replace
1737 // the PHI node with the incoming value.
1738 //
Chris Lattnerf6c0efa2002-08-22 20:22:01 +00001739 Value *InVal = 0;
1740 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
1741 if (PN.getIncomingValue(i) != &PN) // Not the PHI node itself...
1742 if (InVal && PN.getIncomingValue(i) != InVal)
1743 return 0; // Not the same, bail out.
1744 else
1745 InVal = PN.getIncomingValue(i);
1746
1747 // The only case that could cause InVal to be null is if we have a PHI node
1748 // that only has entries for itself. In this case, there is no entry into the
1749 // loop, so kill the PHI.
1750 //
1751 if (InVal == 0) InVal = Constant::getNullValue(PN.getType());
Chris Lattnerbbbdd852002-05-06 18:06:38 +00001752
Chris Lattner9cd1e662002-08-20 15:35:35 +00001753 // All of the incoming values are the same, replace the PHI node now.
1754 return ReplaceInstUsesWith(PN, InVal);
Chris Lattnerbbbdd852002-05-06 18:06:38 +00001755}
1756
Chris Lattner48a44f72002-05-02 17:06:02 +00001757
Chris Lattner113f4f42002-06-25 16:13:24 +00001758Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
Chris Lattner471bd762003-05-22 19:07:21 +00001759 // Is it 'getelementptr %P, long 0' or 'getelementptr %P'
Chris Lattner113f4f42002-06-25 16:13:24 +00001760 // If so, eliminate the noop.
Chris Lattnerae7a0d32002-08-02 19:29:35 +00001761 if ((GEP.getNumOperands() == 2 &&
Chris Lattner136dab72002-09-11 01:21:33 +00001762 GEP.getOperand(1) == Constant::getNullValue(Type::LongTy)) ||
Chris Lattnere6794492002-08-12 21:17:25 +00001763 GEP.getNumOperands() == 1)
1764 return ReplaceInstUsesWith(GEP, GEP.getOperand(0));
Chris Lattner48a44f72002-05-02 17:06:02 +00001765
Chris Lattnerae7a0d32002-08-02 19:29:35 +00001766 // Combine Indices - If the source pointer to this getelementptr instruction
1767 // is a getelementptr instruction, combine the indices of the two
1768 // getelementptr instructions into a single instruction.
1769 //
Chris Lattnerc59af1d2002-08-17 22:21:59 +00001770 if (GetElementPtrInst *Src = dyn_cast<GetElementPtrInst>(GEP.getOperand(0))) {
Chris Lattnerae7a0d32002-08-02 19:29:35 +00001771 std::vector<Value *> Indices;
Chris Lattnerca081252001-12-14 16:52:21 +00001772
Chris Lattnerae7a0d32002-08-02 19:29:35 +00001773 // Can we combine the two pointer arithmetics offsets?
Chris Lattner471bd762003-05-22 19:07:21 +00001774 if (Src->getNumOperands() == 2 && isa<Constant>(Src->getOperand(1)) &&
1775 isa<Constant>(GEP.getOperand(1))) {
Chris Lattner235af562003-03-05 22:33:14 +00001776 // Replace: gep (gep %P, long C1), long C2, ...
1777 // With: gep %P, long (C1+C2), ...
Chris Lattner34428442003-05-27 16:40:51 +00001778 Value *Sum = ConstantExpr::get(Instruction::Add,
1779 cast<Constant>(Src->getOperand(1)),
1780 cast<Constant>(GEP.getOperand(1)));
Chris Lattner235af562003-03-05 22:33:14 +00001781 assert(Sum && "Constant folding of longs failed!?");
1782 GEP.setOperand(0, Src->getOperand(0));
1783 GEP.setOperand(1, Sum);
1784 AddUsesToWorkList(*Src); // Reduce use count of Src
1785 return &GEP;
Chris Lattner471bd762003-05-22 19:07:21 +00001786 } else if (Src->getNumOperands() == 2) {
Chris Lattner235af562003-03-05 22:33:14 +00001787 // Replace: gep (gep %P, long B), long A, ...
1788 // With: T = long A+B; gep %P, T, ...
1789 //
1790 Value *Sum = BinaryOperator::create(Instruction::Add, Src->getOperand(1),
1791 GEP.getOperand(1),
1792 Src->getName()+".sum", &GEP);
1793 GEP.setOperand(0, Src->getOperand(0));
1794 GEP.setOperand(1, Sum);
1795 WorkList.push_back(cast<Instruction>(Sum));
1796 return &GEP;
Chris Lattner5d606a02002-11-04 16:43:32 +00001797 } else if (*GEP.idx_begin() == Constant::getNullValue(Type::LongTy) &&
Chris Lattnera8339e32002-09-17 21:05:42 +00001798 Src->getNumOperands() != 1) {
Chris Lattnerae7a0d32002-08-02 19:29:35 +00001799 // Otherwise we can do the fold if the first index of the GEP is a zero
1800 Indices.insert(Indices.end(), Src->idx_begin(), Src->idx_end());
1801 Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
Chris Lattner5d606a02002-11-04 16:43:32 +00001802 } else if (Src->getOperand(Src->getNumOperands()-1) ==
1803 Constant::getNullValue(Type::LongTy)) {
1804 // If the src gep ends with a constant array index, merge this get into
1805 // it, even if we have a non-zero array index.
1806 Indices.insert(Indices.end(), Src->idx_begin(), Src->idx_end()-1);
1807 Indices.insert(Indices.end(), GEP.idx_begin(), GEP.idx_end());
Chris Lattnerae7a0d32002-08-02 19:29:35 +00001808 }
1809
1810 if (!Indices.empty())
1811 return new GetElementPtrInst(Src->getOperand(0), Indices, GEP.getName());
Chris Lattnerc59af1d2002-08-17 22:21:59 +00001812
1813 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(GEP.getOperand(0))) {
1814 // GEP of global variable. If all of the indices for this GEP are
1815 // constants, we can promote this to a constexpr instead of an instruction.
1816
1817 // Scan for nonconstants...
1818 std::vector<Constant*> Indices;
1819 User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
1820 for (; I != E && isa<Constant>(*I); ++I)
1821 Indices.push_back(cast<Constant>(*I));
1822
1823 if (I == E) { // If they are all constants...
Chris Lattner46b3d302003-04-16 22:40:51 +00001824 Constant *CE =
Chris Lattnerc59af1d2002-08-17 22:21:59 +00001825 ConstantExpr::getGetElementPtr(ConstantPointerRef::get(GV), Indices);
1826
1827 // Replace all uses of the GEP with the new constexpr...
1828 return ReplaceInstUsesWith(GEP, CE);
1829 }
Chris Lattnerca081252001-12-14 16:52:21 +00001830 }
1831
Chris Lattnerca081252001-12-14 16:52:21 +00001832 return 0;
1833}
1834
Chris Lattner1085bdf2002-11-04 16:18:53 +00001835Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
1836 // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
1837 if (AI.isArrayAllocation()) // Check C != 1
1838 if (const ConstantUInt *C = dyn_cast<ConstantUInt>(AI.getArraySize())) {
1839 const Type *NewTy = ArrayType::get(AI.getAllocatedType(), C->getValue());
Chris Lattnera2620ac2002-11-09 00:49:43 +00001840 AllocationInst *New = 0;
Chris Lattner1085bdf2002-11-04 16:18:53 +00001841
1842 // Create and insert the replacement instruction...
1843 if (isa<MallocInst>(AI))
1844 New = new MallocInst(NewTy, 0, AI.getName(), &AI);
Chris Lattnera2620ac2002-11-09 00:49:43 +00001845 else {
1846 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
Chris Lattner1085bdf2002-11-04 16:18:53 +00001847 New = new AllocaInst(NewTy, 0, AI.getName(), &AI);
Chris Lattnera2620ac2002-11-09 00:49:43 +00001848 }
Chris Lattner1085bdf2002-11-04 16:18:53 +00001849
1850 // Scan to the end of the allocation instructions, to skip over a block of
1851 // allocas if possible...
1852 //
1853 BasicBlock::iterator It = New;
1854 while (isa<AllocationInst>(*It)) ++It;
1855
1856 // Now that I is pointing to the first non-allocation-inst in the block,
1857 // insert our getelementptr instruction...
1858 //
1859 std::vector<Value*> Idx(2, Constant::getNullValue(Type::LongTy));
1860 Value *V = new GetElementPtrInst(New, Idx, New->getName()+".sub", It);
1861
1862 // Now make everything use the getelementptr instead of the original
1863 // allocation.
1864 ReplaceInstUsesWith(AI, V);
1865 return &AI;
1866 }
1867 return 0;
1868}
1869
Chris Lattner0f1d8a32003-06-26 05:06:25 +00001870/// GetGEPGlobalInitializer - Given a constant, and a getelementptr
1871/// constantexpr, return the constant value being addressed by the constant
1872/// expression, or null if something is funny.
1873///
1874static Constant *GetGEPGlobalInitializer(Constant *C, ConstantExpr *CE) {
1875 if (CE->getOperand(1) != Constant::getNullValue(Type::LongTy))
1876 return 0; // Do not allow stepping over the value!
1877
1878 // Loop over all of the operands, tracking down which value we are
1879 // addressing...
1880 for (unsigned i = 2, e = CE->getNumOperands(); i != e; ++i)
1881 if (ConstantUInt *CU = dyn_cast<ConstantUInt>(CE->getOperand(i))) {
1882 ConstantStruct *CS = cast<ConstantStruct>(C);
1883 if (CU->getValue() >= CS->getValues().size()) return 0;
1884 C = cast<Constant>(CS->getValues()[CU->getValue()]);
1885 } else if (ConstantSInt *CS = dyn_cast<ConstantSInt>(CE->getOperand(i))) {
1886 ConstantArray *CA = cast<ConstantArray>(C);
1887 if ((uint64_t)CS->getValue() >= CA->getValues().size()) return 0;
1888 C = cast<Constant>(CA->getValues()[CS->getValue()]);
1889 } else
1890 return 0;
1891 return C;
1892}
1893
1894Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
1895 Value *Op = LI.getOperand(0);
1896 if (ConstantPointerRef *CPR = dyn_cast<ConstantPointerRef>(Op))
1897 Op = CPR->getValue();
1898
1899 // Instcombine load (constant global) into the value loaded...
1900 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
Chris Lattnerbdb0ce02003-07-22 21:46:59 +00001901 if (GV->isConstant() && !GV->isExternal())
Chris Lattner0f1d8a32003-06-26 05:06:25 +00001902 return ReplaceInstUsesWith(LI, GV->getInitializer());
1903
1904 // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded...
1905 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op))
1906 if (CE->getOpcode() == Instruction::GetElementPtr)
1907 if (ConstantPointerRef *G=dyn_cast<ConstantPointerRef>(CE->getOperand(0)))
1908 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(G->getValue()))
Chris Lattnerbdb0ce02003-07-22 21:46:59 +00001909 if (GV->isConstant() && !GV->isExternal())
Chris Lattner0f1d8a32003-06-26 05:06:25 +00001910 if (Constant *V = GetGEPGlobalInitializer(GV->getInitializer(), CE))
1911 return ReplaceInstUsesWith(LI, V);
1912 return 0;
1913}
1914
1915
Chris Lattner9eef8a72003-06-04 04:46:00 +00001916Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
1917 // Change br (not X), label True, label False to: br X, label False, True
Chris Lattner45789ac2003-06-05 20:12:51 +00001918 if (BI.isConditional() && !isa<Constant>(BI.getCondition()))
Chris Lattnere967b342003-06-04 05:10:11 +00001919 if (Value *V = dyn_castNotVal(BI.getCondition())) {
1920 BasicBlock *TrueDest = BI.getSuccessor(0);
1921 BasicBlock *FalseDest = BI.getSuccessor(1);
1922 // Swap Destinations and condition...
1923 BI.setCondition(V);
1924 BI.setSuccessor(0, FalseDest);
1925 BI.setSuccessor(1, TrueDest);
1926 return &BI;
1927 }
Chris Lattner9eef8a72003-06-04 04:46:00 +00001928 return 0;
1929}
Chris Lattner1085bdf2002-11-04 16:18:53 +00001930
Chris Lattnerca081252001-12-14 16:52:21 +00001931
Chris Lattner99f48c62002-09-02 04:59:56 +00001932void InstCombiner::removeFromWorkList(Instruction *I) {
1933 WorkList.erase(std::remove(WorkList.begin(), WorkList.end(), I),
1934 WorkList.end());
1935}
1936
Chris Lattner113f4f42002-06-25 16:13:24 +00001937bool InstCombiner::runOnFunction(Function &F) {
Chris Lattner260ab202002-04-18 17:39:14 +00001938 bool Changed = false;
Chris Lattnerca081252001-12-14 16:52:21 +00001939
Chris Lattner260ab202002-04-18 17:39:14 +00001940 WorkList.insert(WorkList.end(), inst_begin(F), inst_end(F));
Chris Lattnerca081252001-12-14 16:52:21 +00001941
1942 while (!WorkList.empty()) {
1943 Instruction *I = WorkList.back(); // Get an instruction from the worklist
1944 WorkList.pop_back();
1945
Misha Brukman632df282002-10-29 23:06:16 +00001946 // Check to see if we can DCE or ConstantPropagate the instruction...
Chris Lattner99f48c62002-09-02 04:59:56 +00001947 // Check to see if we can DIE the instruction...
1948 if (isInstructionTriviallyDead(I)) {
1949 // Add operands to the worklist...
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00001950 if (I->getNumOperands() < 4)
1951 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
1952 if (Instruction *Op = dyn_cast<Instruction>(I->getOperand(i)))
1953 WorkList.push_back(Op);
Chris Lattner99f48c62002-09-02 04:59:56 +00001954 ++NumDeadInst;
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00001955
1956 I->getParent()->getInstList().erase(I);
1957 removeFromWorkList(I);
1958 continue;
1959 }
Chris Lattner99f48c62002-09-02 04:59:56 +00001960
Misha Brukman632df282002-10-29 23:06:16 +00001961 // Instruction isn't dead, see if we can constant propagate it...
Chris Lattner99f48c62002-09-02 04:59:56 +00001962 if (Constant *C = ConstantFoldInstruction(I)) {
1963 // Add operands to the worklist...
1964 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
1965 if (Instruction *Op = dyn_cast<Instruction>(I->getOperand(i)))
1966 WorkList.push_back(Op);
Chris Lattnerc6509f42002-12-05 22:41:53 +00001967 ReplaceInstUsesWith(*I, C);
1968
Chris Lattner99f48c62002-09-02 04:59:56 +00001969 ++NumConstProp;
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00001970 I->getParent()->getInstList().erase(I);
Chris Lattner800aaaf2003-10-07 15:17:02 +00001971 removeFromWorkList(I);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00001972 continue;
Chris Lattner99f48c62002-09-02 04:59:56 +00001973 }
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00001974
Chris Lattnerca081252001-12-14 16:52:21 +00001975 // Now that we have an instruction, try combining it to simplify it...
Chris Lattnerae7a0d32002-08-02 19:29:35 +00001976 if (Instruction *Result = visit(*I)) {
Chris Lattner0b18c1d2002-05-10 15:38:35 +00001977 ++NumCombined;
Chris Lattner260ab202002-04-18 17:39:14 +00001978 // Should we replace the old instruction with a new one?
Chris Lattner053c0932002-05-14 15:24:07 +00001979 if (Result != I) {
1980 // Instructions can end up on the worklist more than once. Make sure
1981 // we do not process an instruction that has been deleted.
Chris Lattner99f48c62002-09-02 04:59:56 +00001982 removeFromWorkList(I);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00001983
1984 // Move the name to the new instruction first...
1985 std::string OldName = I->getName(); I->setName("");
1986 Result->setName(I->getName());
1987
1988 // Insert the new instruction into the basic block...
1989 BasicBlock *InstParent = I->getParent();
1990 InstParent->getInstList().insert(I, Result);
1991
1992 // Everything uses the new instruction now...
1993 I->replaceAllUsesWith(Result);
1994
1995 // Erase the old instruction.
1996 InstParent->getInstList().erase(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00001997 } else {
Chris Lattnerae7a0d32002-08-02 19:29:35 +00001998 BasicBlock::iterator II = I;
1999
2000 // If the instruction was modified, it's possible that it is now dead.
2001 // if so, remove it.
2002 if (dceInstruction(II)) {
2003 // Instructions may end up in the worklist more than once. Erase them
2004 // all.
Chris Lattner99f48c62002-09-02 04:59:56 +00002005 removeFromWorkList(I);
Chris Lattnerae7a0d32002-08-02 19:29:35 +00002006 Result = 0;
2007 }
Chris Lattner053c0932002-05-14 15:24:07 +00002008 }
Chris Lattner260ab202002-04-18 17:39:14 +00002009
Chris Lattnerae7a0d32002-08-02 19:29:35 +00002010 if (Result) {
2011 WorkList.push_back(Result);
2012 AddUsesToWorkList(*Result);
2013 }
Chris Lattner260ab202002-04-18 17:39:14 +00002014 Changed = true;
Chris Lattnerca081252001-12-14 16:52:21 +00002015 }
2016 }
2017
Chris Lattner260ab202002-04-18 17:39:14 +00002018 return Changed;
Chris Lattner04805fa2002-02-26 21:46:54 +00002019}
2020
2021Pass *createInstructionCombiningPass() {
Chris Lattner260ab202002-04-18 17:39:14 +00002022 return new InstCombiner();
Chris Lattner04805fa2002-02-26 21:46:54 +00002023}